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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d86b31ad8ff1b0ae3aead31b19c2fe7da4941a0 | [
"res = False\nif not nums:\n return False\npivot = self.find_pivot(nums, 0, len(nums) - 1)\nif pivot == -1 or pivot == len(nums) - 1:\n res = self.binary_search(nums, target, 0, len(nums) - 1)\nelif nums[pivot] == target:\n res = pivot\nelif nums[0] <= target:\n res = self.binary_search(nums, target, 0,... | <|body_start_0|>
res = False
if not nums:
return False
pivot = self.find_pivot(nums, 0, len(nums) - 1)
if pivot == -1 or pivot == len(nums) - 1:
res = self.binary_search(nums, target, 0, len(nums) - 1)
elif nums[pivot] == target:
res = pivot
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def binary_search(self, nums, target, low, high):
"""Standard binary search in an array with distinct elements :param nums: :param target: :param low: :para... | stack_v2_sparse_classes_36k_train_007600 | 5,178 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": "Standard binary search in an array with distinct elements :param nums: :param target: :param low: :param high: :return:",
"name": "binary_s... | 4 | stack_v2_sparse_classes_30k_test_001006 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def binary_search(self, nums, target, low, high): Standard binary search in an array with di... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def binary_search(self, nums, target, low, high): Standard binary search in an array with di... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def binary_search(self, nums, target, low, high):
"""Standard binary search in an array with distinct elements :param nums: :param target: :param low: :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
res = False
if not nums:
return False
pivot = self.find_pivot(nums, 0, len(nums) - 1)
if pivot == -1 or pivot == len(nums) - 1:
res = self.binary_... | the_stack_v2_python_sparse | algo/binary_search/search_in_rotated_array_II.py | xys234/coding-problems | train | 0 | |
5c8312e9e7718cbbd74017e1e7eafacbb639016b | [
"fsa_filename = './TestFiles/fsa1'\nwith open(fsa_filename, 'r') as fsa_file:\n fsa_rules = fsa_file.readlines()\nacceptor = FSAAcceptor(fsa_rules)\nself.assertTrue(acceptor.can_accept_string(self.test_string1))\nself.assertTrue(acceptor.can_accept_string(self.test_string2))\nself.assertTrue(acceptor.can_accept_... | <|body_start_0|>
fsa_filename = './TestFiles/fsa1'
with open(fsa_filename, 'r') as fsa_file:
fsa_rules = fsa_file.readlines()
acceptor = FSAAcceptor(fsa_rules)
self.assertTrue(acceptor.can_accept_string(self.test_string1))
self.assertTrue(acceptor.can_accept_string(se... | This class contains tests for the FSAAcceptor class | TestFSAAcceptor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFSAAcceptor:
"""This class contains tests for the FSAAcceptor class"""
def test_fsa1(self):
"""Tests for FSA1 :return: void"""
<|body_0|>
def test_fsa2(self):
"""Tests for FSA2 :return: void"""
<|body_1|>
def test_fsa3(self):
"""Tests for... | stack_v2_sparse_classes_36k_train_007601 | 6,573 | no_license | [
{
"docstring": "Tests for FSA1 :return: void",
"name": "test_fsa1",
"signature": "def test_fsa1(self)"
},
{
"docstring": "Tests for FSA2 :return: void",
"name": "test_fsa2",
"signature": "def test_fsa2(self)"
},
{
"docstring": "Tests for FSA3 :return: void",
"name": "test_fsa... | 4 | stack_v2_sparse_classes_30k_train_016539 | Implement the Python class `TestFSAAcceptor` described below.
Class description:
This class contains tests for the FSAAcceptor class
Method signatures and docstrings:
- def test_fsa1(self): Tests for FSA1 :return: void
- def test_fsa2(self): Tests for FSA2 :return: void
- def test_fsa3(self): Tests for FSA3 :return: ... | Implement the Python class `TestFSAAcceptor` described below.
Class description:
This class contains tests for the FSAAcceptor class
Method signatures and docstrings:
- def test_fsa1(self): Tests for FSA1 :return: void
- def test_fsa2(self): Tests for FSA2 :return: void
- def test_fsa3(self): Tests for FSA3 :return: ... | 7af7b357347ed526de7a3d6f16652843d214dcbf | <|skeleton|>
class TestFSAAcceptor:
"""This class contains tests for the FSAAcceptor class"""
def test_fsa1(self):
"""Tests for FSA1 :return: void"""
<|body_0|>
def test_fsa2(self):
"""Tests for FSA2 :return: void"""
<|body_1|>
def test_fsa3(self):
"""Tests for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFSAAcceptor:
"""This class contains tests for the FSAAcceptor class"""
def test_fsa1(self):
"""Tests for FSA1 :return: void"""
fsa_filename = './TestFiles/fsa1'
with open(fsa_filename, 'r') as fsa_file:
fsa_rules = fsa_file.readlines()
acceptor = FSAAccepto... | the_stack_v2_python_sparse | FiniteStateMachines/FSAAcceptor/fsa_acceptor.py | zoew2/Projects | train | 0 |
42491cf5dd3676d7c9bc778ca333603de60a928c | [
"if len(nums) == 0:\n return 0\nif len(nums) == 1:\n return nums[0]\nif len(nums) == 2:\n return max(nums[0], nums[1])\nif len(nums) == 3:\n return max(nums[0], nums[1], nums[2])\nelse:\n dp = [0 for col in range(len(nums))]\n dp[0] = nums[0]\n dp[1] = max(nums[0], nums[1])\n dp[2] = max(num... | <|body_start_0|>
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
if len(nums) == 3:
return max(nums[0], nums[1], nums[2])
else:
dp = [0 for col in range(len(n... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) == 0:
return 0
if len(nums)... | stack_v2_sparse_classes_36k_train_007602 | 1,320 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_",
"signature": "def rob_(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011959 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
"... | e00ebc7d83583ffd26c53f48efdd27ebc76a9623 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
if len(nums) == 3:
return max(nums[0], nu... | the_stack_v2_python_sparse | 213_House-Robber-II.py | Coalin/Daily-LeetCode-Exercise | train | 4 | |
792244baeaa9e7bccfc5bf7e7dde918344244f09 | [
"easy = set()\nfor i in nums:\n easy.add(i)\nfor i in xrange(len(nums)):\n if i not in easy:\n return i\nreturn len(nums)",
"missing = len(nums)\nfor i, num in enumerate(nums):\n missing ^= i ^ num\nreturn missing"
] | <|body_start_0|>
easy = set()
for i in nums:
easy.add(i)
for i in xrange(len(nums)):
if i not in easy:
return i
return len(nums)
<|end_body_0|>
<|body_start_1|>
missing = len(nums)
for i, num in enumerate(nums):
missing... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberConstantMemory(self, nums):
"""if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: L... | stack_v2_sparse_classes_36k_train_007603 | 881 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumber",
"signature": "def missingNumber(self, nums)"
},
{
"docstring": "if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: List[int] :rtype: int",
"... | 2 | stack_v2_sparse_classes_30k_train_009701 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberConstantMemory(self, nums): if we initialize an integer to nn and XOR it with every index and ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumber(self, nums): :type nums: List[int] :rtype: int
- def missingNumberConstantMemory(self, nums): if we initialize an integer to nn and XOR it with every index and ... | 2f7df25d0d735f726b7012e4aa2417dee50526d9 | <|skeleton|>
class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberConstantMemory(self, nums):
"""if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. :type nums: L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumber(self, nums):
""":type nums: List[int] :rtype: int"""
easy = set()
for i in nums:
easy.add(i)
for i in xrange(len(nums)):
if i not in easy:
return i
return len(nums)
def missingNumberConstantMemory(... | the_stack_v2_python_sparse | leetcode/arrays/missing_number.py | marquesarthur/programming_problems | train | 2 | |
067eaeb44191cd205b879e540524ca606d7c3b04 | [
"self.encoder = encoder\nself.dataset = dataset\nself.path = path\nself.batch_size = batch_size\nself.topo = topo",
"if self.batch_size is None:\n if self.topo:\n data = self.dataset.get_topological_view()\n else:\n data = self.dataset.get_design_matrix()\n output = self.encoder.perform(dat... | <|body_start_0|>
self.encoder = encoder
self.dataset = dataset
self.path = path
self.batch_size = batch_size
self.topo = topo
<|end_body_0|>
<|body_start_1|>
if self.batch_size is None:
if self.topo:
data = self.dataset.get_topological_view()
... | .. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME | FeatureDump | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
<|body_0|>
def main_loop(sel... | stack_v2_sparse_classes_36k_train_007604 | 8,573 | permissive | [
{
"docstring": ".. todo:: WRITEME",
"name": "__init__",
"signature": "def __init__(self, encoder, dataset, path, batch_size=None, topo=False)"
},
{
"docstring": ".. todo:: WRITEME Parameters ---------- **kwargs : dict, optional WRITEME",
"name": "main_loop",
"signature": "def main_loop(s... | 2 | stack_v2_sparse_classes_30k_train_013419 | Implement the Python class `FeatureDump` described below.
Class description:
.. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME
Method signatures and docstrings:
- def __init__(self, encoder, dataset, path, batch_size=None, topo=False): .. to... | Implement the Python class `FeatureDump` described below.
Class description:
.. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME
Method signatures and docstrings:
- def __init__(self, encoder, dataset, path, batch_size=None, topo=False): .. to... | 96edb376ced1b828962c749240059903686da549 | <|skeleton|>
class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
<|body_0|>
def main_loop(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureDump:
""".. todo:: WRITEME Parameters ---------- encoder : WRITEME dataset : WRITEME path : WRITEME batch_size : WRITEME topo : WRITEME"""
def __init__(self, encoder, dataset, path, batch_size=None, topo=False):
""".. todo:: WRITEME"""
self.encoder = encoder
self.dataset = ... | the_stack_v2_python_sparse | pylearn2/scripts/train.py | Coderx7/pylearn2 | train | 1 |
4919799fe8d39ff040812edc53f90913a320e728 | [
"if isinstance(layer, (tf.keras.layers.Conv2DTranspose, tf.keras.layers.DepthwiseConv2D)):\n transposed_tensor = tensor.transpose((2, 3, 0, 1))\nelif isinstance(layer, tf.keras.layers.Conv2D):\n transposed_tensor = tensor.transpose((2, 3, 1, 0))\nelse:\n raise ValueError(\"Only Conv2D or it's subclass is c... | <|body_start_0|>
if isinstance(layer, (tf.keras.layers.Conv2DTranspose, tf.keras.layers.DepthwiseConv2D)):
transposed_tensor = tensor.transpose((2, 3, 0, 1))
elif isinstance(layer, tf.keras.layers.Conv2D):
transposed_tensor = tensor.transpose((2, 3, 1, 0))
else:
... | Utility class to handle weight tensor | WeightTensorUtils | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightTensorUtils:
"""Utility class to handle weight tensor"""
def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray:
"""Transpose the weight tensor shape from libpymo format to TensorFlow format"""
<|body_0|>
def transpo... | stack_v2_sparse_classes_36k_train_007605 | 6,180 | permissive | [
{
"docstring": "Transpose the weight tensor shape from libpymo format to TensorFlow format",
"name": "transpose_from_libpymo_to_tf_format",
"signature": "def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray"
},
{
"docstring": "Transpose the weig... | 4 | stack_v2_sparse_classes_30k_train_008437 | Implement the Python class `WeightTensorUtils` described below.
Class description:
Utility class to handle weight tensor
Method signatures and docstrings:
- def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray: Transpose the weight tensor shape from libpymo format to... | Implement the Python class `WeightTensorUtils` described below.
Class description:
Utility class to handle weight tensor
Method signatures and docstrings:
- def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray: Transpose the weight tensor shape from libpymo format to... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class WeightTensorUtils:
"""Utility class to handle weight tensor"""
def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray:
"""Transpose the weight tensor shape from libpymo format to TensorFlow format"""
<|body_0|>
def transpo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightTensorUtils:
"""Utility class to handle weight tensor"""
def transpose_from_libpymo_to_tf_format(tensor: np.ndarray, layer: tf.keras.layers.Layer) -> np.ndarray:
"""Transpose the weight tensor shape from libpymo format to TensorFlow format"""
if isinstance(layer, (tf.keras.layers.Co... | the_stack_v2_python_sparse | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/keras/utils/weight_tensor_utils.py | quic/aimet | train | 1,676 |
3209264a156c4f4301db91d81eb58a26beb0c1ff | [
"if (serial_no := data_service.serial_no) is not None:\n self._attr_unique_id = f'{serial_no}_{description.key}'\nself._attr_device_info = data_service.device_info\nself.entity_description = description\nself._data_service = data_service",
"try:\n self._data_service.update()\nexcept OSError as ex:\n if s... | <|body_start_0|>
if (serial_no := data_service.serial_no) is not None:
self._attr_unique_id = f'{serial_no}_{description.key}'
self._attr_device_info = data_service.device_info
self.entity_description = description
self._data_service = data_service
<|end_body_0|>
<|body_star... | Representation of a sensor entity for APCUPSd status values. | APCUPSdSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APCUPSdSensor:
"""Representation of a sensor entity for APCUPSd status values."""
def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the latest stat... | stack_v2_sparse_classes_36k_train_007606 | 17,047 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None"
},
{
"docstring": "Get the latest status and use it to update our sensor state.",
"name": "update",
"signature": "def up... | 2 | null | Implement the Python class `APCUPSdSensor` described below.
Class description:
Representation of a sensor entity for APCUPSd status values.
Method signatures and docstrings:
- def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> None... | Implement the Python class `APCUPSdSensor` described below.
Class description:
Representation of a sensor entity for APCUPSd status values.
Method signatures and docstrings:
- def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None: Initialize the sensor.
- def update(self) -> None... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class APCUPSdSensor:
"""Representation of a sensor entity for APCUPSd status values."""
def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update(self) -> None:
"""Get the latest stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APCUPSdSensor:
"""Representation of a sensor entity for APCUPSd status values."""
def __init__(self, data_service: APCUPSdData, description: SensorEntityDescription) -> None:
"""Initialize the sensor."""
if (serial_no := data_service.serial_no) is not None:
self._attr_unique_i... | the_stack_v2_python_sparse | homeassistant/components/apcupsd/sensor.py | home-assistant/core | train | 35,501 |
d1fb5f84538822f6219b18608e3ece32372eef08 | [
"super().__init__(max_n_sources)\nif use_band is None and (not use_mean):\n raise ValueError(\"Either set 'use_mean=True' OR indicate a 'use_band' index\")\nif use_band is not None and use_mean:\n raise ValueError(\"Only one of the parameters 'use_band' and 'use_mean' has to be set\")\nself.use_mean = use_mea... | <|body_start_0|>
super().__init__(max_n_sources)
if use_band is None and (not use_mean):
raise ValueError("Either set 'use_mean=True' OR indicate a 'use_band' index")
if use_band is not None and use_mean:
raise ValueError("Only one of the parameters 'use_band' and 'use_me... | Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average of all the bands. For more details on SEP (Source-Extractor Python), see: https:/... | SepSingleBand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SepSingleBand:
"""Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average of all the bands. For more details on SE... | stack_v2_sparse_classes_36k_train_007607 | 24,907 | permissive | [
{
"docstring": "Initializes measurement class. Exactly one of 'use_mean' or 'use_band' must be specified. Args: max_n_sources: See parent class. thresh: Threshold pixel value for detection use in `sep.extract`. This is interpreted as a relative threshold: the absolute threshold at pixel (j, i) will be `thresh *... | 2 | stack_v2_sparse_classes_30k_train_015415 | Implement the Python class `SepSingleBand` described below.
Class description:
Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average o... | Implement the Python class `SepSingleBand` described below.
Class description:
Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average o... | f5b716a373f130238100db8980aa0d282822983a | <|skeleton|>
class SepSingleBand:
"""Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average of all the bands. For more details on SE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SepSingleBand:
"""Return detection, segmentation and deblending information running SEP on a single band. The function performs detection and deblending of the sources based on the provided band index. If `use_mean` feature is used, then we use the average of all the bands. For more details on SEP (Source-Ext... | the_stack_v2_python_sparse | btk/deblend.py | LSSTDESC/BlendingToolKit | train | 22 |
9c7aeaa34b6357478e34a30801698e9006531ed5 | [
"feature_data = image_data(self.inputs.t1_file, 'T1', additional_images=self.inputs.additional_files)\ngm_classifier = joblib.load(self.inputs.gm_classifier_file)\ngm_probability_array = gm_classifier.predict_proba(feature_data.values)[:, 1]\ndel gm_classifier\ngm_probability_image = image_file_from_array_with_refe... | <|body_start_0|>
feature_data = image_data(self.inputs.t1_file, 'T1', additional_images=self.inputs.additional_files)
gm_classifier = joblib.load(self.inputs.gm_classifier_file)
gm_probability_array = gm_classifier.predict_proba(feature_data.values)[:, 1]
del gm_classifier
gm_pro... | This class represents a... | PredictEdgeProbability | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictEdgeProbability:
"""This class represents a..."""
def _run_interface(self, runtime):
"""This function... :param runtime: :return:"""
<|body_0|>
def _list_outputs(self):
"""This function... :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007608 | 13,234 | permissive | [
{
"docstring": "This function... :param runtime: :return:",
"name": "_run_interface",
"signature": "def _run_interface(self, runtime)"
},
{
"docstring": "This function... :return:",
"name": "_list_outputs",
"signature": "def _list_outputs(self)"
}
] | 2 | null | Implement the Python class `PredictEdgeProbability` described below.
Class description:
This class represents a...
Method signatures and docstrings:
- def _run_interface(self, runtime): This function... :param runtime: :return:
- def _list_outputs(self): This function... :return: | Implement the Python class `PredictEdgeProbability` described below.
Class description:
This class represents a...
Method signatures and docstrings:
- def _run_interface(self, runtime): This function... :param runtime: :return:
- def _list_outputs(self): This function... :return:
<|skeleton|>
class PredictEdgeProbab... | 64bb590918a188b660225e44ae54c1072f3a8056 | <|skeleton|>
class PredictEdgeProbability:
"""This class represents a..."""
def _run_interface(self, runtime):
"""This function... :param runtime: :return:"""
<|body_0|>
def _list_outputs(self):
"""This function... :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictEdgeProbability:
"""This class represents a..."""
def _run_interface(self, runtime):
"""This function... :param runtime: :return:"""
feature_data = image_data(self.inputs.t1_file, 'T1', additional_images=self.inputs.additional_files)
gm_classifier = joblib.load(self.inputs.... | the_stack_v2_python_sparse | AutoWorkup/logismosb/maclearn/nipype_interfaces.py | BRAINSia/BRAINSTools | train | 101 |
edde1ec42183c321e92772119e244b10306dee66 | [
"if isinstance(v, str):\n return v\nif isinstance(v, list):\n return json.dumps(v, cls=JsonEncoder)\nraise TypeError(f'unexpected type {type(v)}; permitted: Optional[Union[List[Dict[str, Any]], str]]')",
"if isinstance(v, list):\n return v\nif isinstance(v, dict):\n return [{'Key': k, 'Value': v} for ... | <|body_start_0|>
if isinstance(v, str):
return v
if isinstance(v, list):
return json.dumps(v, cls=JsonEncoder)
raise TypeError(f'unexpected type {type(v)}; permitted: Optional[Union[List[Dict[str, Any]], str]]')
<|end_body_0|>
<|body_start_1|>
if isinstance(v, li... | Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description: Information about the parameter. force: Skip checking the current value of the ... | ArgsDataModel | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgsDataModel:
"""Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description: Information about the parameter. force... | stack_v2_sparse_classes_36k_train_007609 | 11,061 | permissive | [
{
"docstring": "Convert policies to acceptable value.",
"name": "_convert_policies",
"signature": "def _convert_policies(cls, v: Union[List[Dict[str, Any]], str, Any]) -> str"
},
{
"docstring": "Convert tags to acceptable value.",
"name": "_convert_tags",
"signature": "def _convert_tags(... | 2 | null | Implement the Python class `ArgsDataModel` described below.
Class description:
Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description:... | Implement the Python class `ArgsDataModel` described below.
Class description:
Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description:... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class ArgsDataModel:
"""Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description: Information about the parameter. force... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgsDataModel:
"""Parameter hook args. Attributes: allowed_pattern: A regular expression used to validate the parameter value. data_type: The data type for a String parameter. Supported data types include plain text and Amazon Machine Image IDs. description: Information about the parameter. force: Skip checki... | the_stack_v2_python_sparse | runway/cfngin/hooks/ssm/parameter.py | onicagroup/runway | train | 156 |
22cd0efd8ee683507813eda63542ce5d23ce7889 | [
"path = request.GET.get('name')\nfile = OSS().get(path)\next = os.path.splitext(path)[1].lower()\nm = self.mime[ext] if self.mime.__contains__(ext) else 'application/octet-stream'\nreturn HttpResponse(file, content_type=m)",
"file = request.FILES.get('file')\nif not file:\n return Response({'error_code': '文件 f... | <|body_start_0|>
path = request.GET.get('name')
file = OSS().get(path)
ext = os.path.splitext(path)[1].lower()
m = self.mime[ext] if self.mime.__contains__(ext) else 'application/octet-stream'
return HttpResponse(file, content_type=m)
<|end_body_0|>
<|body_start_1|>
file... | 处理所有文件上传和下载的视图类 | UploadView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadView:
"""处理所有文件上传和下载的视图类"""
def get(self, request):
""":param request: request :return: 返回文件"""
<|body_0|>
def post(self, request):
""":param request: request :return: 返回文件访问路径"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
path = request... | stack_v2_sparse_classes_36k_train_007610 | 5,031 | no_license | [
{
"docstring": ":param request: request :return: 返回文件",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": ":param request: request :return: 返回文件访问路径",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000683 | Implement the Python class `UploadView` described below.
Class description:
处理所有文件上传和下载的视图类
Method signatures and docstrings:
- def get(self, request): :param request: request :return: 返回文件
- def post(self, request): :param request: request :return: 返回文件访问路径 | Implement the Python class `UploadView` described below.
Class description:
处理所有文件上传和下载的视图类
Method signatures and docstrings:
- def get(self, request): :param request: request :return: 返回文件
- def post(self, request): :param request: request :return: 返回文件访问路径
<|skeleton|>
class UploadView:
"""处理所有文件上传和下载的视图类"""
... | 29ec29bbaf9aa4dd154448c5530585eabfe26687 | <|skeleton|>
class UploadView:
"""处理所有文件上传和下载的视图类"""
def get(self, request):
""":param request: request :return: 返回文件"""
<|body_0|>
def post(self, request):
""":param request: request :return: 返回文件访问路径"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadView:
"""处理所有文件上传和下载的视图类"""
def get(self, request):
""":param request: request :return: 返回文件"""
path = request.GET.get('name')
file = OSS().get(path)
ext = os.path.splitext(path)[1].lower()
m = self.mime[ext] if self.mime.__contains__(ext) else 'application/o... | the_stack_v2_python_sparse | qingxiu-backend/upload/views.py | pxmxm/test | train | 0 |
6c0aad61be1692cac5432cae34e141a3193ffda8 | [
"size = len(prices)\nif size <= 0:\n return 0\nmemo = {}\n\ndef dp(start, k):\n if k == 0:\n return 0\n if start >= size:\n return 0\n if (start, k) in memo:\n return memo[start, k]\n minIdx = start\n maxPro = 0\n for i in range(start + 1, size):\n if prices[i] < pri... | <|body_start_0|>
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
return 0
if (start, k) in memo:
return memo[start, k]
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_36k_train_007611 | 5,853 | permissive | [
{
"docstring": "暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化",
"name": "maxProfit",
"signature": "def maxProfit(self, k: int, prices: List[int]) -> int"
},
{
"docstring": "动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k][0] = max(dp[i - 1][k][0], dp[i - 1][k][1] + ... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, k: int, prices: List[int]) -> int: 暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化
- def maxProfit_dp(self, k: int, prices: List[int]) -> int: 动态规划:三个操作状态buy, sell, rest。 通用状... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
<|body_0|>
def maxProfit_dp(self, k: int, prices: List[int]) -> int:
"""动态规划:三个操作状态buy, sell, rest。 通用状态转移方程:s[0,1]两种(有无股票)状态的两种情况,昨天的股票持有状态和今天的操作影响今天的收益情况 dp[i][k]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
"""暴力优化2:消除一层循环+备忘录,超时90分吧,后续状态机优化"""
size = len(prices)
if size <= 0:
return 0
memo = {}
def dp(start, k):
if k == 0:
return 0
if start >= size:
... | the_stack_v2_python_sparse | 188-best-time-to-buy-and-sell-stock-iv.py | yuenliou/leetcode | train | 0 | |
5a3aa01210152ce81ac8175d0c78946d8d7e2dc8 | [
"if isinstance(init, mymesh):\n obj = np.ndarray.__new__(cls, init.shape, dtype=init.dtype, buffer=None)\n obj[:] = init[:]\n obj.part1 = obj[0, :]\n obj.part2 = obj[1, :]\nelif isinstance(init, tuple):\n obj = np.ndarray.__new__(cls, shape=(2, init[0]), dtype=init[1], buffer=None)\n obj.fill(val)... | <|body_start_0|>
if isinstance(init, mymesh):
obj = np.ndarray.__new__(cls, init.shape, dtype=init.dtype, buffer=None)
obj[:] = init[:]
obj.part1 = obj[0, :]
obj.part2 = obj[1, :]
elif isinstance(init, tuple):
obj = np.ndarray.__new__(cls, shap... | mymesh | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mymesh:
def __new__(cls, init, val=0.0):
"""Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple containing the dimensions, the communicator and the dtype val: value to initialize Returns: obj of ... | stack_v2_sparse_classes_36k_train_007612 | 1,490 | permissive | [
{
"docstring": "Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple containing the dimensions, the communicator and the dtype val: value to initialize Returns: obj of type mesh",
"name": "__new__",
"signature": ... | 2 | null | Implement the Python class `mymesh` described below.
Class description:
Implement the mymesh class.
Method signatures and docstrings:
- def __new__(cls, init, val=0.0): Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple cont... | Implement the Python class `mymesh` described below.
Class description:
Implement the mymesh class.
Method signatures and docstrings:
- def __new__(cls, init, val=0.0): Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple cont... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class mymesh:
def __new__(cls, init, val=0.0):
"""Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple containing the dimensions, the communicator and the dtype val: value to initialize Returns: obj of ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mymesh:
def __new__(cls, init, val=0.0):
"""Instantiates new datatype. This ensures that even when manipulating data, the result is still a mesh. Args: init: either another mesh or a tuple containing the dimensions, the communicator and the dtype val: value to initialize Returns: obj of type mesh"""
... | the_stack_v2_python_sparse | pySDC/playgrounds/other/parallel_rhs_mesh.py | Parallel-in-Time/pySDC | train | 30 | |
f6dbc720b8bf5aeb2803ae8721f8814445e7dade | [
"super().__init__()\nself.threshold = threshold\nself.constant = constant\nself.vals = vals if isinstance(vals, Sequence) else (0.0, vals)",
"img, retmode = super().forward(img)\nhit = (img[:3] < self.threshold).all(dim=0)\nif self.constant:\n a = img[:3, hit].norm(dim=0)\n a = a.clamp(0, self.threshold) / ... | <|body_start_0|>
super().__init__()
self.threshold = threshold
self.constant = constant
self.vals = vals if isinstance(vals, Sequence) else (0.0, vals)
<|end_body_0|>
<|body_start_1|>
img, retmode = super().forward(img)
hit = (img[:3] < self.threshold).all(dim=0)
... | Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text | Black2RGB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Black2RGB:
"""Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text"""
def __init__(self, threshold=0.25, vals=(0.0, 1.0), constant=True):
""":param threshold: indicates the maximum value on any colour channel that ... | stack_v2_sparse_classes_36k_train_007613 | 5,327 | permissive | [
{
"docstring": ":param threshold: indicates the maximum value on any colour channel that causes a colour flip :param vals: possible values of R/G/B :param constant: whether to use a \"constant\" (read: gradient) colour or individual RGB values for each pixel",
"name": "__init__",
"signature": "def __ini... | 2 | null | Implement the Python class `Black2RGB` described below.
Class description:
Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text
Method signatures and docstrings:
- def __init__(self, threshold=0.25, vals=(0.0, 1.0), constant=True): :param threshold... | Implement the Python class `Black2RGB` described below.
Class description:
Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text
Method signatures and docstrings:
- def __init__(self, threshold=0.25, vals=(0.0, 1.0), constant=True): :param threshold... | 06839b08d8e8f274c02a6bcd31bf1b32d3dc04e4 | <|skeleton|>
class Black2RGB:
"""Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text"""
def __init__(self, threshold=0.25, vals=(0.0, 1.0), constant=True):
""":param threshold: indicates the maximum value on any colour channel that ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Black2RGB:
"""Inserts random RGB values in an image at specific dark colours Used to, for example, convert black writing to colored text"""
def __init__(self, threshold=0.25, vals=(0.0, 1.0), constant=True):
""":param threshold: indicates the maximum value on any colour channel that causes a colo... | the_stack_v2_python_sparse | neodroidvision/utilities/torch_utilities/transforms/image_transforms.py | aivclab/vision | train | 1 |
86b1cc914415341186c1aa16f2afe8e666ea174c | [
"if isinstance(A, Sample):\n dl1 = Samples({k: [v] for k, v in A.items()}).get_dataloader(batch_size=1)\nelif isinstance(A, Samples):\n dl1 = A.get_dataloader(batch_size=batch_size)\nelse:\n dl1 = A\nif isinstance(B, Sample):\n dl2 = Samples({k: [v] for k, v in B.items()}).get_dataloader(batch_size=1)\n... | <|body_start_0|>
if isinstance(A, Sample):
dl1 = Samples({k: [v] for k, v in A.items()}).get_dataloader(batch_size=1)
elif isinstance(A, Samples):
dl1 = A.get_dataloader(batch_size=batch_size)
else:
dl1 = A
if isinstance(B, Sample):
dl2 = S... | Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter inference tasks with a trained network -... | SwyftTrainer | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter ... | stack_v2_sparse_classes_36k_train_007614 | 16,173 | permissive | [
{
"docstring": "Run through model in inference mode. Args: A: Sample, Samples, or dataloader for samples A. B: Sample, Samples, or dataloader for samples B. return_sample_ratios: If true (default), return results as collated collection of `LogRatioSamples` objects. Otherwise, return batches. batch_size: batch_s... | 2 | stack_v2_sparse_classes_30k_train_003206 | Implement the Python class `SwyftTrainer` described below.
Class description:
Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defin... | Implement the Python class `SwyftTrainer` described below.
Class description:
Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defin... | bd1a71b8f1ea1c9f0db81383d8568dd47dfdca28 | <|skeleton|>
class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwyftTrainer:
"""Base class: pytorch_lightning.Trainer It provides training functionality for swyft.SwyftModule. The functionality is identical to `pytorch_lightning.Trainer`, see corresponding documentation for more details. Two additional methods are defined: - `infer` for performing parameter inference tas... | the_stack_v2_python_sparse | swyft/lightning/core.py | undark-lab/swyft | train | 162 |
bdd9b360a5b2d71509bb03161d6878a82e3912b1 | [
"model_filename = 'shape_predictor_68_face_landmarks.dat'\nif not os.path.exists(model_filename):\n os.system('wget http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2')\n os.system('bunzip2 shape_predictor_68_face_landmarks.dat.bz2')\nself.model = dlib.shape_pred... | <|body_start_0|>
model_filename = 'shape_predictor_68_face_landmarks.dat'
if not os.path.exists(model_filename):
os.system('wget http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2')
os.system('bunzip2 shape_predictor_68_face_landmark... | Summary. Attributes ---------- detector : TYPE Description model : TYPE Description | FaceShapeModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceShapeModel:
"""Summary. Attributes ---------- detector : TYPE Description model : TYPE Description"""
def __init__(self):
"""Summary."""
<|body_0|>
def localize(self, image):
"""Summary. Parameters ---------- image : TYPE Description Raises ------ ValueError ... | stack_v2_sparse_classes_36k_train_007615 | 4,242 | permissive | [
{
"docstring": "Summary.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Summary. Parameters ---------- image : TYPE Description Raises ------ ValueError Description Returns ------- name : TYPE Description",
"name": "localize",
"signature": "def localize(self, ... | 4 | stack_v2_sparse_classes_30k_train_010691 | Implement the Python class `FaceShapeModel` described below.
Class description:
Summary. Attributes ---------- detector : TYPE Description model : TYPE Description
Method signatures and docstrings:
- def __init__(self): Summary.
- def localize(self, image): Summary. Parameters ---------- image : TYPE Description Rais... | Implement the Python class `FaceShapeModel` described below.
Class description:
Summary. Attributes ---------- detector : TYPE Description model : TYPE Description
Method signatures and docstrings:
- def __init__(self): Summary.
- def localize(self, image): Summary. Parameters ---------- image : TYPE Description Rais... | 560334017c5748aa29431fa918ed7a35e8f2699c | <|skeleton|>
class FaceShapeModel:
"""Summary. Attributes ---------- detector : TYPE Description model : TYPE Description"""
def __init__(self):
"""Summary."""
<|body_0|>
def localize(self, image):
"""Summary. Parameters ---------- image : TYPE Description Raises ------ ValueError ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceShapeModel:
"""Summary. Attributes ---------- detector : TYPE Description model : TYPE Description"""
def __init__(self):
"""Summary."""
model_filename = 'shape_predictor_68_face_landmarks.dat'
if not os.path.exists(model_filename):
os.system('wget http://sourcefor... | the_stack_v2_python_sparse | UnifyID/faces.py | knakamor/projects | train | 1 |
31a3b9f86fb60a700fc89d40bfb62fc5621ccaf4 | [
"self.full_prefix = '{}_{}'.format(self.__class__._PREFIX, prefix)\nself.progress = prometheus_client.Gauge('{}_attempt_inprogress'.format(self.full_prefix), 'In progress attempts to {}'.format(description), labels, registry=REGISTRY, multiprocess_mode='livesum')\nself.attempt_total = prometheus_client.Counter('{}_... | <|body_start_0|>
self.full_prefix = '{}_{}'.format(self.__class__._PREFIX, prefix)
self.progress = prometheus_client.Gauge('{}_attempt_inprogress'.format(self.full_prefix), 'In progress attempts to {}'.format(description), labels, registry=REGISTRY, multiprocess_mode='livesum')
self.attempt_tota... | Support for defining and observing metrics for an action, including tracking attempts, failures, and timing. | ActionMetrics | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in ... | stack_v2_sparse_classes_36k_train_007616 | 6,480 | permissive | [
{
"docstring": ":param prefix: prefix to use for each metric name :param description: description of action to use in metric description :param labels: label names to define for each metric",
"name": "__init__",
"signature": "def __init__(self, prefix, description, labels)"
},
{
"docstring": "An... | 2 | stack_v2_sparse_classes_30k_train_015146 | Implement the Python class `ActionMetrics` described below.
Class description:
Support for defining and observing metrics for an action, including tracking attempts, failures, and timing.
Method signatures and docstrings:
- def __init__(self, prefix, description, labels): :param prefix: prefix to use for each metric ... | Implement the Python class `ActionMetrics` described below.
Class description:
Support for defining and observing metrics for an action, including tracking attempts, failures, and timing.
Method signatures and docstrings:
- def __init__(self, prefix, description, labels): :param prefix: prefix to use for each metric ... | 6595dd83ea65324196c89cf6fb83f168818822de | <|skeleton|>
class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionMetrics:
"""Support for defining and observing metrics for an action, including tracking attempts, failures, and timing."""
def __init__(self, prefix, description, labels):
""":param prefix: prefix to use for each metric name :param description: description of action to use in metric descri... | the_stack_v2_python_sparse | armada/handlers/metrics.py | airshipit/armada | train | 20 |
f1f857ac21f32c9a9d57f24b9379018d756d37c1 | [
"if self.initial_run:\n initial_pos = data.pose.pose\n self.filter = KalmanFilter(1.0 / self.sub_frequency, initial_pos)\n self.X_est = Odometry()\n self.X_est.pose.pose = initial_pos\n self.initial_run = False\nelse:\n X_measured = data.pose.pose\n time = data.header.stamp\n if X_measured i... | <|body_start_0|>
if self.initial_run:
initial_pos = data.pose.pose
self.filter = KalmanFilter(1.0 / self.sub_frequency, initial_pos)
self.X_est = Odometry()
self.X_est.pose.pose = initial_pos
self.initial_run = False
else:
X_measure... | ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output steady position and velocity data for other nodes. | KalmanFilterNode | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KalmanFilterNode:
"""ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output steady position and velocity data for other... | stack_v2_sparse_classes_36k_train_007617 | 2,827 | permissive | [
{
"docstring": "Process received positions data and return Kalman estimation. :type data: Odometry",
"name": "sensor_callback",
"signature": "def sensor_callback(self, data)"
},
{
"docstring": "Initialize agent instance, create subscribers and publishers.",
"name": "__init__",
"signature... | 2 | stack_v2_sparse_classes_30k_train_009408 | Implement the Python class `KalmanFilterNode` described below.
Class description:
ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output stea... | Implement the Python class `KalmanFilterNode` described below.
Class description:
ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output stea... | 25a1c67a2ee20b39f64da43a81e7f8d9785c4f94 | <|skeleton|>
class KalmanFilterNode:
"""ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output steady position and velocity data for other... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KalmanFilterNode:
"""ROS node implementation of Kalman filter. This node subscribes to a list of all existing Sphero's positions broadcast from OptiTrack system, associates one of them to the Sphero in the same namespace and uses Kalman filter to output steady position and velocity data for other nodes."""
... | the_stack_v2_python_sparse | scripts/kalman_filter_sim_node.py | louvreaux/sphero_formation | train | 1 |
ece1d797a3b98dc341b9b1e116a2373ea328ba2d | [
"number_frequency_map = {}\nfor num in arr:\n number_frequency_map[num] = number_frequency_map.get(num, 0) + 1\nlucky_number = -1\nfor key, value in number_frequency_map.items():\n if key == value:\n lucky_number = max(value, lucky_number)\nreturn lucky_number",
"lucky_list = []\nfor i in arr:\n i... | <|body_start_0|>
number_frequency_map = {}
for num in arr:
number_frequency_map[num] = number_frequency_map.get(num, 0) + 1
lucky_number = -1
for key, value in number_frequency_map.items():
if key == value:
lucky_number = max(value, lucky_number)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
<|body_0|>
def findLucky_2(self, arr: List[int]) -> int:
"""Time: O(N^2) Space: O(N)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
number_frequency_map = {}
... | stack_v2_sparse_classes_36k_train_007618 | 2,039 | no_license | [
{
"docstring": "Time: O(N) Space: O(N)",
"name": "findLucky",
"signature": "def findLucky(self, arr: List[int]) -> int"
},
{
"docstring": "Time: O(N^2) Space: O(N)",
"name": "findLucky_2",
"signature": "def findLucky_2(self, arr: List[int]) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_012618 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr: List[int]) -> int: Time: O(N) Space: O(N)
- def findLucky_2(self, arr: List[int]) -> int: Time: O(N^2) Space: O(N) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr: List[int]) -> int: Time: O(N) Space: O(N)
- def findLucky_2(self, arr: List[int]) -> int: Time: O(N^2) Space: O(N)
<|skeleton|>
class Solution:
def... | 57534898c17d058ef1dba2b1cb8cdcd8d1d2a41c | <|skeleton|>
class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
<|body_0|>
def findLucky_2(self, arr: List[int]) -> int:
"""Time: O(N^2) Space: O(N)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLucky(self, arr: List[int]) -> int:
"""Time: O(N) Space: O(N)"""
number_frequency_map = {}
for num in arr:
number_frequency_map[num] = number_frequency_map.get(num, 0) + 1
lucky_number = -1
for key, value in number_frequency_map.items():
... | the_stack_v2_python_sparse | leetcode/leetcode_question_bank/problems/1394_find_lucky_integer_in_an_array/lucky_integer.py | arivolispark/datastructuresandalgorithms | train | 0 | |
9f68c37f78bf3089d787dd0e9b45a3b94f43d2ce | [
"request = self.context.get('request')\ndata_flag = request.GET.get('data')\nkey = request.GET.get('key')\nif (str2bool(data_flag) or key) and obj:\n data = Widget.query_data(obj)\nelse:\n data = []\nreturn data",
"column = attrs.get('column')\nif 'content_object' in attrs:\n content_object = attrs.get('... | <|body_start_0|>
request = self.context.get('request')
data_flag = request.GET.get('data')
key = request.GET.get('key')
if (str2bool(data_flag) or key) and obj:
data = Widget.query_data(obj)
else:
data = []
return data
<|end_body_0|>
<|body_start_... | WidgetSerializer | WidgetSerializer | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WidgetSerializer:
"""WidgetSerializer"""
def get_data(self, obj):
"""Return the Widget.query_data(obj)"""
<|body_0|>
def validate(self, attrs):
"""Validates that column exists in the XForm."""
<|body_1|>
def validate_content_object(self, value):
... | stack_v2_sparse_classes_36k_train_007619 | 6,612 | permissive | [
{
"docstring": "Return the Widget.query_data(obj)",
"name": "get_data",
"signature": "def get_data(self, obj)"
},
{
"docstring": "Validates that column exists in the XForm.",
"name": "validate",
"signature": "def validate(self, attrs)"
},
{
"docstring": "Validate if a user is the... | 3 | null | Implement the Python class `WidgetSerializer` described below.
Class description:
WidgetSerializer
Method signatures and docstrings:
- def get_data(self, obj): Return the Widget.query_data(obj)
- def validate(self, attrs): Validates that column exists in the XForm.
- def validate_content_object(self, value): Validate... | Implement the Python class `WidgetSerializer` described below.
Class description:
WidgetSerializer
Method signatures and docstrings:
- def get_data(self, obj): Return the Widget.query_data(obj)
- def validate(self, attrs): Validates that column exists in the XForm.
- def validate_content_object(self, value): Validate... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class WidgetSerializer:
"""WidgetSerializer"""
def get_data(self, obj):
"""Return the Widget.query_data(obj)"""
<|body_0|>
def validate(self, attrs):
"""Validates that column exists in the XForm."""
<|body_1|>
def validate_content_object(self, value):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WidgetSerializer:
"""WidgetSerializer"""
def get_data(self, obj):
"""Return the Widget.query_data(obj)"""
request = self.context.get('request')
data_flag = request.GET.get('data')
key = request.GET.get('key')
if (str2bool(data_flag) or key) and obj:
dat... | the_stack_v2_python_sparse | onadata/libs/serializers/widget_serializer.py | onaio/onadata | train | 177 |
1db500821af8f97a36c71e60c3941f935c34e839 | [
"obj = None\ntry:\n obj = cls.objects.get(ip=ip)\nexcept ObjectDoesNotExist as e:\n obj = cls()\n obj.ip = ip\nobj.gpu_user_name = gpu_user_name\nobj.update_time = timezone.now()\nobj.save()\nreturn obj",
"rt = {}\nfor k, v in self.__dict__.items():\n if isinstance(v, (int, float, bool, str, datetime.... | <|body_start_0|>
obj = None
try:
obj = cls.objects.get(ip=ip)
except ObjectDoesNotExist as e:
obj = cls()
obj.ip = ip
obj.gpu_user_name = gpu_user_name
obj.update_time = timezone.now()
obj.save()
return obj
<|end_body_0|>
<|bod... | Gpu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gpu:
def create_or_replace(cls, ip, gpu_user_name):
"""发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象"""
<|body_0|>
def as_dict(self):
"""把对象转换为可序列化的dict :param self:传入对象 :return: 返回字典"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_007620 | 13,402 | no_license | [
{
"docstring": "发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象",
"name": "create_or_replace",
"signature": "def create_or_replace(cls, ip, gpu_user_name)"
},
{
"docstring": "把对象转换为可序列化的dict :param self:传入对象 :return: 返回字典",
"name": "as_dict",
"signature": "def a... | 2 | stack_v2_sparse_classes_30k_train_013911 | Implement the Python class `Gpu` described below.
Class description:
Implement the Gpu class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, gpu_user_name): 发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象
- def as_dict(self): 把对象转换为可序列化的dict :param self:传入对象 :return: 返回字典 | Implement the Python class `Gpu` described below.
Class description:
Implement the Gpu class.
Method signatures and docstrings:
- def create_or_replace(cls, ip, gpu_user_name): 发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象
- def as_dict(self): 把对象转换为可序列化的dict :param self:传入对象 :return: 返回字典... | 4febccac57bfa5f7ef46f5f57e52206c8b0a57ac | <|skeleton|>
class Gpu:
def create_or_replace(cls, ip, gpu_user_name):
"""发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象"""
<|body_0|>
def as_dict(self):
"""把对象转换为可序列化的dict :param self:传入对象 :return: 返回字典"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gpu:
def create_or_replace(cls, ip, gpu_user_name):
"""发现一个有新gpu的主机信息 :param ip: ip地址 :param gpu_user_name: 显卡使用者 :return: gpu对象"""
obj = None
try:
obj = cls.objects.get(ip=ip)
except ObjectDoesNotExist as e:
obj = cls()
obj.ip = ip
o... | the_stack_v2_python_sparse | item/dev/cmdb/asset/models.py | soulorman/Python | train | 0 | |
4d9a93fc218ab5acc11d68399b97332f66b9ea72 | [
"self.component1_motor = wpilib.Talon(1)\nself.some_motor = wpilib.Talon(2)\nself.joystick = wpilib.Joystick(0)",
"try:\n if self.joystick.getTrigger():\n self.component2.do_something()\nexcept:\n self.onException()"
] | <|body_start_0|>
self.component1_motor = wpilib.Talon(1)
self.some_motor = wpilib.Talon(2)
self.joystick = wpilib.Joystick(0)
<|end_body_0|>
<|body_start_1|>
try:
if self.joystick.getTrigger():
self.component2.do_something()
except:
self.o... | MyRobot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyRobot:
def createObjects(self):
"""Initialize all wpilib motors & sensors"""
<|body_0|>
def teleopPeriodic(self):
"""Place code here that does things as a result of operator actions"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.component1_m... | stack_v2_sparse_classes_36k_train_007621 | 1,088 | no_license | [
{
"docstring": "Initialize all wpilib motors & sensors",
"name": "createObjects",
"signature": "def createObjects(self)"
},
{
"docstring": "Place code here that does things as a result of operator actions",
"name": "teleopPeriodic",
"signature": "def teleopPeriodic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008134 | Implement the Python class `MyRobot` described below.
Class description:
Implement the MyRobot class.
Method signatures and docstrings:
- def createObjects(self): Initialize all wpilib motors & sensors
- def teleopPeriodic(self): Place code here that does things as a result of operator actions | Implement the Python class `MyRobot` described below.
Class description:
Implement the MyRobot class.
Method signatures and docstrings:
- def createObjects(self): Initialize all wpilib motors & sensors
- def teleopPeriodic(self): Place code here that does things as a result of operator actions
<|skeleton|>
class MyR... | edbaa498ef685bed516f6792089f88be1a5db865 | <|skeleton|>
class MyRobot:
def createObjects(self):
"""Initialize all wpilib motors & sensors"""
<|body_0|>
def teleopPeriodic(self):
"""Place code here that does things as a result of operator actions"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyRobot:
def createObjects(self):
"""Initialize all wpilib motors & sensors"""
self.component1_motor = wpilib.Talon(1)
self.some_motor = wpilib.Talon(2)
self.joystick = wpilib.Joystick(0)
def teleopPeriodic(self):
"""Place code here that does things as a result of ... | the_stack_v2_python_sparse | magicbot-simple/robot.py | robotpy/examples | train | 38 | |
775aab074ee97da225682bb1a5fd6272924c9251 | [
"self.trie = Trie()\nself.cache = self.trie\nself.cacheStr = ''\nfor sent, time in zip(sentences, times):\n self.trie.insert(self.trie, sent, time)",
"if c == '#':\n self.cache = self.trie\n self.trie.insert(self.trie, self.cacheStr, 1)\n self.cacheStr = ''\n return []\nelse:\n self.cacheStr += ... | <|body_start_0|>
self.trie = Trie()
self.cache = self.trie
self.cacheStr = ''
for sent, time in zip(sentences, times):
self.trie.insert(self.trie, sent, time)
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.cache = self.trie
self.trie.insert... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.trie = Trie()
... | stack_v2_sparse_classes_36k_train_007622 | 2,593 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 8075fbb40987d5e6af8d30941a19fa48a3320f56 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.trie = Trie()
self.cache = self.trie
self.cacheStr = ''
for sent, time in zip(sentences, times):
self.trie.insert(self.trie, sent, time)
... | the_stack_v2_python_sparse | p642/Solution.py | carwestsam/leetCode | train | 4 | |
242007547d8c4860ac39086b35e39c80f89f1e6b | [
"try:\n with self.get_keycloak_client() as kc:\n if user_name is None:\n search = request.GET.get('search')\n response = kc.get_all_users(search)\n return Response(response, status=200)\n else:\n response = kc.get_userdata(user_name)\n roles = ... | <|body_start_0|>
try:
with self.get_keycloak_client() as kc:
if user_name is None:
search = request.GET.get('search')
response = kc.get_all_users(search)
return Response(response, status=200)
else:
... | View to manage users | BossUser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BossUser:
"""View to manage users"""
def get(self, request, user_name=None):
"""Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of user data"""
<|body_0|>
def post(self, requ... | stack_v2_sparse_classes_36k_train_007623 | 11,158 | permissive | [
{
"docstring": "Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of user data",
"name": "get",
"signature": "def get(self, request, user_name=None)"
},
{
"docstring": "Create a new user Args: request:... | 3 | null | Implement the Python class `BossUser` described below.
Class description:
View to manage users
Method signatures and docstrings:
- def get(self, request, user_name=None): Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of... | Implement the Python class `BossUser` described below.
Class description:
View to manage users
Method signatures and docstrings:
- def get(self, request, user_name=None): Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of... | c2e26d272bd7b8d54abdc2948193163537e31291 | <|skeleton|>
class BossUser:
"""View to manage users"""
def get(self, request, user_name=None):
"""Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of user data"""
<|body_0|>
def post(self, requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BossUser:
"""View to manage users"""
def get(self, request, user_name=None):
"""Get information about a user Args: request: Django rest framework request user_name: User name to get information about Returns: JSON dictionary of user data"""
try:
with self.get_keycloak_client()... | the_stack_v2_python_sparse | django/sso/views/views_user.py | jhuapl-boss/boss | train | 20 |
a7298b649e9a5acbc33d7386595310088e460d7e | [
"idx = 0\nret = list()\nwhile idx < len(string):\n c = string[idx]\n span = re.match(ENCODE_TEMPLATE.format(c), string[idx:]).span()[1]\n if span == 1:\n ret.append(str(c))\n else:\n ret.append(''.join([str(span), str(c)]))\n idx += span\nreturn ''.join(ret)",
"idx = 0\nret = list()\n... | <|body_start_0|>
idx = 0
ret = list()
while idx < len(string):
c = string[idx]
span = re.match(ENCODE_TEMPLATE.format(c), string[idx:]).span()[1]
if span == 1:
ret.append(str(c))
else:
ret.append(''.join([str(span), ... | Method2 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Method2:
def encode(string):
"""Encode a given string using run-length-encoding"""
<|body_0|>
def decode(string):
"""Decode run-length-encoded string back to normal"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
idx = 0
ret = list()
... | stack_v2_sparse_classes_36k_train_007624 | 1,724 | permissive | [
{
"docstring": "Encode a given string using run-length-encoding",
"name": "encode",
"signature": "def encode(string)"
},
{
"docstring": "Decode run-length-encoded string back to normal",
"name": "decode",
"signature": "def decode(string)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003031 | Implement the Python class `Method2` described below.
Class description:
Implement the Method2 class.
Method signatures and docstrings:
- def encode(string): Encode a given string using run-length-encoding
- def decode(string): Decode run-length-encoded string back to normal | Implement the Python class `Method2` described below.
Class description:
Implement the Method2 class.
Method signatures and docstrings:
- def encode(string): Encode a given string using run-length-encoding
- def decode(string): Decode run-length-encoded string back to normal
<|skeleton|>
class Method2:
def enco... | 31f0faa3f35dd0b264a161c862fbdc3808dc5aee | <|skeleton|>
class Method2:
def encode(string):
"""Encode a given string using run-length-encoding"""
<|body_0|>
def decode(string):
"""Decode run-length-encoded string back to normal"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Method2:
def encode(string):
"""Encode a given string using run-length-encoding"""
idx = 0
ret = list()
while idx < len(string):
c = string[idx]
span = re.match(ENCODE_TEMPLATE.format(c), string[idx:]).span()[1]
if span == 1:
... | the_stack_v2_python_sparse | run-length-encoding/better.py | always-waiting/exercism-python | train | 0 | |
e97b833c1284288711e53f72a0bde96517390715 | [
"self.requirements_description = requirements_description\nself.required = required\nself.others = others\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nrequirements_description = dictionary.get('RequirementsDescription')\nrequired = idfy_rest_client.models.require... | <|body_start_0|>
self.requirements_description = requirements_description
self.required = required
self.others = others
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
requirements_descript... | Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatures): TODO: type description here. | SignatureObject | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignatureObject:
"""Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatures): TODO: type description here."""
... | stack_v2_sparse_classes_36k_train_007625 | 2,762 | permissive | [
{
"docstring": "Constructor for the SignatureObject class",
"name": "__init__",
"signature": "def __init__(self, requirements_description=None, required=None, others=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictiona... | 2 | null | Implement the Python class `SignatureObject` described below.
Class description:
Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatu... | Implement the Python class `SignatureObject` described below.
Class description:
Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatu... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class SignatureObject:
"""Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatures): TODO: type description here."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignatureObject:
"""Implementation of the 'SignatureObject' model. TODO: type model description here. Attributes: requirements_description (string): TODO: type description here. required (RequiredSignatures): TODO: type description here. others (OtherSignatures): TODO: type description here."""
def __ini... | the_stack_v2_python_sparse | idfy_rest_client/models/signature_object.py | dealflowteam/Idfy | train | 0 |
c260f98429f2a4ac80419689c1f658c1bd8179b8 | [
"self.assertTrue(anagram('cinema', 'iceman'))\nself.assertTrue(anagram('dormitory', 'dirtyroom'))\nself.assertFalse(anagram('hello', 'lohae'))\nself.assertFalse(anagram('ill', 'like'))\nself.assertFalse(anagram('illness', 'nes'))",
"self.assertTrue(anagram_dd('cinema', 'iceman'))\nself.assertTrue(anagram_dd('dorm... | <|body_start_0|>
self.assertTrue(anagram('cinema', 'iceman'))
self.assertTrue(anagram('dormitory', 'dirtyroom'))
self.assertFalse(anagram('hello', 'lohae'))
self.assertFalse(anagram('ill', 'like'))
self.assertFalse(anagram('illness', 'nes'))
<|end_body_0|>
<|body_start_1|>
... | verify that functions works fine | FunctionTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
<|body_0|>
def test_anagram_dd(self):
"""verify anagram_dd works fine"""
<|body_1|>
def test_book_index(self):
"""verify that book_in... | stack_v2_sparse_classes_36k_train_007626 | 2,565 | no_license | [
{
"docstring": "verify anagram works fine",
"name": "test_anagram",
"signature": "def test_anagram(self)"
},
{
"docstring": "verify anagram_dd works fine",
"name": "test_anagram_dd",
"signature": "def test_anagram_dd(self)"
},
{
"docstring": "verify that book_index works fine",
... | 3 | stack_v2_sparse_classes_30k_train_015907 | Implement the Python class `FunctionTest` described below.
Class description:
verify that functions works fine
Method signatures and docstrings:
- def test_anagram(self): verify anagram works fine
- def test_anagram_dd(self): verify anagram_dd works fine
- def test_book_index(self): verify that book_index works fine | Implement the Python class `FunctionTest` described below.
Class description:
verify that functions works fine
Method signatures and docstrings:
- def test_anagram(self): verify anagram works fine
- def test_anagram_dd(self): verify anagram_dd works fine
- def test_book_index(self): verify that book_index works fine
... | f45bd7c20e91584428c90a332173ee9c8fa66a4c | <|skeleton|>
class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
<|body_0|>
def test_anagram_dd(self):
"""verify anagram_dd works fine"""
<|body_1|>
def test_book_index(self):
"""verify that book_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FunctionTest:
"""verify that functions works fine"""
def test_anagram(self):
"""verify anagram works fine"""
self.assertTrue(anagram('cinema', 'iceman'))
self.assertTrue(anagram('dormitory', 'dirtyroom'))
self.assertFalse(anagram('hello', 'lohae'))
self.assertFalse... | the_stack_v2_python_sparse | HanrunLiHW07.py | obleevious/SSW810Final_repo | train | 0 |
6b8787739e681958c7eccf46ebaa818ce47d404f | [
"predictions = np.zeros((n_predictions, n_timepoints), dtype='float32')\nfor idx in range(n_predictions):\n prediction_params = np.array([gaussian_params[0], gaussian_params[1], gaussian_params[2], 1.0, 0.0, sa[idx], ss[idx], nb[idx], sb[idx]]).T\n predictions[idx, :] = self.return_prediction(*list(prediction... | <|body_start_0|>
predictions = np.zeros((n_predictions, n_timepoints), dtype='float32')
for idx in range(n_predictions):
prediction_params = np.array([gaussian_params[0], gaussian_params[1], gaussian_params[2], 1.0, 0.0, sa[idx], ss[idx], nb[idx], sb[idx]]).T
predictions[idx, :] ... | Norm_Iso2DGaussianModel Redefining class for normalization model | Norm_Iso2DGaussianModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Norm_Iso2DGaussianModel:
"""Norm_Iso2DGaussianModel Redefining class for normalization model"""
def create_grid_predictions(self, gaussian_params, n_predictions, n_timepoints, sa, ss, nb, sb):
"""create_predictions creates predictions for a given set of parameters [description] Param... | stack_v2_sparse_classes_36k_train_007627 | 20,783 | no_license | [
{
"docstring": "create_predictions creates predictions for a given set of parameters [description] Parameters ---------- gaussian_params: array size (3), containing prf position and size. n_predictions, n_timepoints: self explanatory, obtained from fitter nb,sa,ss,sb: meshgrid, created in fitter.grid_fit",
... | 2 | stack_v2_sparse_classes_30k_train_010799 | Implement the Python class `Norm_Iso2DGaussianModel` described below.
Class description:
Norm_Iso2DGaussianModel Redefining class for normalization model
Method signatures and docstrings:
- def create_grid_predictions(self, gaussian_params, n_predictions, n_timepoints, sa, ss, nb, sb): create_predictions creates pred... | Implement the Python class `Norm_Iso2DGaussianModel` described below.
Class description:
Norm_Iso2DGaussianModel Redefining class for normalization model
Method signatures and docstrings:
- def create_grid_predictions(self, gaussian_params, n_predictions, n_timepoints, sa, ss, nb, sb): create_predictions creates pred... | f8eda6b3d741e5e12e4192c2ff7d100b5bb3f5d1 | <|skeleton|>
class Norm_Iso2DGaussianModel:
"""Norm_Iso2DGaussianModel Redefining class for normalization model"""
def create_grid_predictions(self, gaussian_params, n_predictions, n_timepoints, sa, ss, nb, sb):
"""create_predictions creates predictions for a given set of parameters [description] Param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Norm_Iso2DGaussianModel:
"""Norm_Iso2DGaussianModel Redefining class for normalization model"""
def create_grid_predictions(self, gaussian_params, n_predictions, n_timepoints, sa, ss, nb, sb):
"""create_predictions creates predictions for a given set of parameters [description] Parameters -------... | the_stack_v2_python_sparse | mri_analysis/model/prfpy/model.py | mszinte/pRFgazeMod | train | 0 |
a66714246d128ad8818f5e9fb889feec5076a688 | [
"stc.StyledTextCtrl.__init__(self, parent, style=style)\nself._styles = [None] * 32\nself._free = 1",
"free = self._free\nif c and isinstance(c, str):\n c = c.lower()\nelse:\n c = 'black'\ntry:\n style = self._styles.index(c)\n return style\nexcept ValueError:\n style = free\n self._styles[style... | <|body_start_0|>
stc.StyledTextCtrl.__init__(self, parent, style=style)
self._styles = [None] * 32
self._free = 1
<|end_body_0|>
<|body_start_1|>
free = self._free
if c and isinstance(c, str):
c = c.lower()
else:
c = 'black'
try:
... | Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window. | Log | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log:
"""Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window."""
def __init__(self, parent, style=wx.SIMPLE_BORDER):
"""Constructor"""
<|body_0|>
def getStyle(self, c='black'):
"""Returns a style for a given colou... | stack_v2_sparse_classes_36k_train_007628 | 4,339 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent, style=wx.SIMPLE_BORDER)"
},
{
"docstring": "Returns a style for a given colour if one exists. If no style exists for the colour, make a new style. If we run out of styles, (only 32 allowed here) we go to t... | 3 | null | Implement the Python class `Log` described below.
Class description:
Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window.
Method signatures and docstrings:
- def __init__(self, parent, style=wx.SIMPLE_BORDER): Constructor
- def getStyle(self, c='black'): Returns a st... | Implement the Python class `Log` described below.
Class description:
Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window.
Method signatures and docstrings:
- def __init__(self, parent, style=wx.SIMPLE_BORDER): Constructor
- def getStyle(self, c='black'): Returns a st... | 979436525c57fdaeaa832e960985e0406e123587 | <|skeleton|>
class Log:
"""Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window."""
def __init__(self, parent, style=wx.SIMPLE_BORDER):
"""Constructor"""
<|body_0|>
def getStyle(self, c='black'):
"""Returns a style for a given colou... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log:
"""Subclass the StyledTextCtrl to provide additions and initializations to make it useful as a log window."""
def __init__(self, parent, style=wx.SIMPLE_BORDER):
"""Constructor"""
stc.StyledTextCtrl.__init__(self, parent, style=style)
self._styles = [None] * 32
self._... | the_stack_v2_python_sparse | Research/wx doco/someStyledTextCtrl1.py | abulka/pynsource | train | 271 |
38dc493f74d2ff34f553b8ce38a7c253325dbe4e | [
"super().__init__(x, y)\nself._state_index = 0\nself._state = [self._radius / 5, self._radius / 4, self._radius / 3, self._radius / 2, self._radius]\nself._radius = self._state[0]",
"self._state_index = (self._state_index + 1) % len(self._state)\nself._radius = self._state[self._state_index]\nsuper().draw_burst(s... | <|body_start_0|>
super().__init__(x, y)
self._state_index = 0
self._state = [self._radius / 5, self._radius / 4, self._radius / 3, self._radius / 2, self._radius]
self._radius = self._state[0]
<|end_body_0|>
<|body_start_1|>
self._state_index = (self._state_index + 1) % len(self... | A class representing an animated fireworks starburst. Public methods: __init__, draw_burst | AnimatedBurst | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnimatedBurst:
"""A class representing an animated fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: int, y: int) -> None:
"""Initialize an instance of GradualBurst at x,y."""
<|body_0|>
def draw_burst(self, surface: pygame.Surface) -> No... | stack_v2_sparse_classes_36k_train_007629 | 4,380 | no_license | [
{
"docstring": "Initialize an instance of GradualBurst at x,y.",
"name": "__init__",
"signature": "def __init__(self, x: int, y: int) -> None"
},
{
"docstring": "Draw the firework on surface.",
"name": "draw_burst",
"signature": "def draw_burst(self, surface: pygame.Surface) -> None"
}... | 2 | stack_v2_sparse_classes_30k_train_009143 | Implement the Python class `AnimatedBurst` described below.
Class description:
A class representing an animated fireworks starburst. Public methods: __init__, draw_burst
Method signatures and docstrings:
- def __init__(self, x: int, y: int) -> None: Initialize an instance of GradualBurst at x,y.
- def draw_burst(self... | Implement the Python class `AnimatedBurst` described below.
Class description:
A class representing an animated fireworks starburst. Public methods: __init__, draw_burst
Method signatures and docstrings:
- def __init__(self, x: int, y: int) -> None: Initialize an instance of GradualBurst at x,y.
- def draw_burst(self... | 0fe17edf6ffcb35265032c6449d866b9434fda00 | <|skeleton|>
class AnimatedBurst:
"""A class representing an animated fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: int, y: int) -> None:
"""Initialize an instance of GradualBurst at x,y."""
<|body_0|>
def draw_burst(self, surface: pygame.Surface) -> No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnimatedBurst:
"""A class representing an animated fireworks starburst. Public methods: __init__, draw_burst"""
def __init__(self, x: int, y: int) -> None:
"""Initialize an instance of GradualBurst at x,y."""
super().__init__(x, y)
self._state_index = 0
self._state = [self... | the_stack_v2_python_sparse | Chapter5TextbookCode/Listing 5-3.py | ProfessorBurke/PythonObjectsGames | train | 3 |
ae1484874866b0cae3797d25c09cef62088d97b4 | [
"res = ''\nfor e in strs:\n res += str(len(e)) + ':' + e\nreturn res",
"ans = []\ni = 0\nwhile i < len(s):\n index = s.find(':', i)\n size = int(s[i:index])\n print(s[i:index])\n ans.append(s[index + 1:index + 1 + size])\n i = index + 1 + size\nreturn ans"
] | <|body_start_0|>
res = ''
for e in strs:
res += str(len(e)) + ':' + e
return res
<|end_body_0|>
<|body_start_1|>
ans = []
i = 0
while i < len(s):
index = s.find(':', i)
size = int(s[i:index])
print(s[i:index])
a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_007630 | 854 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_015042 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type... | 0bab7ee631af6b45c0c1322fcc8ae26b6280a7d6 | <|skeleton|>
class Solution:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
res = ''
for e in strs:
res += str(len(e)) + ':' + e
return res
def decode(self, s):
"""Decodes a single string to a list of strings.... | the_stack_v2_python_sparse | python/271.encode_decode_strings.py | xiang525/leetcode_2018 | train | 0 | |
9c756a6141f5477340b66a77efaa26821bf7ef29 | [
"work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)\nif not work_pool:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Work pool \"{work_pool_name}\" not found.')\nreturn work_pool.id",
"work_pool = await models.workers.read_work_pool_b... | <|body_start_0|>
work_pool = await models.workers.read_work_pool_by_name(session=session, work_pool_name=work_pool_name)
if not work_pool:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Work pool "{work_pool_name}" not found.')
return work_pool.id
<|end_body_0|>
... | WorkerLookups | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_36k_train_007631 | 18,979 | permissive | [
{
"docstring": "Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based).",
"name": "_get_work_pool_id_from_name",
"signature": "async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUI... | 3 | stack_v2_sparse_classes_30k_train_020297 | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | Implement the Python class `WorkerLookups` described below.
Class description:
Implement the WorkerLookups class.
Method signatures and docstrings:
- async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID: Given a work pool name, return its ID. Used for translating user-facing... | 2c50d2b64c811c364cbc5faa2b5c80a742572090 | <|skeleton|>
class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
<|body_0|>
async d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkerLookups:
async def _get_work_pool_id_from_name(self, session: AsyncSession, work_pool_name: str) -> UUID:
"""Given a work pool name, return its ID. Used for translating user-facing APIs (which are name-based) to internal ones (which are id-based)."""
work_pool = await models.workers.read... | the_stack_v2_python_sparse | src/prefect/server/api/workers.py | PrefectHQ/prefect | train | 12,917 | |
0ff9f8dfcf09bba3409b5ba26f36bddc5e147438 | [
"logging.warn('%s is still experimental', self.__class__.__name__)\nsitecol = readinput.get_site_collection(self.oqparam)\nself.datastore['sitecol'] = self.sitecol = sitecol\nself.csm = get_composite_source_model(self.oqparam)\nself.gsims_by_grp = {grp.id: self.csm.info.get_gsims(grp.id) for sm in self.csm.source_m... | <|body_start_0|>
logging.warn('%s is still experimental', self.__class__.__name__)
sitecol = readinput.get_site_collection(self.oqparam)
self.datastore['sitecol'] = self.sitecol = sitecol
self.csm = get_composite_source_model(self.oqparam)
self.gsims_by_grp = {grp.id: self.csm.in... | UCERF classical calculator. | UcerfPSHACalculator | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UcerfPSHACalculator:
"""UCERF classical calculator."""
def pre_execute(self):
"""parse the logic tree and source model input"""
<|body_0|>
def execute(self):
"""Run in parallel `core_task(sources, sitecol, monitor)`, by parallelizing on the sources according to t... | stack_v2_sparse_classes_36k_train_007632 | 8,230 | permissive | [
{
"docstring": "parse the logic tree and source model input",
"name": "pre_execute",
"signature": "def pre_execute(self)"
},
{
"docstring": "Run in parallel `core_task(sources, sitecol, monitor)`, by parallelizing on the sources according to their weight and tectonic region type.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_000631 | Implement the Python class `UcerfPSHACalculator` described below.
Class description:
UCERF classical calculator.
Method signatures and docstrings:
- def pre_execute(self): parse the logic tree and source model input
- def execute(self): Run in parallel `core_task(sources, sitecol, monitor)`, by parallelizing on the s... | Implement the Python class `UcerfPSHACalculator` described below.
Class description:
UCERF classical calculator.
Method signatures and docstrings:
- def pre_execute(self): parse the logic tree and source model input
- def execute(self): Run in parallel `core_task(sources, sitecol, monitor)`, by parallelizing on the s... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class UcerfPSHACalculator:
"""UCERF classical calculator."""
def pre_execute(self):
"""parse the logic tree and source model input"""
<|body_0|>
def execute(self):
"""Run in parallel `core_task(sources, sitecol, monitor)`, by parallelizing on the sources according to t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UcerfPSHACalculator:
"""UCERF classical calculator."""
def pre_execute(self):
"""parse the logic tree and source model input"""
logging.warn('%s is still experimental', self.__class__.__name__)
sitecol = readinput.get_site_collection(self.oqparam)
self.datastore['sitecol']... | the_stack_v2_python_sparse | openquake/calculators/ucerf_classical.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
3d0f4d69c6646b6c39e6b9c4300419777c35b64b | [
"super().__init__(convert_charrefs=True)\nself.url = urlparse(url)\nself.generator = None\nself.version = None\nself._parsed_url = None\nself.server = None\nself.scriptpath = None",
"if self.version and value < self.version:\n return\nself.version = value",
"url = url.split('.php', 1)[0]\ntry:\n value, sc... | <|body_start_0|>
super().__init__(convert_charrefs=True)
self.url = urlparse(url)
self.generator = None
self.version = None
self._parsed_url = None
self.server = None
self.scriptpath = None
<|end_body_0|>
<|body_start_1|>
if self.version and value < self.... | Wiki HTML page parser. | WikiHTMLPageParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
<|body_0|>
def set_version(self, value) -> None:
"""Set highest version."""
<|body_1|>
def set_api_url(self, url) -> None:
"""Set api_url."""... | stack_v2_sparse_classes_36k_train_007633 | 10,845 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, url) -> None"
},
{
"docstring": "Set highest version.",
"name": "set_version",
"signature": "def set_version(self, value) -> None"
},
{
"docstring": "Set api_url.",
"name": "set_api_url",
... | 4 | stack_v2_sparse_classes_30k_train_005714 | Implement the Python class `WikiHTMLPageParser` described below.
Class description:
Wiki HTML page parser.
Method signatures and docstrings:
- def __init__(self, url) -> None: Initializer.
- def set_version(self, value) -> None: Set highest version.
- def set_api_url(self, url) -> None: Set api_url.
- def handle_star... | Implement the Python class `WikiHTMLPageParser` described below.
Class description:
Wiki HTML page parser.
Method signatures and docstrings:
- def __init__(self, url) -> None: Initializer.
- def set_version(self, value) -> None: Set highest version.
- def set_api_url(self, url) -> None: Set api_url.
- def handle_star... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
<|body_0|>
def set_version(self, value) -> None:
"""Set highest version."""
<|body_1|>
def set_api_url(self, url) -> None:
"""Set api_url."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikiHTMLPageParser:
"""Wiki HTML page parser."""
def __init__(self, url) -> None:
"""Initializer."""
super().__init__(convert_charrefs=True)
self.url = urlparse(url)
self.generator = None
self.version = None
self._parsed_url = None
self.server = Non... | the_stack_v2_python_sparse | pywikibot/site_detect.py | wikimedia/pywikibot | train | 432 |
21047cbed21bcd733e79c8dd6cba51a4797cf7e8 | [
"self.lookUp = {}\nfor i, s in enumerate(sentences):\n self.lookUp[s] = times[i]\nself.trie = Trie()\nfor s in sentences:\n self.trie.insert(s)\nself.keyword = ''",
"if c == '#':\n self.lookUp[self.keyword] = self.lookUp.get(self.keyword, 0) + 1\n self.trie.insert(self.keyword)\n self.keyword = ''\... | <|body_start_0|>
self.lookUp = {}
for i, s in enumerate(sentences):
self.lookUp[s] = times[i]
self.trie = Trie()
for s in sentences:
self.trie.insert(s)
self.keyword = ''
<|end_body_0|>
<|body_start_1|>
if c == '#':
self.lookUp[self.ke... | AutocompleteSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.lookUp = {}
... | stack_v2_sparse_classes_36k_train_007634 | 2,534 | no_license | [
{
"docstring": ":type sentences: List[str] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, sentences, times)"
},
{
"docstring": ":type c: str :rtype: List[str]",
"name": "input",
"signature": "def input(self, c)"
}
] | 2 | null | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str] | Implement the Python class `AutocompleteSystem` described below.
Class description:
Implement the AutocompleteSystem class.
Method signatures and docstrings:
- def __init__(self, sentences, times): :type sentences: List[str] :type times: List[int]
- def input(self, c): :type c: str :rtype: List[str]
<|skeleton|>
cla... | 90c000c3be70727cde4f7494fbbb1c425bfd3da4 | <|skeleton|>
class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
<|body_0|>
def input(self, c):
""":type c: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutocompleteSystem:
def __init__(self, sentences, times):
""":type sentences: List[str] :type times: List[int]"""
self.lookUp = {}
for i, s in enumerate(sentences):
self.lookUp[s] = times[i]
self.trie = Trie()
for s in sentences:
self.trie.insert... | the_stack_v2_python_sparse | categories/design/642. Design Search Autocomplete System.py | chenjienan/python-leetcode | train | 16 | |
242eb189caf722039a78e7fd95959aa28d00848e | [
"self.assertEqual(expression_parser.Token('sqrt').category, 'function')\nself.assertEqual(expression_parser.Token('abs').category, 'function')\nself.assertEqual(expression_parser.Token('tan').category, 'function')\nwith self.assertRaisesRegex(Exception, 'Invalid token: tan().'):\n expression_parser.Token('tan()'... | <|body_start_0|>
self.assertEqual(expression_parser.Token('sqrt').category, 'function')
self.assertEqual(expression_parser.Token('abs').category, 'function')
self.assertEqual(expression_parser.Token('tan').category, 'function')
with self.assertRaisesRegex(Exception, 'Invalid token: tan()... | Test the token module. | TokenUnitTests | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TokenUnitTests:
"""Test the token module."""
def test_is_function(self) -> None:
"""Tests for is_function method."""
<|body_0|>
def test_is_identifier(self) -> None:
"""Tests for is_identifier method."""
<|body_1|>
def test_is_number(self) -> None:
... | stack_v2_sparse_classes_36k_train_007635 | 28,629 | permissive | [
{
"docstring": "Tests for is_function method.",
"name": "test_is_function",
"signature": "def test_is_function(self) -> None"
},
{
"docstring": "Tests for is_identifier method.",
"name": "test_is_identifier",
"signature": "def test_is_identifier(self) -> None"
},
{
"docstring": "... | 4 | null | Implement the Python class `TokenUnitTests` described below.
Class description:
Test the token module.
Method signatures and docstrings:
- def test_is_function(self) -> None: Tests for is_function method.
- def test_is_identifier(self) -> None: Tests for is_identifier method.
- def test_is_number(self) -> None: Tests... | Implement the Python class `TokenUnitTests` described below.
Class description:
Test the token module.
Method signatures and docstrings:
- def test_is_function(self) -> None: Tests for is_function method.
- def test_is_identifier(self) -> None: Tests for is_identifier method.
- def test_is_number(self) -> None: Tests... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class TokenUnitTests:
"""Test the token module."""
def test_is_function(self) -> None:
"""Tests for is_function method."""
<|body_0|>
def test_is_identifier(self) -> None:
"""Tests for is_identifier method."""
<|body_1|>
def test_is_number(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TokenUnitTests:
"""Test the token module."""
def test_is_function(self) -> None:
"""Tests for is_function method."""
self.assertEqual(expression_parser.Token('sqrt').category, 'function')
self.assertEqual(expression_parser.Token('abs').category, 'function')
self.assertEqua... | the_stack_v2_python_sparse | core/domain/expression_parser_test.py | oppia/oppia | train | 6,172 |
2e220c2cdda1cb1dff44f5e1369069bd1bb803c3 | [
"if not value:\n value = u''\nelif isinstance(value, (tuple, list)):\n value = u'\\n'.join(value)\nreturn value",
"values = super(StringListField, self).clean(value)\nval = [val.strip() for val in values.splitlines() if val]\nreturn val"
] | <|body_start_0|>
if not value:
value = u''
elif isinstance(value, (tuple, list)):
value = u'\n'.join(value)
return value
<|end_body_0|>
<|body_start_1|>
values = super(StringListField, self).clean(value)
val = [val.strip() for val in values.splitlines() i... | StringListField | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
<|body_0|>
def clean(self, value):
"""Converts a value from the HTML form to ... | stack_v2_sparse_classes_36k_train_007636 | 1,735 | permissive | [
{
"docstring": "Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string",
"name": "prepare_value",
"signature": "def prepare_value(self, value)"
},
{
"docstring": "Converts a value from the HTML form to a ListField va... | 2 | null | Implement the Python class `StringListField` described below.
Class description:
Implement the StringListField class.
Method signatures and docstrings:
- def prepare_value(self, value): Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode stri... | Implement the Python class `StringListField` described below.
Class description:
Implement the StringListField class.
Method signatures and docstrings:
- def prepare_value(self, value): Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode stri... | 0fcb81e6a5edaf42c00c64faf001fc43b24e11c0 | <|skeleton|>
class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
<|body_0|>
def clean(self, value):
"""Converts a value from the HTML form to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringListField:
def prepare_value(self, value):
"""Converts a value into a value appropriate for a Textarea widget :arg value: None or a list of unicode strings :returns: unicode string"""
if not value:
value = u''
elif isinstance(value, (tuple, list)):
value =... | the_stack_v2_python_sparse | fjord/base/forms.py | mozilla/fjord | train | 18 | |
cd1cf625e58385e673ac0ad20f2346e6d7610a25 | [
"configs = None\nconfigsDao = ConfigsDao()\ntry:\n configs = configsDao.add(args)\nexcept Exception as e:\n abort(500, e)\nreturn configs",
"record = None\nconfigsDao = ConfigsDao()\ntry:\n record = configsDao.edit(args)\nexcept Exception as e:\n abort(500, e)\nreturn record",
"result = False\nids =... | <|body_start_0|>
configs = None
configsDao = ConfigsDao()
try:
configs = configsDao.add(args)
except Exception as e:
abort(500, e)
return configs
<|end_body_0|>
<|body_start_1|>
record = None
configsDao = ConfigsDao()
try:
... | configs module resource main service: add/delete/edit/view | ConfigsAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def get(self, args... | stack_v2_sparse_classes_36k_train_007637 | 5,875 | permissive | [
{
"docstring": "add",
"name": "post",
"signature": "def post(self, args)"
},
{
"docstring": "edit",
"name": "put",
"signature": "def put(self, args)"
},
{
"docstring": "delete",
"name": "delete",
"signature": "def delete(self, args)"
},
{
"docstring": "view",
... | 4 | stack_v2_sparse_classes_30k_train_013559 | Implement the Python class `ConfigsAPI` described below.
Class description:
configs module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def delete(self, args): delete
- def get(self, args): view | Implement the Python class `ConfigsAPI` described below.
Class description:
configs module resource main service: add/delete/edit/view
Method signatures and docstrings:
- def post(self, args): add
- def put(self, args): edit
- def delete(self, args): delete
- def get(self, args): view
<|skeleton|>
class ConfigsAPI:
... | 0fb1b604185a8bd8b72c1d2d527fb94bbaf46a86 | <|skeleton|>
class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
<|body_0|>
def put(self, args):
"""edit"""
<|body_1|>
def delete(self, args):
"""delete"""
<|body_2|>
def get(self, args... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigsAPI:
"""configs module resource main service: add/delete/edit/view"""
def post(self, args):
"""add"""
configs = None
configsDao = ConfigsDao()
try:
configs = configsDao.add(args)
except Exception as e:
abort(500, e)
return con... | the_stack_v2_python_sparse | app/modules/configs/resource.py | daitouli/baoaiback | train | 0 |
3e87e2d274064f2e2dfc735ef04b0a3810c7106e | [
"s = ['left', 'right']\nres = self.r.lpush('stdents', *s)\nprint(res)\nres = self.r.lrange('stdents', -1, 0)\nprint(res)\nreturn res",
"res = self.r.ltrim('stdents', -1, 0)\nprint(res)\nreturn res",
"res = self.r.lpop('stdents')\nprint(res)\nres = self.r.lrange('stdents', -1, 0)\nprint(res)\nreturn res",
"res... | <|body_start_0|>
s = ['left', 'right']
res = self.r.lpush('stdents', *s)
print(res)
res = self.r.lrange('stdents', -1, 0)
print(res)
return res
<|end_body_0|>
<|body_start_1|>
res = self.r.ltrim('stdents', -1, 0)
print(res)
return res
<|end_body_1... | TestList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestList:
def test_push(self):
"""lpush/rpush -- 从左/右插入数据"""
<|body_0|>
def test_ltrim(self):
"""ltrim -- 按一定长度修剪数据"""
<|body_1|>
def test_pop(self):
"""lpop/rpop -- 移除最左/最右的数据并返回"""
<|body_2|>
def test_pushx(self):
"""lpushx... | stack_v2_sparse_classes_36k_train_007638 | 3,577 | no_license | [
{
"docstring": "lpush/rpush -- 从左/右插入数据",
"name": "test_push",
"signature": "def test_push(self)"
},
{
"docstring": "ltrim -- 按一定长度修剪数据",
"name": "test_ltrim",
"signature": "def test_ltrim(self)"
},
{
"docstring": "lpop/rpop -- 移除最左/最右的数据并返回",
"name": "test_pop",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_000552 | Implement the Python class `TestList` described below.
Class description:
Implement the TestList class.
Method signatures and docstrings:
- def test_push(self): lpush/rpush -- 从左/右插入数据
- def test_ltrim(self): ltrim -- 按一定长度修剪数据
- def test_pop(self): lpop/rpop -- 移除最左/最右的数据并返回
- def test_pushx(self): lpushx/rpushx -- ... | Implement the Python class `TestList` described below.
Class description:
Implement the TestList class.
Method signatures and docstrings:
- def test_push(self): lpush/rpush -- 从左/右插入数据
- def test_ltrim(self): ltrim -- 按一定长度修剪数据
- def test_pop(self): lpop/rpop -- 移除最左/最右的数据并返回
- def test_pushx(self): lpushx/rpushx -- ... | 9434557f8e6b85ff7fc8f4699b253b054910d869 | <|skeleton|>
class TestList:
def test_push(self):
"""lpush/rpush -- 从左/右插入数据"""
<|body_0|>
def test_ltrim(self):
"""ltrim -- 按一定长度修剪数据"""
<|body_1|>
def test_pop(self):
"""lpop/rpop -- 移除最左/最右的数据并返回"""
<|body_2|>
def test_pushx(self):
"""lpushx... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestList:
def test_push(self):
"""lpush/rpush -- 从左/右插入数据"""
s = ['left', 'right']
res = self.r.lpush('stdents', *s)
print(res)
res = self.r.lrange('stdents', -1, 0)
print(res)
return res
def test_ltrim(self):
"""ltrim -- 按一定长度修剪数据"""
... | the_stack_v2_python_sparse | SQL/test_redis.py | 0Monster0/Python | train | 1 | |
c08fa6b6c41bbe8eebf5ec8d758ac05c153c9d33 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('kzhang21_ryuc', 'kzhang21_ryuc')\nurl = 'http://datamechanics.io/data/boston_entertainment.csv'\ndata = pd.read_csv(url, header=0)\ndata_entertainment = data[['BUSINESSNAME', 'LICCATDESC', 'Neighborhood'... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kzhang21_ryuc', 'kzhang21_ryuc')
url = 'http://datamechanics.io/data/boston_entertainment.csv'
data = pd.read_csv(url, header=0)
data_ente... | entertainment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class entertainment:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_36k_train_007639 | 4,668 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_002376 | Implement the Python class `entertainment` described below.
Class description:
Implement the entertainment class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | Implement the Python class `entertainment` described below.
Class description:
Implement the entertainment class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class entertainment:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class entertainment:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kzhang21_ryuc', 'kzhang21_ryuc')
... | the_stack_v2_python_sparse | kzhang21_ryuc/entertainment.py | maximega/course-2019-spr-proj | train | 2 | |
e3c3aaddc3bbe4b0799506eb57d18a31e8a07e27 | [
"self.__satellite_number = satellite_number\nself.__tle_url = tle_url\nself.__tle_file = tle_file\nself.__satellite_name = satellite_name\nself.__satellite_contact_name = satellite_contact_name\nself.__line1 = None\nself.__line2 = None\nself.__get_tle()",
"if self.__tle_file is not None:\n lines = input(self._... | <|body_start_0|>
self.__satellite_number = satellite_number
self.__tle_url = tle_url
self.__tle_file = tle_file
self.__satellite_name = satellite_name
self.__satellite_contact_name = satellite_contact_name
self.__line1 = None
self.__line2 = None
self.__get... | Class to retrieve and use a two line element set for a given satellite | SatelliteTle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SatelliteTle:
"""Class to retrieve and use a two line element set for a given satellite"""
def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elements/cubesat.txt', tle_file=None):
"""Constructor: satellite n... | stack_v2_sparse_classes_36k_train_007640 | 8,790 | no_license | [
{
"docstring": "Constructor: satellite number according to NORAD",
"name": "__init__",
"signature": "def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elements/cubesat.txt', tle_file=None)"
},
{
"docstring": "Method to ... | 4 | stack_v2_sparse_classes_30k_val_000550 | Implement the Python class `SatelliteTle` described below.
Class description:
Class to retrieve and use a two line element set for a given satellite
Method signatures and docstrings:
- def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elemen... | Implement the Python class `SatelliteTle` described below.
Class description:
Class to retrieve and use a two line element set for a given satellite
Method signatures and docstrings:
- def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elemen... | 0eed643eeaa9bcc35020b0b38399c25b616421c2 | <|skeleton|>
class SatelliteTle:
"""Class to retrieve and use a two line element set for a given satellite"""
def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elements/cubesat.txt', tle_file=None):
"""Constructor: satellite n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SatelliteTle:
"""Class to retrieve and use a two line element set for a given satellite"""
def __init__(self, satellite_number, satellite_name=None, satellite_contact_name=None, tle_url='http://www.celestrak.com/NORAD/elements/cubesat.txt', tle_file=None):
"""Constructor: satellite number accordi... | the_stack_v2_python_sparse | scripts/sgp4_to_iirv.py | nasa-itc/OrbitInviewPowerPrediction | train | 0 |
ee554dc4293d42926a2c638b9567e5448090ac38 | [
"QtGui.QAction.__init__(self, QtGui.QIcon(':/images/flip.png'), '&Flip Horizontal...', parent)\nself.setStatusTip('Flip the image horizontally')\nself.flipMatrix = QtGui.QMatrix(-1, 0, 0, 1, 0, 0)",
"cellWidget = self.toolBar.getSnappedWidget()\nlabel = cellWidget.label\nif not label.pixmap() or label.pixmap().is... | <|body_start_0|>
QtGui.QAction.__init__(self, QtGui.QIcon(':/images/flip.png'), '&Flip Horizontal...', parent)
self.setStatusTip('Flip the image horizontally')
self.flipMatrix = QtGui.QMatrix(-1, 0, 0, 1, 0, 0)
<|end_body_0|>
<|body_start_1|>
cellWidget = self.toolBar.getSnappedWidget()... | ImageViewerFlipAction is the action to flip the image | ImageViewerFlipAction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageViewerFlipAction:
"""ImageViewerFlipAction is the action to flip the image"""
def __init__(self, parent=None):
"""ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the action"""
<|body_0|>
def triggeredSlot(self, ch... | stack_v2_sparse_classes_36k_train_007641 | 14,880 | permissive | [
{
"docstring": "ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the action",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "toggledSlot(checked: boolean) -> None Execute the action when the button is clic... | 2 | null | Implement the Python class `ImageViewerFlipAction` described below.
Class description:
ImageViewerFlipAction is the action to flip the image
Method signatures and docstrings:
- def __init__(self, parent=None): ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the act... | Implement the Python class `ImageViewerFlipAction` described below.
Class description:
ImageViewerFlipAction is the action to flip the image
Method signatures and docstrings:
- def __init__(self, parent=None): ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the act... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class ImageViewerFlipAction:
"""ImageViewerFlipAction is the action to flip the image"""
def __init__(self, parent=None):
"""ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the action"""
<|body_0|>
def triggeredSlot(self, ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageViewerFlipAction:
"""ImageViewerFlipAction is the action to flip the image"""
def __init__(self, parent=None):
"""ImageViewerFlipAction(parent: QWidget) -> ImageViewerFlipAction Setup the image, status tip, etc. of the action"""
QtGui.QAction.__init__(self, QtGui.QIcon(':/images/flip... | the_stack_v2_python_sparse | vistrails_current/vistrails/packages/spreadsheet/widgets/imageviewer/imageviewer.py | lumig242/VisTrailsRecommendation | train | 3 |
457e437c64be492bce9a214ac8f00abe8939af78 | [
"if lo < 0:\n raise ValueError('lo must be non-negative')\nif hi is None:\n hi = len(nums) - 1\nwhile lo <= hi:\n mid = lo + hi >> 1\n if nums[mid] > target:\n hi = mid - 1\n elif nums[mid] < target:\n lo = mid + 1\n else:\n return mid\nreturn -1",
"if lo < 0:\n raise Val... | <|body_start_0|>
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(nums) - 1
while lo <= hi:
mid = lo + hi >> 1
if nums[mid] > target:
hi = mid - 1
elif nums[mid] < target:
lo... | BinSearch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinSearch:
def bin_search(self, nums, target, lo=0, hi=None):
"""基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:"""
<|body_0|>
def bs_strict_lower_bound(self, nums, target, lo=0, hi=None):
"""查找严格下界 :param nums: :param target: :param lo: :par... | stack_v2_sparse_classes_36k_train_007642 | 5,556 | no_license | [
{
"docstring": "基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:",
"name": "bin_search",
"signature": "def bin_search(self, nums, target, lo=0, hi=None)"
},
{
"docstring": "查找严格下界 :param nums: :param target: :param lo: :param hi: :return:",
"name": "bs_strict_lower_bo... | 6 | stack_v2_sparse_classes_30k_train_017091 | Implement the Python class `BinSearch` described below.
Class description:
Implement the BinSearch class.
Method signatures and docstrings:
- def bin_search(self, nums, target, lo=0, hi=None): 基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:
- def bs_strict_lower_bound(self, nums, target, lo=0... | Implement the Python class `BinSearch` described below.
Class description:
Implement the BinSearch class.
Method signatures and docstrings:
- def bin_search(self, nums, target, lo=0, hi=None): 基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:
- def bs_strict_lower_bound(self, nums, target, lo=0... | 215d513b3564a7a76db3d2b29e4acc341a68e8ee | <|skeleton|>
class BinSearch:
def bin_search(self, nums, target, lo=0, hi=None):
"""基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:"""
<|body_0|>
def bs_strict_lower_bound(self, nums, target, lo=0, hi=None):
"""查找严格下界 :param nums: :param target: :param lo: :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinSearch:
def bin_search(self, nums, target, lo=0, hi=None):
"""基本实现 不存在则返回-1 :param nums: :param target: :param lo: :param hi: :return:"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(nums) - 1
while lo <= hi:
... | the_stack_v2_python_sparse | python/bin-search/bin-search.py | euxuoh/leetcode | train | 0 | |
da2693cd5336b61e6ef1768c054b1339628eb31f | [
"self.__logger = State().getLogger('ConfigInput_Component_Logger')\nself.__logger.info('Starting __init__() with ConfigPath: ' + configPath, 'Input:__init__')\nself.__configParser = JsonParser(configPath)\nself.__logger.info('Finished __init__() with ConfigPath: ' + configPath, 'Input:__init__')",
"self.__logger.... | <|body_start_0|>
self.__logger = State().getLogger('ConfigInput_Component_Logger')
self.__logger.info('Starting __init__() with ConfigPath: ' + configPath, 'Input:__init__')
self.__configParser = JsonParser(configPath)
self.__logger.info('Finished __init__() with ConfigPath: ' + configPa... | ConfigInput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigInput:
def __init__(self, configPath):
"""Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput("/path/to/config")"""
<|body_0|>
def execute(self):
"""Führt den entsprechenden E... | stack_v2_sparse_classes_36k_train_007643 | 1,653 | no_license | [
{
"docstring": "Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput(\"/path/to/config\")",
"name": "__init__",
"signature": "def __init__(self, configPath)"
},
{
"docstring": "Führt den entsprechenden Einlesevo... | 2 | stack_v2_sparse_classes_30k_train_008279 | Implement the Python class `ConfigInput` described below.
Class description:
Implement the ConfigInput class.
Method signatures and docstrings:
- def __init__(self, configPath): Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput("/... | Implement the Python class `ConfigInput` described below.
Class description:
Implement the ConfigInput class.
Method signatures and docstrings:
- def __init__(self, configPath): Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput("/... | 3daaa72b193ebfb55894b47b6a752cdc2192bb6b | <|skeleton|>
class ConfigInput:
def __init__(self, configPath):
"""Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput("/path/to/config")"""
<|body_0|>
def execute(self):
"""Führt den entsprechenden E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigInput:
def __init__(self, configPath):
"""Constructor, initialisiert Membervariablen Parameters ---------- configPath : string Path to config file. Example ------- >>> ConfigInput("/path/to/config")"""
self.__logger = State().getLogger('ConfigInput_Component_Logger')
self.__logge... | the_stack_v2_python_sparse | SheetMusicScanner/ConfigInput_Component/ConfigInput/ConfigInput.py | jadeskon/score-scan | train | 0 | |
7e483edae90369c4aa451d46ece5517a2a13a678 | [
"super(AwakeablePeriodicThread, self).__init__(interval, target, name, on_shutdown)\nself.request = forksafe.Event()\nself.served = forksafe.Event()\nself.awake_lock = forksafe.Lock()",
"with self.awake_lock:\n self.served.clear()\n self.request.set()\n self.served.wait()",
"while not self.quit.is_set(... | <|body_start_0|>
super(AwakeablePeriodicThread, self).__init__(interval, target, name, on_shutdown)
self.request = forksafe.Event()
self.served = forksafe.Event()
self.awake_lock = forksafe.Lock()
<|end_body_0|>
<|body_start_1|>
with self.awake_lock:
self.served.clea... | Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request. | AwakeablePeriodicThread | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AwakeablePeriodicThread:
"""Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request."""
def __init__(self, interval, target, name=None, on_shutdown=None):
... | stack_v2_sparse_classes_36k_train_007644 | 5,013 | permissive | [
{
"docstring": "Create a periodic thread that can be awakened on demand.",
"name": "__init__",
"signature": "def __init__(self, interval, target, name=None, on_shutdown=None)"
},
{
"docstring": "Awake the thread.",
"name": "awake",
"signature": "def awake(self)"
},
{
"docstring":... | 3 | null | Implement the Python class `AwakeablePeriodicThread` described below.
Class description:
Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request.
Method signatures and docstrings:
- def __... | Implement the Python class `AwakeablePeriodicThread` described below.
Class description:
Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request.
Method signatures and docstrings:
- def __... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class AwakeablePeriodicThread:
"""Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request."""
def __init__(self, interval, target, name=None, on_shutdown=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AwakeablePeriodicThread:
"""Periodic thread that can be awakened on demand. This class can be used to instantiate a worker thread that will run its `run_periodic` function every `interval` seconds, or upon request."""
def __init__(self, interval, target, name=None, on_shutdown=None):
"""Create a ... | the_stack_v2_python_sparse | ddtrace/internal/periodic.py | DataDog/dd-trace-py | train | 461 |
1c5d85ce5b29c7a38d0f8a93c412244f5d578f4d | [
"self.table_name = table_name\nself.columns = columns\nif offset < 0:\n raise Exception('Invalid Offset: {}'.format(offset))\nself.offset = offset\nif limit is not None and limit < 0:\n raise Exception('Invalid Limit: {}'.format(limit))\nself.limit = limit\nself.rowid = rowid\nif offset > 0 or limit is not No... | <|body_start_0|>
self.table_name = table_name
self.columns = columns
if offset < 0:
raise Exception('Invalid Offset: {}'.format(offset))
self.offset = offset
if limit is not None and limit < 0:
raise Exception('Invalid Limit: {}'.format(limit))
sel... | Dataset reader for Mimir datasets. | MimirDatasetReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MimirDatasetReader:
"""Dataset reader for Mimir datasets."""
def __init__(self, table_name, columns, offset=0, limit=None, rowid=None):
"""Initialize information about the delimited file and the file format. Parameters ---------- table_name: string Name of table or view in database t... | stack_v2_sparse_classes_36k_train_007645 | 5,546 | permissive | [
{
"docstring": "Initialize information about the delimited file and the file format. Parameters ---------- table_name: string Name of table or view in database that contains the dataset columns: vizier.datastore.mimir.MimirDatasetColumn List of descriptors for columns in the database offset: int, optional Numbe... | 4 | stack_v2_sparse_classes_30k_train_003957 | Implement the Python class `MimirDatasetReader` described below.
Class description:
Dataset reader for Mimir datasets.
Method signatures and docstrings:
- def __init__(self, table_name, columns, offset=0, limit=None, rowid=None): Initialize information about the delimited file and the file format. Parameters --------... | Implement the Python class `MimirDatasetReader` described below.
Class description:
Dataset reader for Mimir datasets.
Method signatures and docstrings:
- def __init__(self, table_name, columns, offset=0, limit=None, rowid=None): Initialize information about the delimited file and the file format. Parameters --------... | e99f43df3df80ad5647f57d805c339257336ac73 | <|skeleton|>
class MimirDatasetReader:
"""Dataset reader for Mimir datasets."""
def __init__(self, table_name, columns, offset=0, limit=None, rowid=None):
"""Initialize information about the delimited file and the file format. Parameters ---------- table_name: string Name of table or view in database t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MimirDatasetReader:
"""Dataset reader for Mimir datasets."""
def __init__(self, table_name, columns, offset=0, limit=None, rowid=None):
"""Initialize information about the delimited file and the file format. Parameters ---------- table_name: string Name of table or view in database that contains ... | the_stack_v2_python_sparse | vizier/datastore/mimir/reader.py | VizierDB/web-api-async | train | 2 |
50f0cfc81045733051edf463c57f2da2fea7ae09 | [
"super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Example')\nself.coin_list = None\nself.player_list = None\nself.player_sprite = None\nself.score = 0\nself.set_mouse_visible(False)\narcade.set_background_color(arcade.color.AMAZON)",
"self.player_list = arcade.SpriteList()\nself.coin_list = arcade.SpriteList... | <|body_start_0|>
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Example')
self.coin_list = None
self.player_list = None
self.player_sprite = None
self.score = 0
self.set_mouse_visible(False)
arcade.set_background_color(arcade.color.AMAZON)
<|end_body_0|>
<... | Our custom Window Class | MyGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyGame:
"""Our custom Window Class"""
def __init__(self):
"""Initializer"""
<|body_0|>
def setup(self):
"""Set up the game and initialize the variables."""
<|body_1|>
def on_draw(self):
"""Draw everything"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_007646 | 2,529 | no_license | [
{
"docstring": "Initializer",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Set up the game and initialize the variables.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Draw everything",
"name": "on_draw",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_005316 | Implement the Python class `MyGame` described below.
Class description:
Our custom Window Class
Method signatures and docstrings:
- def __init__(self): Initializer
- def setup(self): Set up the game and initialize the variables.
- def on_draw(self): Draw everything | Implement the Python class `MyGame` described below.
Class description:
Our custom Window Class
Method signatures and docstrings:
- def __init__(self): Initializer
- def setup(self): Set up the game and initialize the variables.
- def on_draw(self): Draw everything
<|skeleton|>
class MyGame:
"""Our custom Window... | d20b3566a6d3631a632b17a1d78e03fbeb2517aa | <|skeleton|>
class MyGame:
"""Our custom Window Class"""
def __init__(self):
"""Initializer"""
<|body_0|>
def setup(self):
"""Set up the game and initialize the variables."""
<|body_1|>
def on_draw(self):
"""Draw everything"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyGame:
"""Our custom Window Class"""
def __init__(self):
"""Initializer"""
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, 'Sprite Example')
self.coin_list = None
self.player_list = None
self.player_sprite = None
self.score = 0
self.set_mouse_visible... | the_stack_v2_python_sparse | source/chapters/21_sprites_and_collisions/sprite_sample_coins.py | pvcraven/arcade_book | train | 35 |
dedeb942280b6694051aeffc932caef4fea109ad | [
"results = self.form.search()\nif results.count() == 0 and len(self.request.GET) > 0 and (not 'q' in self.request.GET):\n results = SearchQuerySet()\nself.vs_query = ''\nif 'q' in self.request.GET:\n self.vs_query += ' text:' + self.request.GET.get('q')\ndocuments_ids = self.get_documents().values_list('id', ... | <|body_start_0|>
results = self.form.search()
if results.count() == 0 and len(self.request.GET) > 0 and (not 'q' in self.request.GET):
results = SearchQuerySet()
self.vs_query = ''
if 'q' in self.request.GET:
self.vs_query += ' text:' + self.request.GET.get('q')
... | SearchDocumentView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchDocumentView:
def get_results(self):
"""Fetches the results via the form. Returns an empty list if there's no query to search with."""
<|body_0|>
def get_documents(self):
"""Return the documents accordingly to specific search field"""
<|body_1|>
de... | stack_v2_sparse_classes_36k_train_007647 | 12,858 | no_license | [
{
"docstring": "Fetches the results via the form. Returns an empty list if there's no query to search with.",
"name": "get_results",
"signature": "def get_results(self)"
},
{
"docstring": "Return the documents accordingly to specific search field",
"name": "get_documents",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_004473 | Implement the Python class `SearchDocumentView` described below.
Class description:
Implement the SearchDocumentView class.
Method signatures and docstrings:
- def get_results(self): Fetches the results via the form. Returns an empty list if there's no query to search with.
- def get_documents(self): Return the docum... | Implement the Python class `SearchDocumentView` described below.
Class description:
Implement the SearchDocumentView class.
Method signatures and docstrings:
- def get_results(self): Fetches the results via the form. Returns an empty list if there's no query to search with.
- def get_documents(self): Return the docum... | 29352a49a01bedb57be85896d0d31e627bb9e5bf | <|skeleton|>
class SearchDocumentView:
def get_results(self):
"""Fetches the results via the form. Returns an empty list if there's no query to search with."""
<|body_0|>
def get_documents(self):
"""Return the documents accordingly to specific search field"""
<|body_1|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchDocumentView:
def get_results(self):
"""Fetches the results via the form. Returns an empty list if there's no query to search with."""
results = self.form.search()
if results.count() == 0 and len(self.request.GET) > 0 and (not 'q' in self.request.GET):
results = Searc... | the_stack_v2_python_sparse | documents/views.py | yierva/festos | train | 0 | |
478dadc8ad8c25903315cd673659ee68e3ba44ea | [
"with m.If(self.interface.status_requested):\n with m.If(stall_condition):\n m.d.comb += self.interface.handshakes_out.stall.eq(1)\n with m.Else():\n m.d.comb += self.send_zlp()\nwith m.If(self.interface.handshakes_in.ack):\n m.d.comb += [write_strobe.eq(1), new_value_signal.eq(self.interface... | <|body_start_0|>
with m.If(self.interface.status_requested):
with m.If(stall_condition):
m.d.comb += self.interface.handshakes_out.stall.eq(1)
with m.Else():
m.d.comb += self.send_zlp()
with m.If(self.interface.handshakes_in.ack):
m.d.c... | Pure-gateware USB control request handler. | ControlRequestHandler | [
"BSD-3-Clause",
"CERN-OHL-P-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControlRequestHandler:
"""Pure-gateware USB control request handler."""
def handle_register_write_request(self, m, new_value_signal, write_strobe, stall_condition=0):
"""Fills in the current state with a request handler meant to set a register. Parameters: new_value_signal -- The sig... | stack_v2_sparse_classes_36k_train_007648 | 2,782 | permissive | [
{
"docstring": "Fills in the current state with a request handler meant to set a register. Parameters: new_value_signal -- The signal to receive the new value to be applied to the relevant register. write_strobe -- The signal which will be pulsed when new_value_signal contains a update. stall_condition -- If pr... | 2 | stack_v2_sparse_classes_30k_train_008122 | Implement the Python class `ControlRequestHandler` described below.
Class description:
Pure-gateware USB control request handler.
Method signatures and docstrings:
- def handle_register_write_request(self, m, new_value_signal, write_strobe, stall_condition=0): Fills in the current state with a request handler meant t... | Implement the Python class `ControlRequestHandler` described below.
Class description:
Pure-gateware USB control request handler.
Method signatures and docstrings:
- def handle_register_write_request(self, m, new_value_signal, write_strobe, stall_condition=0): Fills in the current state with a request handler meant t... | 1d8e9cfa6a3e577f255ff3544384a1442b3b015b | <|skeleton|>
class ControlRequestHandler:
"""Pure-gateware USB control request handler."""
def handle_register_write_request(self, m, new_value_signal, write_strobe, stall_condition=0):
"""Fills in the current state with a request handler meant to set a register. Parameters: new_value_signal -- The sig... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControlRequestHandler:
"""Pure-gateware USB control request handler."""
def handle_register_write_request(self, m, new_value_signal, write_strobe, stall_condition=0):
"""Fills in the current state with a request handler meant to set a register. Parameters: new_value_signal -- The signal to receiv... | the_stack_v2_python_sparse | luna/gateware/usb/request/control.py | greatscottgadgets/luna | train | 842 |
dab5075d356e6e99e81f0510720027b5b7d7a5b9 | [
"self.resource = resource\nself.inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=[])\nself.gen_inventory()",
"my_group = Group(name=groupname)\nif groupvars:\n for key, value in groupvars.iteritems():\n my_group.set_variable(key, value)\nfor host in hosts:\n hostname ... | <|body_start_0|>
self.resource = resource
self.inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=[])
self.gen_inventory()
<|end_body_0|>
<|body_start_1|>
my_group = Group(name=groupname)
if groupvars:
for key, value in groupvars.iterit... | this is my ansible inventory object. | MyInventory | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": va... | stack_v2_sparse_classes_36k_train_007649 | 8,816 | permissive | [
{
"docstring": "resource的数据格式是一个列表字典,比如 { \"group1\": { \"hosts\": [{\"hostname\": \"10.0.0.0\", \"port\": \"22\", \"username\": \"test\", \"password\": \"pass\"}, ...], \"vars\": {\"var1\": value1, \"var2\": value2, ...} } } 如果你只传入1个列表,这默认该列表内的所有主机属于my_group组,比如 [{\"hostname\": \"10.0.0.0\", \"port\": \"22\", ... | 3 | stack_v2_sparse_classes_30k_train_004307 | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "pass... | Implement the Python class `MyInventory` described below.
Class description:
this is my ansible inventory object.
Method signatures and docstrings:
- def __init__(self, resource, loader, variable_manager): resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "pass... | eb9373434d1ca069fd37ae6688d140d99a319294 | <|skeleton|>
class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyInventory:
"""this is my ansible inventory object."""
def __init__(self, resource, loader, variable_manager):
"""resource的数据格式是一个列表字典,比如 { "group1": { "hosts": [{"hostname": "10.0.0.0", "port": "22", "username": "test", "password": "pass"}, ...], "vars": {"var1": value1, "var2": value2, ...} } ... | the_stack_v2_python_sparse | apps/myapp/ansible_api.py.bak | chenhuxy/myweb | train | 14 |
fb00bdb3e18dfac7ceb21663aae124cdb418fe15 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.Tx, self.Rcv, self.TwoWay = (Tx, Rcv, TwoWay)\nsuper(AntennaType, self).__init__(**kwargs)",
"if self.Tx is not None:\n self.Tx._apply_reference_frequency(reference_fr... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.Tx, self.Rcv, self.TwoWay = (Tx, Rcv, TwoWay)
super(AntennaType, self).__init__(**kwargs)
<|end_body_0|>
<|body_sta... | Parameters that describe the antenna illumination patterns during the collection. | AntennaType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntennaType:
"""Parameters that describe the antenna illumination patterns during the collection."""
def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, **kwargs):
"""Parameters ---------- Tx : AntParamType Rcv : ... | stack_v2_sparse_classes_36k_train_007650 | 9,216 | permissive | [
{
"docstring": "Parameters ---------- Tx : AntParamType Rcv : AntParamType TwoWay : AntParamType kwargs",
"name": "__init__",
"signature": "def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, **kwargs)"
},
{
"docstring": "If ... | 2 | stack_v2_sparse_classes_30k_train_008240 | Implement the Python class `AntennaType` described below.
Class description:
Parameters that describe the antenna illumination patterns during the collection.
Method signatures and docstrings:
- def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, ... | Implement the Python class `AntennaType` described below.
Class description:
Parameters that describe the antenna illumination patterns during the collection.
Method signatures and docstrings:
- def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, ... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class AntennaType:
"""Parameters that describe the antenna illumination patterns during the collection."""
def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, **kwargs):
"""Parameters ---------- Tx : AntParamType Rcv : ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AntennaType:
"""Parameters that describe the antenna illumination patterns during the collection."""
def __init__(self, Tx: Optional[AntParamType]=None, Rcv: Optional[AntParamType]=None, TwoWay: Optional[AntParamType]=None, **kwargs):
"""Parameters ---------- Tx : AntParamType Rcv : AntParamType ... | the_stack_v2_python_sparse | sarpy/io/complex/sicd_elements/Antenna.py | ngageoint/sarpy | train | 192 |
baa53ed8831d6be35ed89aa1f4afd7a3d9ff3ac1 | [
"pbf = self\npbf.id = uuid\npbf.full_name = full_name\npbf.take_photo = take_photo\npbf.create_dt = create_dt\ndb.session.add(pbf)\ndb.session.commit()\nreturn self.id",
"sql = \" select pbf.id, pbf.full_name, g.student_id as authorize_name from info_people_basic_facts pbf join info_authorize a on pbf.id = a.bas... | <|body_start_0|>
pbf = self
pbf.id = uuid
pbf.full_name = full_name
pbf.take_photo = take_photo
pbf.create_dt = create_dt
db.session.add(pbf)
db.session.commit()
return self.id
<|end_body_0|>
<|body_start_1|>
sql = " select pbf.id, pbf.full_name, ... | InfoPeopleBasicFacts | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoPeopleBasicFacts:
def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt):
"""增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :return:"""
<|body_0|>
def check_full_name(self, login_user_id, full_name, relation_student):
... | stack_v2_sparse_classes_36k_train_007651 | 3,233 | no_license | [
{
"docstring": "增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :return:",
"name": "save_people_basic_facts",
"signature": "def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt)"
},
{
"docstring": "判断授权人是否存在 :param full_name: 授权人姓名 :return:",
"... | 3 | stack_v2_sparse_classes_30k_train_001679 | Implement the Python class `InfoPeopleBasicFacts` described below.
Class description:
Implement the InfoPeopleBasicFacts class.
Method signatures and docstrings:
- def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt): 增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :re... | Implement the Python class `InfoPeopleBasicFacts` described below.
Class description:
Implement the InfoPeopleBasicFacts class.
Method signatures and docstrings:
- def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt): 增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :re... | a7cf5a0b6daa372ed860dc43d92c55fcde764eb9 | <|skeleton|>
class InfoPeopleBasicFacts:
def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt):
"""增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :return:"""
<|body_0|>
def check_full_name(self, login_user_id, full_name, relation_student):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfoPeopleBasicFacts:
def save_people_basic_facts(self, uuid, full_name, take_photo, create_dt):
"""增加授权人信息 :param uuid: :param full_name: :param take_photo: :param create_dt: :return:"""
pbf = self
pbf.id = uuid
pbf.full_name = full_name
pbf.take_photo = take_photo
... | the_stack_v2_python_sparse | python_project/smart_schoolBus_project/app/schoolbus_situation/models/info_people_basic_facts_model.py | malqch/aibus | train | 0 | |
d9ee8d8817e3d95297c0e1f1c5df35f1f95ff8a9 | [
"self.legend = legend\nself.ax = ax\nself.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']\nself.line_styles = ['-', '-', '--', '-.', ':']\nself.line = []\nself.ax.set_ylabel(ylabel)\nself.ax.set_xlabel(xlabel)\nself.ax.set_title(title)\nself.ax.grid(True)\nself.init = True",
"if self.init == True:\n for i in rang... | <|body_start_0|>
self.legend = legend
self.ax = ax
self.colors = ['b', 'g', 'r', 'c', 'm', 'y', 'b']
self.line_styles = ['-', '-', '--', '-.', ':']
self.line = []
self.ax.set_ylabel(ylabel)
self.ax.set_xlabel(xlabel)
self.ax.set_title(title)
self.a... | Create each individual subplot. | myPlot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_36k_train_007652 | 6,668 | no_license | [
{
"docstring": "ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX: (\"data1\",\"data2\", ... , \"dataN\")",
"name": "__init__",
"signature": "def __init__(self, ax, xlabel=''... | 2 | stack_v2_sparse_classes_30k_train_001054 | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | Implement the Python class `myPlot` described below.
Class description:
Create each individual subplot.
Method signatures and docstrings:
- def __init__(self, ax, xlabel='', ylabel='', title='', legend=None): ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis tit... | 498a54f9777c5a849b0af491d9e76fcc470aa083 | <|skeleton|>
class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class myPlot:
"""Create each individual subplot."""
def __init__(self, ax, xlabel='', ylabel='', title='', legend=None):
"""ax - This is a handle to the axes of the figure xlable - Label of the x-axis ylable - Label of the y-axis title - Plot title legend - A tuple of strings that identify the data. EX... | the_stack_v2_python_sparse | DeepWNCS/Testbed/Plant-side/Plotter.py | msh0576/RL_WCPS | train | 1 |
757d5223549ca77f16c2a075dfbe55ea347c5b35 | [
"if not root:\n return []\nqueue, lst = (deque([root]), [])\nwhile queue:\n node = queue.popleft()\n lst.append(str(node.val) if node else '$')\n if node:\n queue.append(node.left)\n queue.append(node.right)\nreturn ' '.join(lst)",
"if not data:\n return None\nnodes = [TreeNode(int(va... | <|body_start_0|>
if not root:
return []
queue, lst = (deque([root]), [])
while queue:
node = queue.popleft()
lst.append(str(node.val) if node else '$')
if node:
queue.append(node.left)
queue.append(node.right)
... | 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_007653 | 1,284 | 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_014465 | 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:... | a6d3898d900f2063302dc1ffc3dafd61eefa79b7 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
queue, lst = (deque([root]), [])
while queue:
node = queue.popleft()
lst.append(str(node.val) if node else '$')... | the_stack_v2_python_sparse | 297_serialize_and_deserialize_binary_tree.py | YI-DING/daily-leetcode | train | 0 | |
82b11074e5d1b48130fa4f5bd3ba0701051e8122 | [
"canned_query_views = []\nif mr.project_id:\n with mr.profiler.Phase('getting canned queries'):\n canned_queries = self.services.features.GetCannedQueriesByProjectID(mr.cnxn, mr.project_id)\n canned_query_views = [savedqueries_helpers.SavedQueryView(sq, idx + 1, None, None) for idx, sq in enumerate(can... | <|body_start_0|>
canned_query_views = []
if mr.project_id:
with mr.profiler.Phase('getting canned queries'):
canned_queries = self.services.features.GetCannedQueriesByProjectID(mr.cnxn, mr.project_id)
canned_query_views = [savedqueries_helpers.SavedQueryView(sq, i... | IssueAdvancedSearch shows a form to enter an advanced search. | IssueAdvancedSearch | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for... | stack_v2_sparse_classes_36k_train_007654 | 4,674 | permissive | [
{
"docstring": "Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering the page.",
"name": "GatherPageData",
"signature": "def GatherPageData(self, mr)"
},
{
"docstring": "Proces... | 4 | stack_v2_sparse_classes_30k_train_013903 | Implement the Python class `IssueAdvancedSearch` described below.
Class description:
IssueAdvancedSearch shows a form to enter an advanced search.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed ... | Implement the Python class `IssueAdvancedSearch` described below.
Class description:
IssueAdvancedSearch shows a form to enter an advanced search.
Method signatures and docstrings:
- def GatherPageData(self, mr): Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed ... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IssueAdvancedSearch:
"""IssueAdvancedSearch shows a form to enter an advanced search."""
def GatherPageData(self, mr):
"""Build up a dictionary of data values to use when rendering the page. Args: mr: commonly used info parsed from the request. Returns: Dict of values used by EZT for rendering th... | the_stack_v2_python_sparse | appengine/monorail/tracker/issueadvsearch.py | xinghun61/infra | train | 2 |
67f306a14efe22cc061a03119327cd791dfc956b | [
"super().__init__(metric_names=metric_names, seconds_between_polls=seconds_between_polls, trial_indices_to_ignore=trial_indices_to_ignore, min_progression=min_progression, max_progression=max_progression, min_curves=min_curves, true_objective_metric_name=true_objective_metric_name, normalize_progressions=normalize_... | <|body_start_0|>
super().__init__(metric_names=metric_names, seconds_between_polls=seconds_between_polls, trial_indices_to_ignore=trial_indices_to_ignore, min_progression=min_progression, max_progression=max_progression, min_curves=min_curves, true_objective_metric_name=true_objective_metric_name, normalize_pro... | Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step. | PercentileEarlyStoppingStrategy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PercentileEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, percentile_threshold: float=50.0, min_progre... | stack_v2_sparse_classes_36k_train_007655 | 10,718 | permissive | [
{
"docstring": "Construct a PercentileEarlyStoppingStrategy instance. Args: metric_names: A (length-one) list of name of the metric to observe. If None will default to the objective metric on the Experiment's OptimizationConfig. seconds_between_polls: How often to poll the early stopping metric to evaluate whet... | 3 | null | Implement the Python class `PercentileEarlyStoppingStrategy` described below.
Class description:
Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step.
Method signatures and docstrings:
- def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_... | Implement the Python class `PercentileEarlyStoppingStrategy` described below.
Class description:
Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step.
Method signatures and docstrings:
- def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_... | 6443cee30cbf8cec290200a7420a3db08e4b5445 | <|skeleton|>
class PercentileEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, percentile_threshold: float=50.0, min_progre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PercentileEarlyStoppingStrategy:
"""Implements the strategy of stopping a trial if its performance falls below that of other trials at the same step."""
def __init__(self, metric_names: Optional[Iterable[str]]=None, seconds_between_polls: int=300, percentile_threshold: float=50.0, min_progression: Option... | the_stack_v2_python_sparse | ax/early_stopping/strategies/percentile.py | facebook/Ax | train | 2,207 |
cf360b3df06229fa5a122288dee32421a844311d | [
"super(UpConvBlock, self).__init__()\nself.upconv = UpConv2x2(in_channels)\nself.conv1 = conv3x3(in_channels, out_channels)\nself.conv2 = conv3x3(out_channels, out_channels)\nself.conv3 = conv3x3(out_channels, out_channels)\nself.norm = nn.BatchNorm2d(out_channels, track_running_stats=False)",
"xv = self.upconv(x... | <|body_start_0|>
super(UpConvBlock, self).__init__()
self.upconv = UpConv2x2(in_channels)
self.conv1 = conv3x3(in_channels, out_channels)
self.conv2 = conv3x3(out_channels, out_channels)
self.conv3 = conv3x3(out_channels, out_channels)
self.norm = nn.BatchNorm2d(out_chann... | UpConvBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
<|body_0|>
def forward(self, xh, xv):
"""Args: xh: torch Variable, activations f... | stack_v2_sparse_classes_36k_train_007656 | 6,249 | permissive | [
{
"docstring": "Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels)"
},
{
"docstring": "Args: xh: torch Variable, activations from same resolutio... | 2 | stack_v2_sparse_classes_30k_val_001058 | Implement the Python class `UpConvBlock` described below.
Class description:
Implement the UpConvBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps
- de... | Implement the Python class `UpConvBlock` described below.
Class description:
Implement the UpConvBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels): Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps
- de... | cae21c67316ed36529fdc2e470a105a9f847975c | <|skeleton|>
class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
<|body_0|>
def forward(self, xh, xv):
"""Args: xh: torch Variable, activations f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpConvBlock:
def __init__(self, in_channels, out_channels):
"""Args: in_channels: number of channels in input (1st) feature map out_channels: number of channels in output feature maps"""
super(UpConvBlock, self).__init__()
self.upconv = UpConv2x2(in_channels)
self.conv1 = conv3... | the_stack_v2_python_sparse | models/alex_fold_detector_norm_0130/architecture.py | seung-lab/SEAMLeSS | train | 7 | |
f7b8c0d585ee7adf56ff2eb9e0a3dec1b6766f35 | [
"if not last:\n self.ret.append(cur)\n return\nfor index, num in enumerate(last):\n self.buffer(cur + [num], last[:index] + last[index + 1:])",
"self.ret = []\nself.buffer([], nums)\nreturn self.ret"
] | <|body_start_0|>
if not last:
self.ret.append(cur)
return
for index, num in enumerate(last):
self.buffer(cur + [num], last[:index] + last[index + 1:])
<|end_body_0|>
<|body_start_1|>
self.ret = []
self.buffer([], nums)
return self.ret
<|end_bo... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buffer(self, cur, last):
""":type cur: list[int] :type last: list[int] :rtype :list[int]"""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not las... | stack_v2_sparse_classes_36k_train_007657 | 702 | no_license | [
{
"docstring": ":type cur: list[int] :type last: list[int] :rtype :list[int]",
"name": "buffer",
"signature": "def buffer(self, cur, last)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buffer(self, cur, last): :type cur: list[int] :type last: list[int] :rtype :list[int]
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buffer(self, cur, last): :type cur: list[int] :type last: list[int] :rtype :list[int]
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
c... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def buffer(self, cur, last):
""":type cur: list[int] :type last: list[int] :rtype :list[int]"""
<|body_0|>
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buffer(self, cur, last):
""":type cur: list[int] :type last: list[int] :rtype :list[int]"""
if not last:
self.ret.append(cur)
return
for index, num in enumerate(last):
self.buffer(cur + [num], last[:index] + last[index + 1:])
def p... | the_stack_v2_python_sparse | python/leetcode/46_Permutations.py | bobcaoge/my-code | train | 0 | |
5a3e77ed905eb5336b7117a3c08e681b279bf8ed | [
"X = check_array(X, dtype=np.float32, accept_sparse='csc')\nif quantile is None:\n return super(BaseTreeQuantileRegressor, self).predict(X, check_input=check_input)\nquantiles = np.zeros(X.shape[0])\nX_leaves = self.apply(X)\nunique_leaves = np.unique(X_leaves)\nfor leaf in unique_leaves:\n quantiles[X_leaves... | <|body_start_0|>
X = check_array(X, dtype=np.float32, accept_sparse='csc')
if quantile is None:
return super(BaseTreeQuantileRegressor, self).predict(X, check_input=check_input)
quantiles = np.zeros(X.shape[0])
X_leaves = self.apply(X)
unique_leaves = np.unique(X_leav... | BaseTreeQuantileRegressor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseTreeQuantileRegressor:
def predict(self, X, quantile=None, check_input=False):
"""Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and i... | stack_v2_sparse_classes_36k_train_007658 | 36,172 | permissive | [
{
"docstring": "Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. quantile : int, optional Value rangi... | 2 | null | Implement the Python class `BaseTreeQuantileRegressor` described below.
Class description:
Implement the BaseTreeQuantileRegressor class.
Method signatures and docstrings:
- def predict(self, X, quantile=None, check_input=False): Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of... | Implement the Python class `BaseTreeQuantileRegressor` described below.
Class description:
Implement the BaseTreeQuantileRegressor class.
Method signatures and docstrings:
- def predict(self, X, quantile=None, check_input=False): Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of... | 6af92e149491f6e5062495d87306b3625d12d992 | <|skeleton|>
class BaseTreeQuantileRegressor:
def predict(self, X, quantile=None, check_input=False):
"""Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseTreeQuantileRegressor:
def predict(self, X, quantile=None, check_input=False):
"""Predict regression value for X. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse mat... | the_stack_v2_python_sparse | tabular/src/autogluon/tabular/models/rf/rf_quantile.py | stjordanis/autogluon | train | 0 | |
8347b3e71ca8e903e681e95d23b340607289e06b | [
"self.index_to_result = []\nself.hashable_to_index = dict()\nfor i, result in enumerate(generator):\n self.index_to_result.append(result)\n hashable = to_hashable(result)\n if hashable in self.hashable_to_index:\n break\n else:\n self.hashable_to_index[hashable] = i\nelse:\n raise Excep... | <|body_start_0|>
self.index_to_result = []
self.hashable_to_index = dict()
for i, result in enumerate(generator):
self.index_to_result.append(result)
hashable = to_hashable(result)
if hashable in self.hashable_to_index:
break
else:
... | RepeatingSequence | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
<|body_0|>
def cycle_number(self, index):
"""Returns which 0-indexed cycle... | stack_v2_sparse_classes_36k_train_007659 | 24,260 | permissive | [
{
"docstring": "generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable.",
"name": "__init__",
"signature": "def __init__(self, generator, to_hashable=lambda x: x)"
},
{
"docstring": "Returns which 0-indexed cycle index appears in. cycle_num... | 3 | stack_v2_sparse_classes_30k_test_001063 | Implement the Python class `RepeatingSequence` described below.
Class description:
Implement the RepeatingSequence class.
Method signatures and docstrings:
- def __init__(self, generator, to_hashable=lambda x: x): generator should yield the things in the sequence. to_hashable should be used if things aren't nicely ha... | Implement the Python class `RepeatingSequence` described below.
Class description:
Implement the RepeatingSequence class.
Method signatures and docstrings:
- def __init__(self, generator, to_hashable=lambda x: x): generator should yield the things in the sequence. to_hashable should be used if things aren't nicely ha... | 42ded86513cac25272a880983746f261336fee96 | <|skeleton|>
class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
<|body_0|>
def cycle_number(self, index):
"""Returns which 0-indexed cycle... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepeatingSequence:
def __init__(self, generator, to_hashable=lambda x: x):
"""generator should yield the things in the sequence. to_hashable should be used if things aren't nicely hashable."""
self.index_to_result = []
self.hashable_to_index = dict()
for i, result in enumerate(... | the_stack_v2_python_sparse | dojo/adventofcode.com/2021/catchup/mcpower_utils.py | saramic/learning | train | 4 | |
cd8352b991c423d6d22caeec72b3e5430a0d5f87 | [
"self.size = 997\nself.hash_map = [None] * self.size\nfor i in range(self.size):\n self.hash_map[i] = ListNode(-1, -1)",
"hash_key = hash(key) % self.size\nhead = self.hash_map[hash_key]\nhead.insert(key, value)",
"hash_key = hash(key) % self.size\nhead = self.hash_map[hash_key]\nreturn head.get(key)",
"ha... | <|body_start_0|>
self.size = 997
self.hash_map = [None] * self.size
for i in range(self.size):
self.hash_map[i] = ListNode(-1, -1)
<|end_body_0|>
<|body_start_1|>
hash_key = hash(key) % self.size
head = self.hash_map[hash_key]
head.insert(key, value)
<|end_bo... | MyHashMap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def put(self, key, value):
"""value will always be non-negative. :type key: int :type value: int :rtype: None"""
<|body_1|>
def get(self, key):
"""Returns the va... | stack_v2_sparse_classes_36k_train_007660 | 2,448 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "value will always be non-negative. :type key: int :type value: int :rtype: None",
"name": "put",
"signature": "def put(self, key, value)"
},
{
"docstrin... | 4 | stack_v2_sparse_classes_30k_train_016621 | Implement the Python class `MyHashMap` described below.
Class description:
Implement the MyHashMap class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def put(self, key, value): value will always be non-negative. :type key: int :type value: int :rtype: None
- def get(... | Implement the Python class `MyHashMap` described below.
Class description:
Implement the MyHashMap class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def put(self, key, value): value will always be non-negative. :type key: int :type value: int :rtype: None
- def get(... | 768f7273d2cbba0e14ba9b18bf8a561058077848 | <|skeleton|>
class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def put(self, key, value):
"""value will always be non-negative. :type key: int :type value: int :rtype: None"""
<|body_1|>
def get(self, key):
"""Returns the va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyHashMap:
def __init__(self):
"""Initialize your data structure here."""
self.size = 997
self.hash_map = [None] * self.size
for i in range(self.size):
self.hash_map[i] = ListNode(-1, -1)
def put(self, key, value):
"""value will always be non-negative. ... | the_stack_v2_python_sparse | Week4/Design/706_design_hashmap.py | ravee-interview/DataStructures | train | 0 | |
cd8c2c5756c187eaf404357418dd5ac2a6810575 | [
"date_time = None\nevent_time = self._GetJSONValue(json_dict, 'EventTime')\nif event_time:\n try:\n date_time = dfdatetime_time_elements.TimeElementsInMicroseconds()\n date_time.CopyFromDateTimeString(event_time)\n except ValueError as exception:\n parser_mediator.ProduceExtractionWarning... | <|body_start_0|>
date_time = None
event_time = self._GetJSONValue(json_dict, 'EventTime')
if event_time:
try:
date_time = dfdatetime_time_elements.TimeElementsInMicroseconds()
date_time.CopyFromDateTimeString(event_time)
except ValueError a... | JSON-L parser plugin for AWS CloudTrail log files. | AWSCloudTrailLogJSONLPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSCloudTrailLogJSONLPlugin:
"""JSON-L parser plugin for AWS CloudTrail log files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such a... | stack_v2_sparse_classes_36k_train_007661 | 4,646 | permissive | [
{
"docstring": "Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. json_dict (dict): JSON dictionary of the log record.",
"name": "_ParseRecord",
"signature": "def _ParseRecord(self, parser_m... | 2 | null | Implement the Python class `AWSCloudTrailLogJSONLPlugin` described below.
Class description:
JSON-L parser plugin for AWS CloudTrail log files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, json_dict): Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates ... | Implement the Python class `AWSCloudTrailLogJSONLPlugin` described below.
Class description:
JSON-L parser plugin for AWS CloudTrail log files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, json_dict): Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AWSCloudTrailLogJSONLPlugin:
"""JSON-L parser plugin for AWS CloudTrail log files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSCloudTrailLogJSONLPlugin:
"""JSON-L parser plugin for AWS CloudTrail log files."""
def _ParseRecord(self, parser_mediator, json_dict):
"""Parses an AWS CloudTrail log record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and... | the_stack_v2_python_sparse | plaso/parsers/jsonl_plugins/aws_cloudtrail_log.py | log2timeline/plaso | train | 1,506 |
6c7b92d711a3149db2cf5a313b492ffda70a088a | [
"super().__init__(*args, **kwargs)\nself.num_parallel_samples = num_parallel_samples\nself.sample_noise = sample_noise",
"kernel_args, sigma = self.get_gp_params(F, past_target, past_time_feat, feat_static_cat)\ngp = GaussianProcess(sigma=sigma, kernel=self.kernel_output.kernel(kernel_args), context_length=self.c... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.num_parallel_samples = num_parallel_samples
self.sample_noise = sample_noise
<|end_body_0|>
<|body_start_1|>
kernel_args, sigma = self.get_gp_params(F, past_target, past_time_feat, feat_static_cat)
gp = GaussianProcess(sigm... | GaussianProcessPredictionNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive... | stack_v2_sparse_classes_36k_train_007662 | 9,486 | permissive | [
{
"docstring": "Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\\\sigma^2I` to the predictive covariance matrix. *args Variable length argument list. **kwargs Arbitrary keyword arguments.",
"name": "__init__",
"signature... | 2 | stack_v2_sparse_classes_30k_train_021316 | Implement the Python class `GaussianProcessPredictionNetwork` described below.
Class description:
Implement the GaussianProcessPredictionNetwork class.
Method signatures and docstrings:
- def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None: Parameters ---------- num_parallel_sam... | Implement the Python class `GaussianProcessPredictionNetwork` described below.
Class description:
Implement the GaussianProcessPredictionNetwork class.
Method signatures and docstrings:
- def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None: Parameters ---------- num_parallel_sam... | df4256b0e67120db555c109a1bf6cfa2b3bd3cd8 | <|skeleton|>
class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianProcessPredictionNetwork:
def __init__(self, num_parallel_samples: int, sample_noise: bool, *args, **kwargs) -> None:
"""Parameters ---------- num_parallel_samples Number of samples to be drawn. sample_noise Boolean to determine whether to add :math:`\\sigma^2I` to the predictive covariance ma... | the_stack_v2_python_sparse | src/gluonts/model/gp_forecaster/_network.py | mbohlkeschneider/gluon-ts | train | 54 | |
2944f6f3ab6fcc732264db3ce87dc8c8234e4075 | [
"super().__init__()\nwarnings.warn('PooledRNNEncoder is deprecated, please use the Pooling module in the Embedder object', DeprecationWarning)\nself.pooling = pooling\nself.rnn = RNNEncoder(input_size=input_size, hidden_size=hidden_size, n_layers=n_layers, rnn_type=rnn_type, dropout=dropout, ... | <|body_start_0|>
super().__init__()
warnings.warn('PooledRNNEncoder is deprecated, please use the Pooling module in the Embedder object', DeprecationWarning)
self.pooling = pooling
self.rnn = RNNEncoder(input_size=input_size, hidden_size=hidden_size, n_layers=n_lay... | Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN. | PooledRNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PooledRNNEncoder:
"""Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN."""
def __init__(self, input_size: int, hidden_size: int, n_layers: int=1, rnn_type: str='lstm', dropout: ... | stack_v2_sparse_classes_36k_train_007663 | 9,960 | permissive | [
{
"docstring": "Initializes the PooledRNNEncoder object. Parameters ---------- input_size : int The dimension the input data hidden_size : int The hidden dimension to encode the data in n_layers : int, optional The number of rnn layers, defaults to 1 rnn_type : str, optional The type of rnn cell, one of: `lstm`... | 2 | stack_v2_sparse_classes_30k_train_018297 | Implement the Python class `PooledRNNEncoder` described below.
Class description:
Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN.
Method signatures and docstrings:
- def __init__(self, input_size: int... | Implement the Python class `PooledRNNEncoder` described below.
Class description:
Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN.
Method signatures and docstrings:
- def __init__(self, input_size: int... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class PooledRNNEncoder:
"""Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN."""
def __init__(self, input_size: int, hidden_size: int, n_layers: int=1, rnn_type: str='lstm', dropout: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PooledRNNEncoder:
"""Implement an RNNEncoder with additional pooling. This class can be used to obtan a single encoded output for an input sequence. It also ignores the state of the RNN."""
def __init__(self, input_size: int, hidden_size: int, n_layers: int=1, rnn_type: str='lstm', dropout: float=0, bidi... | the_stack_v2_python_sparse | flambe/nn/rnn.py | cle-ros/flambe | train | 1 |
844d78141475afa1c4b7d0fbb47f475ad833e95c | [
"self.neurons = neurons\nself.activation = activation\nself.update_func = GatedMLP(neurons=neurons, activations=[activation] * len(neurons))\nself.weight_func = tf.keras.layers.Dense(neurons[-1], use_bias=False)\nsuper().__init__(**kwargs)",
"n_bonds = tf.shape(graph[Index.BOND_ATOM_INDICES])[0]\natoms = tf.resha... | <|body_start_0|>
self.neurons = neurons
self.activation = activation
self.update_func = GatedMLP(neurons=neurons, activations=[activation] * len(neurons))
self.weight_func = tf.keras.layers.Dense(neurons[-1], use_bias=False)
super().__init__(**kwargs)
<|end_body_0|>
<|body_start... | .. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u) | ConcatAtoms | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConcatAtoms:
""".. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u)"""
def __init__(self, neurons: List[int], activation: str='swish', **kwargs):
"""Concatenate the atom attributes and bond attributes (and optionally the state attributes, and then pass to an update function, e.g., an MLP Arg... | stack_v2_sparse_classes_36k_train_007664 | 7,328 | permissive | [
{
"docstring": "Concatenate the atom attributes and bond attributes (and optionally the state attributes, and then pass to an update function, e.g., an MLP Args: neurons (list): number of neurons in each layer activation (str): activation function",
"name": "__init__",
"signature": "def __init__(self, n... | 3 | stack_v2_sparse_classes_30k_train_019353 | Implement the Python class `ConcatAtoms` described below.
Class description:
.. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u)
Method signatures and docstrings:
- def __init__(self, neurons: List[int], activation: str='swish', **kwargs): Concatenate the atom attributes and bond attributes (and optionally the state attribut... | Implement the Python class `ConcatAtoms` described below.
Class description:
.. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u)
Method signatures and docstrings:
- def __init__(self, neurons: List[int], activation: str='swish', **kwargs): Concatenate the atom attributes and bond attributes (and optionally the state attribut... | 1f89ecb564b2691c810cd106c3476b15a8699bb7 | <|skeleton|>
class ConcatAtoms:
""".. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u)"""
def __init__(self, neurons: List[int], activation: str='swish', **kwargs):
"""Concatenate the atom attributes and bond attributes (and optionally the state attributes, and then pass to an update function, e.g., an MLP Arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConcatAtoms:
""".. math:: eij^\\prime = Update(vi⊕vj⊕eij⊕u)"""
def __init__(self, neurons: List[int], activation: str='swish', **kwargs):
"""Concatenate the atom attributes and bond attributes (and optionally the state attributes, and then pass to an update function, e.g., an MLP Args: neurons (l... | the_stack_v2_python_sparse | m3gnet/layers/_bond.py | materialsvirtuallab/m3gnet | train | 175 |
5ef40a68f91722394293ba6a8f83ea6fa1db0b90 | [
"string = np.array(['xyz'.encode('ascii')], dtype=object)\nshape = np.array([1, 3], dtype=np.int32)\narrays = [string, shape]\nstring_t = tf.placeholder(tf.string, [1])\nshape_t = tf.placeholder(tf.int32, [2])\ntensors = [string_t, shape_t]\npacked = packed_tensors.PackedTensors()\npacked.pack(tensors, arrays)\npac... | <|body_start_0|>
string = np.array(['xyz'.encode('ascii')], dtype=object)
shape = np.array([1, 3], dtype=np.int32)
arrays = [string, shape]
string_t = tf.placeholder(tf.string, [1])
shape_t = tf.placeholder(tf.int32, [2])
tensors = [string_t, shape_t]
packed = pac... | PackedTensorsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackedTensorsTest:
def test_pack_unpack(self):
"""Tests packing and unpacking tensors."""
<|body_0|>
def test_model(self):
"""Tests setting and getting model."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
string = np.array(['xyz'.encode('ascii')],... | stack_v2_sparse_classes_36k_train_007665 | 1,891 | permissive | [
{
"docstring": "Tests packing and unpacking tensors.",
"name": "test_pack_unpack",
"signature": "def test_pack_unpack(self)"
},
{
"docstring": "Tests setting and getting model.",
"name": "test_model",
"signature": "def test_model(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020023 | Implement the Python class `PackedTensorsTest` described below.
Class description:
Implement the PackedTensorsTest class.
Method signatures and docstrings:
- def test_pack_unpack(self): Tests packing and unpacking tensors.
- def test_model(self): Tests setting and getting model. | Implement the Python class `PackedTensorsTest` described below.
Class description:
Implement the PackedTensorsTest class.
Method signatures and docstrings:
- def test_pack_unpack(self): Tests packing and unpacking tensors.
- def test_model(self): Tests setting and getting model.
<|skeleton|>
class PackedTensorsTest:... | 00a229e5c23c248a7aa88081ec3e48bdd0df34c5 | <|skeleton|>
class PackedTensorsTest:
def test_pack_unpack(self):
"""Tests packing and unpacking tensors."""
<|body_0|>
def test_model(self):
"""Tests setting and getting model."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackedTensorsTest:
def test_pack_unpack(self):
"""Tests packing and unpacking tensors."""
string = np.array(['xyz'.encode('ascii')], dtype=object)
shape = np.array([1, 3], dtype=np.int32)
arrays = [string, shape]
string_t = tf.placeholder(tf.string, [1])
shape_t... | the_stack_v2_python_sparse | tensorflow_compression/python/util/packed_tensors_test.py | mengab/compression | train | 3 | |
48bef7e5f0aea7867dbd90b93337a12573fc0e34 | [
"l = 0\nr = len(s) - 1\nwhile l < r:\n if s[l] != s[r]:\n return self.is_palindrome(s, l, r - 1) or self.is_palindrome(s, l + 1, r)\n l += 1\n r -= 1\nreturn True",
"while l < r:\n if s[l] != s[r]:\n return False\n l += 1\n r -= 1\nreturn True"
] | <|body_start_0|>
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
return self.is_palindrome(s, l, r - 1) or self.is_palindrome(s, l + 1, r)
l += 1
r -= 1
return True
<|end_body_0|>
<|body_start_1|>
while l < r:
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""Args: s: str Return: bool"""
<|body_0|>
def is_palindrome(self, s, l, r):
"""Args: s: str l: int r: int Return: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = 0
r = len(s) - 1
whil... | stack_v2_sparse_classes_36k_train_007666 | 808 | no_license | [
{
"docstring": "Args: s: str Return: bool",
"name": "validPalindrome",
"signature": "def validPalindrome(self, s)"
},
{
"docstring": "Args: s: str l: int r: int Return: bool",
"name": "is_palindrome",
"signature": "def is_palindrome(self, s, l, r)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): Args: s: str Return: bool
- def is_palindrome(self, s, l, r): Args: s: str l: int r: int Return: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validPalindrome(self, s): Args: s: str Return: bool
- def is_palindrome(self, s, l, r): Args: s: str l: int r: int Return: bool
<|skeleton|>
class Solution:
def validPa... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def validPalindrome(self, s):
"""Args: s: str Return: bool"""
<|body_0|>
def is_palindrome(self, s, l, r):
"""Args: s: str l: int r: int Return: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validPalindrome(self, s):
"""Args: s: str Return: bool"""
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
return self.is_palindrome(s, l, r - 1) or self.is_palindrome(s, l + 1, r)
l += 1
r -= 1
return ... | the_stack_v2_python_sparse | code/680. 验证回文字符串 Ⅱ.py | AiZhanghan/Leetcode | train | 0 | |
6a2b77197a95c0c6c3b2deb9324a25979bd63c35 | [
"if self.value is not None:\n vals = [self.value]\nelse:\n vals = []\nif self.left is None and self.right is None:\n pass\nelif self.left is None:\n vals += self.right.preorder()\nelif self.right is None:\n vals += self.left.preorder()\nelse:\n vals += self.left.preorder()\n vals += self.right.... | <|body_start_0|>
if self.value is not None:
vals = [self.value]
else:
vals = []
if self.left is None and self.right is None:
pass
elif self.left is None:
vals += self.right.preorder()
elif self.right is None:
vals += sel... | Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing | Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
"""Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing"""
def preorder(self):
"""Preorder traversing Returns: list: all values in the tree that are... | stack_v2_sparse_classes_36k_train_007667 | 3,387 | no_license | [
{
"docstring": "Preorder traversing Returns: list: all values in the tree that are not None",
"name": "preorder",
"signature": "def preorder(self)"
},
{
"docstring": "Postorder traversing Returns: list: all values in the tree that are not None",
"name": "postorder",
"signature": "def pos... | 2 | null | Implement the Python class `Node` described below.
Class description:
Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing
Method signatures and docstrings:
- def preorder(self): Preorder ... | Implement the Python class `Node` described below.
Class description:
Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing
Method signatures and docstrings:
- def preorder(self): Preorder ... | e89b329bc9edd37d5d9986f07ca8a63d50686882 | <|skeleton|>
class Node:
"""Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing"""
def preorder(self):
"""Preorder traversing Returns: list: all values in the tree that are... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
"""Class for a node of a binary tree. Attributes: value: value of the node left: left child (Node or Leaf) right: right child(Node or Leaf) Methods for preorder and postorder traversing"""
def preorder(self):
"""Preorder traversing Returns: list: all values in the tree that are not None"""
... | the_stack_v2_python_sparse | StudentProblem/10.21.11.36/8/1569576977.py | LennartElbe/codeEvo | train | 0 |
d249acb48540e89f3c55617851d80935a2de8fb3 | [
"def backTrack(n, res, tmp, flag, row):\n if row == n:\n z = []\n for t in tmp:\n z.append(''.join(t))\n res.append(z)\n else:\n for col in range(n):\n if flag[row] and flag[n + col] and flag[2 * n + row + col] and flag[5 * n - 2 + col - row]:\n ... | <|body_start_0|>
def backTrack(n, res, tmp, flag, row):
if row == n:
z = []
for t in tmp:
z.append(''.join(t))
res.append(z)
else:
for col in range(n):
if flag[row] and flag[n + col] a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def totalNQueens0(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def backTrack(n, res, tmp, flag, row):
if row == n:
... | stack_v2_sparse_classes_36k_train_007668 | 2,109 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "totalNQueens",
"signature": "def totalNQueens(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "totalNQueens0",
"signature": "def totalNQueens0(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000101 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def totalNQueens(self, n): :type n: int :rtype: int
- def totalNQueens0(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 totalNQueens(self, n): :type n: int :rtype: int
- def totalNQueens0(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def totalNQueens(self, n):
"... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def totalNQueens(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def totalNQueens0(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 totalNQueens(self, n):
""":type n: int :rtype: int"""
def backTrack(n, res, tmp, flag, row):
if row == n:
z = []
for t in tmp:
z.append(''.join(t))
res.append(z)
else:
for ... | the_stack_v2_python_sparse | PythonCode/src/0052_N-Queens_II.py | oneyuan/CodeforFun | train | 0 | |
0c83b187faee66f104e24e60804e94717ae9b426 | [
"self.data = data.t\nself.n_folds = n_folds\nself.grouper = grouper\nif learner == 'logreg':\n self.learner = Orange.classification.logreg.LogRegLearner(stepwise_lr=True)\nelse:\n self.learner = Orange.classification.svm.LinearSVMLearner()\nif baseline:\n return\nif grouper is None:\n lf = list((i % n_f... | <|body_start_0|>
self.data = data.t
self.n_folds = n_folds
self.grouper = grouper
if learner == 'logreg':
self.learner = Orange.classification.logreg.LogRegLearner(stepwise_lr=True)
else:
self.learner = Orange.classification.svm.LinearSVMLearner()
... | Everything you want for your training needs | Trainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trainer:
"""Everything you want for your training needs"""
def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False):
"""Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quick and versatile) data (TabData): training data n_folds (i... | stack_v2_sparse_classes_36k_train_007669 | 9,142 | no_license | [
{
"docstring": "Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quick and versatile) data (TabData): training data n_folds (int): number of training folds grouper (str): grouping attribute for folds",
"name": "__init__",
"signature": "def __init__(self, data, n_folds=10, gr... | 3 | stack_v2_sparse_classes_30k_train_017439 | Implement the Python class `Trainer` described below.
Class description:
Everything you want for your training needs
Method signatures and docstrings:
- def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False): Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quic... | Implement the Python class `Trainer` described below.
Class description:
Everything you want for your training needs
Method signatures and docstrings:
- def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False): Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quic... | 5c0331a354640a10c072f79beebc94e0b9b5b092 | <|skeleton|>
class Trainer:
"""Everything you want for your training needs"""
def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False):
"""Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quick and versatile) data (TabData): training data n_folds (i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trainer:
"""Everything you want for your training needs"""
def __init__(self, data, n_folds=10, grouper=None, learner='svm', baseline=False):
"""Class initialiser Builds classifiers for data Learner is LinearSVM (reliable, quick and versatile) data (TabData): training data n_folds (int): number o... | the_stack_v2_python_sparse | old/classify.py | jrmyp/zeno | train | 0 |
63f29c22e7ae287a6a7d55727880a80d53550f8d | [
"groups = models.CmAlarmGroup.objects.all()\nserializer = serializers.CmAlarmGroupSerializer(groups, many=True)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"post_data = {}\ns_alarm_group = serializers.CmAlarmGroupSerializer(data=request.DATA['alarm_group'])\nif s_alarm_group.is_valid():\n al... | <|body_start_0|>
groups = models.CmAlarmGroup.objects.all()
serializer = serializers.CmAlarmGroupSerializer(groups, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
post_data = {}
s_alarm_group = serializers.CmAlarmGroupSeria... | GroupUserMappingList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupUserMappingList:
def get(self, request):
"""action : 9.1 get alarm groups :param request: :return:"""
<|body_0|>
def post(self, request):
"""action: 9.2 create alarm groups create a alarm group with user bonded"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_007670 | 10,115 | no_license | [
{
"docstring": "action : 9.1 get alarm groups :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "action: 9.2 create alarm groups create a alarm group with user bonded",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018244 | Implement the Python class `GroupUserMappingList` described below.
Class description:
Implement the GroupUserMappingList class.
Method signatures and docstrings:
- def get(self, request): action : 9.1 get alarm groups :param request: :return:
- def post(self, request): action: 9.2 create alarm groups create a alarm g... | Implement the Python class `GroupUserMappingList` described below.
Class description:
Implement the GroupUserMappingList class.
Method signatures and docstrings:
- def get(self, request): action : 9.1 get alarm groups :param request: :return:
- def post(self, request): action: 9.2 create alarm groups create a alarm g... | 44bc38c2c04fcaa928f58aeb8165fc1fff64bbcd | <|skeleton|>
class GroupUserMappingList:
def get(self, request):
"""action : 9.1 get alarm groups :param request: :return:"""
<|body_0|>
def post(self, request):
"""action: 9.2 create alarm groups create a alarm group with user bonded"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupUserMappingList:
def get(self, request):
"""action : 9.1 get alarm groups :param request: :return:"""
groups = models.CmAlarmGroup.objects.all()
serializer = serializers.CmAlarmGroupSerializer(groups, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
... | the_stack_v2_python_sparse | trunk/monitor_web/cm_alarm/group_user_views.py | wuhongyang/iass-web | train | 0 | |
57fc5e9d1c08e404ce7a544f3b2f8887298b0e31 | [
"if n == 0:\n return ''\nelse:\n num = n - 1 // 26\n print('num {}'.format(num))\n tmp = self.convertToTitle((n - 1) // 26)\n tmp2 = chr((n - 1) % 26 + ord('A'))\n return tmp + tmp2",
"ans = []\nwhile n:\n n = n - 1\n n = n // 26\n remain = n % 26\n ascii_code = ord('A') + remain\n ... | <|body_start_0|>
if n == 0:
return ''
else:
num = n - 1 // 26
print('num {}'.format(num))
tmp = self.convertToTitle((n - 1) // 26)
tmp2 = chr((n - 1) % 26 + ord('A'))
return tmp + tmp2
<|end_body_0|>
<|body_start_1|>
ans = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return ''
else:
num ... | stack_v2_sparse_classes_36k_train_007671 | 1,041 | no_license | [
{
"docstring": ":type n: int :rtype: str",
"name": "convertToTitle",
"signature": "def convertToTitle(self, n)"
},
{
"docstring": ":type n: int :rtype: str",
"name": "convertToTitle",
"signature": "def convertToTitle(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convertToTitle(self, n): :type n: int :rtype: str
- def convertToTitle(self, n): :type n: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convertToTitle(self, n): :type n: int :rtype: str
- def convertToTitle(self, n): :type n: int :rtype: str
<|skeleton|>
class Solution:
def convertToTitle(self, n):
... | 5714fdb2d8a89a68d68d07f7ffd3f6bcff5b2ccf | <|skeleton|>
class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def convertToTitle(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def convertToTitle(self, n):
""":type n: int :rtype: str"""
if n == 0:
return ''
else:
num = n - 1 // 26
print('num {}'.format(num))
tmp = self.convertToTitle((n - 1) // 26)
tmp2 = chr((n - 1) % 26 + ord('A'))
... | the_stack_v2_python_sparse | Python/string/168_excel_column.py | 01-Jacky/PracticeProblems | train | 0 | |
726d649d137b1aa6f53e882d0c8926372c0fa6d8 | [
"self.k = k\nself.datepart_method = datepart_method\nself.distance_metric = distance_metric\nself.linear_mixed = linear_mixed",
"test, scores = seasonal_independent_match(DTindex=df.index, DTindex_future=df.index, k=df.shape[0] - 1, datepart_method=self.datepart_method, distance_metric=self.distance_metric)\nfull... | <|body_start_0|>
self.k = k
self.datepart_method = datepart_method
self.distance_metric = distance_metric
self.linear_mixed = linear_mixed
<|end_body_0|>
<|body_start_1|>
test, scores = seasonal_independent_match(DTindex=df.index, DTindex_future=df.index, k=df.shape[0] - 1, date... | SeasonalityMotifImputer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeasonalityMotifImputer:
def __init__(self, k: int=3, datepart_method: str='simple_2', distance_metric: str='canberra', linear_mixed: bool=False):
"""Shares arg params with SeasonalityMotif model with which it has much in common. Args: k (int): n neighbors. More is smoother, fewer is mos... | stack_v2_sparse_classes_36k_train_007672 | 14,186 | permissive | [
{
"docstring": "Shares arg params with SeasonalityMotif model with which it has much in common. Args: k (int): n neighbors. More is smoother, fewer is most accurate, usually datepart_method (str): standard date part methods accepted distance_metirc (str): same as seaonality motif, ie 'mae', 'canberra' linear_mi... | 2 | null | Implement the Python class `SeasonalityMotifImputer` described below.
Class description:
Implement the SeasonalityMotifImputer class.
Method signatures and docstrings:
- def __init__(self, k: int=3, datepart_method: str='simple_2', distance_metric: str='canberra', linear_mixed: bool=False): Shares arg params with Sea... | Implement the Python class `SeasonalityMotifImputer` described below.
Class description:
Implement the SeasonalityMotifImputer class.
Method signatures and docstrings:
- def __init__(self, k: int=3, datepart_method: str='simple_2', distance_metric: str='canberra', linear_mixed: bool=False): Shares arg params with Sea... | f2a332d2f681cd20ec277a5e1a996e2457e915d3 | <|skeleton|>
class SeasonalityMotifImputer:
def __init__(self, k: int=3, datepart_method: str='simple_2', distance_metric: str='canberra', linear_mixed: bool=False):
"""Shares arg params with SeasonalityMotif model with which it has much in common. Args: k (int): n neighbors. More is smoother, fewer is mos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeasonalityMotifImputer:
def __init__(self, k: int=3, datepart_method: str='simple_2', distance_metric: str='canberra', linear_mixed: bool=False):
"""Shares arg params with SeasonalityMotif model with which it has much in common. Args: k (int): n neighbors. More is smoother, fewer is most accurate, us... | the_stack_v2_python_sparse | autots/tools/impute.py | winedarksea/AutoTS | train | 827 | |
49fd90d458f875467cb13a2bde9413bd17bc4d73 | [
"self._rep = rep\nself._output_sizes = output_sizes\nself._type = att_type\nself._scale = scale\nself._normalise = normalise\nif self._type == 'multihead':\n self._num_heads = num_heads",
"if self._rep == 'identity':\n k, q = (x1, x2)\nelif self._rep == 'mlp':\n k = batch_mlp(x1, self._output_sizes, 'att... | <|body_start_0|>
self._rep = rep
self._output_sizes = output_sizes
self._type = att_type
self._scale = scale
self._normalise = normalise
if self._type == 'multihead':
self._num_heads = num_heads
<|end_body_0|>
<|body_start_1|>
if self._rep == 'identit... | The Attention module. | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representat... | stack_v2_sparse_classes_36k_train_007673 | 15,798 | permissive | [
{
"docstring": "Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the context data. Args: rep: transformation to apply to contexts before computing attention. One of: ['identity','mlp']. output_sizes: l... | 2 | stack_v2_sparse_classes_30k_train_006772 | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Create attention module. Takes in context inputs, target inputs and representations of each cont... | Implement the Python class `Attention` described below.
Class description:
The Attention module.
Method signatures and docstrings:
- def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8): Create attention module. Takes in context inputs, target inputs and representations of each cont... | ddd3e586b01ba3a7f8b3721582aca7403649400e | <|skeleton|>
class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""The Attention module."""
def __init__(self, rep, output_sizes, att_type, scale=1.0, normalise=True, num_heads=8):
"""Create attention module. Takes in context inputs, target inputs and representations of each context input/output pair to output an aggregated representation of the co... | the_stack_v2_python_sparse | backup/model.py | jsikyoon/ASNP-RMR | train | 8 |
a9085eaf7a446c54f2a7226b5c8e7ae9a6661930 | [
"super(StreamPositionalEncoding, self).__init__()\nself.d_model = d_model\nself.xscale = math.sqrt(self.d_model)\nself.dropout = torch.nn.Dropout(p=dropout_rate)\nself.pe = None\nself.tmp = torch.tensor(0.0).expand(1, max_len)\nself.extend_pe(self.tmp.size(1), self.tmp.device, self.tmp.dtype)\nself._register_load_s... | <|body_start_0|>
super(StreamPositionalEncoding, self).__init__()
self.d_model = d_model
self.xscale = math.sqrt(self.d_model)
self.dropout = torch.nn.Dropout(p=dropout_rate)
self.pe = None
self.tmp = torch.tensor(0.0).expand(1, max_len)
self.extend_pe(self.tmp.si... | Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length. | StreamPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
... | stack_v2_sparse_classes_36k_train_007674 | 12,758 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, length, device, dtype)"
},
... | 3 | stack_v2_sparse_classes_30k_train_001414 | Implement the Python class `StreamPositionalEncoding` described below.
Class description:
Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model, dropout_rate, max_... | Implement the Python class `StreamPositionalEncoding` described below.
Class description:
Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length.
Method signatures and docstrings:
- def __init__(self, d_model, dropout_rate, max_... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamPositionalEncoding:
"""Streaming Positional encoding. Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int): Maximum input length."""
def __init__(self, d_model, dropout_rate, max_len=5000):
"""Construct an PositionalEncoding object."""
super(St... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transformer/embedding.py | espnet/espnet | train | 7,242 |
23befa0c1d4d45b83c174ee6e3d13e412e7dd23e | [
"super(TimeSlice, self).__init__()\nself.duration = duration\nself.event_timestamp = event_timestamp",
"if self.event_timestamp:\n return self.event_timestamp + self.duration * self._MICRO_SECONDS_PER_MINUTE\nreturn None",
"if self.event_timestamp:\n return self.event_timestamp - self.duration * self._MIC... | <|body_start_0|>
super(TimeSlice, self).__init__()
self.duration = duration
self.event_timestamp = event_timestamp
<|end_body_0|>
<|body_start_1|>
if self.event_timestamp:
return self.event_timestamp + self.duration * self._MICRO_SECONDS_PER_MINUTE
return None
<|end_... | Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None. | TimeSlice | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeSlice:
"""Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None."""
def __init__(self, event_timestamp, duration=5)... | stack_v2_sparse_classes_36k_train_007675 | 1,303 | permissive | [
{
"docstring": "Initializes the time slice. Args: event_timestamp (int): event timestamp of the time slice or None. duration (Optional[int]): duration of the time slice in minutes. The default is 5, which represent 2.5 minutes before and 2.5 minutes after the event timestamp.",
"name": "__init__",
"sign... | 3 | null | Implement the Python class `TimeSlice` described below.
Class description:
Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None.
Method signatur... | Implement the Python class `TimeSlice` described below.
Class description:
Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None.
Method signatur... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class TimeSlice:
"""Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None."""
def __init__(self, event_timestamp, duration=5)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeSlice:
"""Time slice. The time slice is used to provide a context of events around an event of interest. Attributes: duration (int): duration of the time slice in minutes. event_timestamp (int): event timestamp of the time slice or None."""
def __init__(self, event_timestamp, duration=5):
"""... | the_stack_v2_python_sparse | plaso/cli/time_slices.py | log2timeline/plaso | train | 1,506 |
8de29fac7d06b9a91866a09bfdfca2dc12ed9fbc | [
"s = '1'\nfor _ in range(n - 1):\n cur = s[0]\n counter = 0\n temp = ''\n for char in s:\n if char == cur:\n counter += 1\n else:\n temp += str(counter) + cur\n cur = char\n counter = 1\n temp += str(counter) + cur\n s = temp\nreturn s",
... | <|body_start_0|>
s = '1'
for _ in range(n - 1):
cur = s[0]
counter = 0
temp = ''
for char in s:
if char == cur:
counter += 1
else:
temp += str(counter) + cur
cur = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay1(self, n):
""":type n: int :rtype: str"""
<|body_1|>
def countAndSay2(self, n):
""":type n: int :rtype: str"""
<|body_2|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_007676 | 2,312 | no_license | [
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay",
"signature": "def countAndSay(self, n)"
},
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay1",
"signature": "def countAndSay1(self, n)"
},
{
"docstring": ":type n: int :rtype: str",
"name": "coun... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay1(self, n): :type n: int :rtype: str
- def countAndSay2(self, n): :type n: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay1(self, n): :type n: int :rtype: str
- def countAndSay2(self, n): :type n: int :rtype: str
<|skeleton|>
class... | 6bee015dac47603253018fd773920e62b29f3f20 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay1(self, n):
""":type n: int :rtype: str"""
<|body_1|>
def countAndSay2(self, n):
""":type n: int :rtype: str"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
s = '1'
for _ in range(n - 1):
cur = s[0]
counter = 0
temp = ''
for char in s:
if char == cur:
counter += 1
else:
... | the_stack_v2_python_sparse | 38-count-and-say.py | nanli-7/algorithms | train | 4 | |
139d08b545f60dd4f06025fb9651b6dec03011c6 | [
"if self.storage_type != StorageType.AZURE_BLOB_STORAGE.value:\n raise ValueError(f'SAS URLs can only be retrieved for bundles on Azure Blob Storage. Storage type is: {self.storage_type}.')\nblob_name = path.replace(f'{StorageURLScheme.AZURE_BLOB_STORAGE.value}{AZURE_BLOB_ACCOUNT_NAME}/{AZURE_BLOB_CONTAINER_NAME... | <|body_start_0|>
if self.storage_type != StorageType.AZURE_BLOB_STORAGE.value:
raise ValueError(f'SAS URLs can only be retrieved for bundles on Azure Blob Storage. Storage type is: {self.storage_type}.')
blob_name = path.replace(f'{StorageURLScheme.AZURE_BLOB_STORAGE.value}{AZURE_BLOB_ACCOUN... | A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by parsing a given bundle link URL by calling parse_bundle_url(). Attributes: storage_type... | LinkedBundlePath | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinkedBundlePath:
"""A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by parsing a given bundle link URL by calling ... | stack_v2_sparse_classes_36k_train_007677 | 15,993 | permissive | [
{
"docstring": "Generates a SAS URL that can be used to read the given blob for one hour. Args: permission: Different permission granted by SAS token. `r`, `w` or `wr`. `r` for read permission, and `w` for write permission.",
"name": "_get_azure_sas_url",
"signature": "def _get_azure_sas_url(self, path,... | 4 | stack_v2_sparse_classes_30k_train_002491 | Implement the Python class `LinkedBundlePath` described below.
Class description:
A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by pars... | Implement the Python class `LinkedBundlePath` described below.
Class description:
A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by pars... | 5be8cb3fa4b43c9e7e8f0a3b217644a7f0a39628 | <|skeleton|>
class LinkedBundlePath:
"""A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by parsing a given bundle link URL by calling ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinkedBundlePath:
"""A LinkedBundlePath refers to a path that points to the location of a linked bundle within a specific storage location. It can either point directly to the bundle, or to a file that is located within that bundle. It is constructed by parsing a given bundle link URL by calling parse_bundle_... | the_stack_v2_python_sparse | codalab/common.py | codalab/codalab-worksheets | train | 126 |
a039e1dea7d55097ca9d14ebdcf513d2ce2e05a0 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | XArmShuidiServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XArmShuidiServicer:
"""Missing associated documentation comment in .proto file."""
def arm_move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def arm_get_jnt_values(self, request, context):
"""Missi... | stack_v2_sparse_classes_36k_train_007678 | 8,487 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "arm_move_jspace_path",
"signature": "def arm_move_jspace_path(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "arm_get_jnt_values",
"signatur... | 5 | stack_v2_sparse_classes_30k_train_007499 | Implement the Python class `XArmShuidiServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def arm_move_jspace_path(self, request, context): Missing associated documentation comment in .proto file.
- def arm_get_jnt_values(self, req... | Implement the Python class `XArmShuidiServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def arm_move_jspace_path(self, request, context): Missing associated documentation comment in .proto file.
- def arm_get_jnt_values(self, req... | 405f15be1a3f7740f3eb7d234d96998f6d057a54 | <|skeleton|>
class XArmShuidiServicer:
"""Missing associated documentation comment in .proto file."""
def arm_move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def arm_get_jnt_values(self, request, context):
"""Missi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XArmShuidiServicer:
"""Missing associated documentation comment in .proto file."""
def arm_move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not imple... | the_stack_v2_python_sparse | robot_con/xarm_shuidi/xarm_shuidi_pb2_grpc.py | Shogo-Hayakawa/wrs | train | 0 |
bef543a19d01266512e70723682a7ff49e5b3650 | [
"from motey.di.app_module import DIRepositories\nresults = DIRepositories.capability_repository().all()\nreturn (jsonify(results), 200)",
"from motey.di.app_module import DIRepositories\nif request.content_type == 'application/json':\n data = request.json\n try:\n validate(data, capability_json_schem... | <|body_start_0|>
from motey.di.app_module import DIRepositories
results = DIRepositories.capability_repository().all()
return (jsonify(results), 200)
<|end_body_0|>
<|body_start_1|>
from motey.di.app_module import DIRepositories
if request.content_type == 'application/json':
... | This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched. | Capabilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Capabilities:
"""This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched."""
def get(self):
"""Returns a list off all existing... | stack_v2_sparse_classes_36k_train_007679 | 3,703 | permissive | [
{
"docstring": "Returns a list off all existing capabilities of this node. :return: a JSON object with all the existing capabilities of this node",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a list of new capabilities or at least a single one to the node. The content type... | 3 | stack_v2_sparse_classes_30k_train_005760 | Implement the Python class `Capabilities` described below.
Class description:
This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched.
Method signatures and doc... | Implement the Python class `Capabilities` described below.
Class description:
This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched.
Method signatures and doc... | d3f07d9d161d97ec2c19f66167dfb26eb9c6e616 | <|skeleton|>
class Capabilities:
"""This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched."""
def get(self):
"""Returns a list off all existing... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Capabilities:
"""This REST API endpoint for capability handling. A capability is basically a capability for the whole node. New capabilities can be added or deleted via this endpoint or a list with the existing ones can be fetched."""
def get(self):
"""Returns a list off all existing capabilities... | the_stack_v2_python_sparse | motey/communication/api_routes/capabilities.py | Neoklosch/Motey | train | 0 |
eb97a0ab08ff19e2e71e842b5af03e127a6d9cf3 | [
"s = s.strip()\ndot_seen = False\ne_seen = False\nnum_seen = False\nfor i, a in enumerate(s):\n if a.isdigit():\n num_seen = True\n elif a == '.':\n if e_seen or dot_seen:\n return False\n dot_seen = True\n elif a == 'e':\n if e_seen or not num_seen:\n retu... | <|body_start_0|>
s = s.strip()
dot_seen = False
e_seen = False
num_seen = False
for i, a in enumerate(s):
if a.isdigit():
num_seen = True
elif a == '.':
if e_seen or dot_seen:
return False
... | 指数 e 后面只能是数字 | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
<|body_0|>
def isNumber2(self, s: str):
... | stack_v2_sparse_classes_36k_train_007680 | 3,962 | permissive | [
{
"docstring": "提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现",
"name": "isNumber",
"signature": "def isNumber(self, s: str)"
},
{
"docstring": "提示:有限状态机 FSM 状态转移图见同目录下 FSM.pn... | 2 | stack_v2_sparse_classes_30k_train_004350 | Implement the Python class `Solution` described below.
Class description:
指数 e 后面只能是数字
Method signatures and docstrings:
- def isNumber(self, s: str): 提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现
... | Implement the Python class `Solution` described below.
Class description:
指数 e 后面只能是数字
Method signatures and docstrings:
- def isNumber(self, s: str): 提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现
... | 889d8fa489f1f2719c5a0dafd3ae51df7b4bf978 | <|skeleton|>
class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
<|body_0|>
def isNumber2(self, s: str):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""指数 e 后面只能是数字"""
def isNumber(self, s: str):
"""提示: 考虑所有情况,下面这些情况肯定不是数字: 1、如果当前字符是小数点,且前面已经出现过小数点或者 'e'; 2、如果当前字符是 'e',且前面已经出现过 'e',或者前面没有出现过数字; 3、如果 '+-' 不是出现在最开始,或者不是紧跟在 'e' 后 4、如果串为空,或者只含有 '.' 或者只含有 '+-',而没有数字出现"""
s = s.strip()
dot_seen = False
e_seen = Fal... | the_stack_v2_python_sparse | LeetCode/65-有效数字/isNumber.py | jinbooooom/coding-for-algorithms | train | 14 |
96b316984e58f7aeac9c9ece573eb3387602c0c4 | [
"user = g.user\nproject = Project.find_by_id(project_id)\nproject_dump = ProjectSchema().dump(project)\nfor project_users in project.users:\n if project_users.user_id == user.id:\n project_dump['myRole'] = project_users.role\nreturn (project_dump, HTTPStatus.OK)",
"user = g.user\nproject = Project.find_... | <|body_start_0|>
user = g.user
project = Project.find_by_id(project_id)
project_dump = ProjectSchema().dump(project)
for project_users in project.users:
if project_users.user_id == user.id:
project_dump['myRole'] = project_users.role
return (project_du... | Resource for managing get project by id. | ProjectResourceById | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
<|body_0|>
def delete(project_id):
"""Delete project."""
<|body_1|>
def put(project_id):
"""Update project details."""
... | stack_v2_sparse_classes_36k_train_007681 | 6,357 | permissive | [
{
"docstring": "Get project details.",
"name": "get",
"signature": "def get(project_id)"
},
{
"docstring": "Delete project.",
"name": "delete",
"signature": "def delete(project_id)"
},
{
"docstring": "Update project details.",
"name": "put",
"signature": "def put(project_... | 4 | stack_v2_sparse_classes_30k_train_019833 | Implement the Python class `ProjectResourceById` described below.
Class description:
Resource for managing get project by id.
Method signatures and docstrings:
- def get(project_id): Get project details.
- def delete(project_id): Delete project.
- def put(project_id): Update project details.
- def patch(project_id): ... | Implement the Python class `ProjectResourceById` described below.
Class description:
Resource for managing get project by id.
Method signatures and docstrings:
- def get(project_id): Get project details.
- def delete(project_id): Delete project.
- def put(project_id): Update project details.
- def patch(project_id): ... | 3bfe09c100a0f5b98d61228324336d5f45ad93ad | <|skeleton|>
class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
<|body_0|>
def delete(project_id):
"""Delete project."""
<|body_1|>
def put(project_id):
"""Update project details."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectResourceById:
"""Resource for managing get project by id."""
def get(project_id):
"""Get project details."""
user = g.user
project = Project.find_by_id(project_id)
project_dump = ProjectSchema().dump(project)
for project_users in project.users:
i... | the_stack_v2_python_sparse | selfservice-api/src/selfservice_api/resources/project.py | bcgov/BCSC-SS | train | 2 |
ec378a4eafebcc67cd3f41015e660edb3dfb0c18 | [
"super(DataQualityOperator, self).__init__(*args, **kwargs)\nself.conn_id = conn_id\nself.table = table\nself.pkey = pkey\nself.params = {'pkey': S.Identifier(self.pkey), 'table': S.Identifier(self.table)}\nself.qf_rowcount = S.SQL(DataQualityOperator.q_rowcount).format(**self.params)\nself.qf_pkeycount = S.SQL(Dat... | <|body_start_0|>
super(DataQualityOperator, self).__init__(*args, **kwargs)
self.conn_id = conn_id
self.table = table
self.pkey = pkey
self.params = {'pkey': S.Identifier(self.pkey), 'table': S.Identifier(self.table)}
self.qf_rowcount = S.SQL(DataQualityOperator.q_rowcoun... | Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count the number of rows per primary key - qf_ stands for a template query q_ formatted with a... | DataQualityOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataQualityOperator:
"""Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count the number of rows per primary key - qf_ ... | stack_v2_sparse_classes_36k_train_007682 | 2,790 | no_license | [
{
"docstring": "Args: conn_id (str): in Airflow Connection Database, name of Redshift connection pkey (str): Name of primary key of table table (str): Name of table *args: **kwargs:",
"name": "__init__",
"signature": "def __init__(self, conn_id='', pkey='', table='', *args, **kwargs)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_014938 | Implement the Python class `DataQualityOperator` described below.
Class description:
Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count th... | Implement the Python class `DataQualityOperator` described below.
Class description:
Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count th... | ec7f881b6e11d7e3294176128290fdd1ad684fc0 | <|skeleton|>
class DataQualityOperator:
"""Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count the number of rows per primary key - qf_ ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataQualityOperator:
"""Data Quality Checks: 1. Check the target table has a positive number of rows 2. Check the target table has no duplicate primary key Properties: - q_rowcount: query used to count the number of rows - q_pkeycount: query used to count the number of rows per primary key - qf_ stands for a ... | the_stack_v2_python_sparse | p5_pipeline_airflow/airflowcode/plugins/operators/data_quality.py | ogierpaul/Udacity-Data-Engineer-NanoDegree | train | 1 |
fa3f56273d53b25b68435519d3bcf9c8bcf07dd7 | [
"self.nums = nums\nself.sumList = [0] * len(nums)\nif not nums:\n self.sumList = None\nelse:\n self.sumList[0] = nums[0]\n for index in range(1, len(nums)):\n self.sumList[index] = self.sumList[index - 1] + self.nums[index]",
"if not self.sumList:\n return\nif i >= len(self.nums):\n return\n... | <|body_start_0|>
self.nums = nums
self.sumList = [0] * len(nums)
if not nums:
self.sumList = None
else:
self.sumList[0] = nums[0]
for index in range(1, len(nums)):
self.sumList[index] = self.sumList[index - 1] + self.nums[index]
<|end_b... | 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|>
self.nums = nums
self.sumList = [0] * len(nums)
... | stack_v2_sparse_classes_36k_train_007683 | 1,282 | 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):
... | 807ba32ed7802b756e93dfe44264dac5bb9317a0 | <|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]"""
self.nums = nums
self.sumList = [0] * len(nums)
if not nums:
self.sumList = None
else:
self.sumList[0] = nums[0]
for index in range(1, len(nums)):
self.su... | the_stack_v2_python_sparse | num301_400/num301_310/num303.py | guozhaoxin/leetcode | train | 0 | |
ef9872cf2b7f55967088d64b5e5eb4f641319a88 | [
"threading.Thread.__init__(self)\nself._queue = queue\nself._execution_queue = execution_queue\nself._context = context",
"threading.Thread.run(self)\ntest_step = self._queue.get()\ntry:\n test_step.run(self._context)\n self._execution_queue.put((test_step.name, test_step.ts_verdict_msg))\nexcept Exception ... | <|body_start_0|>
threading.Thread.__init__(self)
self._queue = queue
self._execution_queue = execution_queue
self._context = context
<|end_body_0|>
<|body_start_1|>
threading.Thread.run(self)
test_step = self._queue.get()
try:
test_step.run(self._cont... | Implements thread which runs a test step | ThreadStepRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadStepRunner:
"""Implements thread which runs a test step"""
def __init__(self, queue, execution_queue, context):
"""Constructor"""
<|body_0|>
def run(self):
"""Runs the test step into a thread."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007684 | 1,488 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, queue, execution_queue, context)"
},
{
"docstring": "Runs the test step into a thread.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000974 | Implement the Python class `ThreadStepRunner` described below.
Class description:
Implements thread which runs a test step
Method signatures and docstrings:
- def __init__(self, queue, execution_queue, context): Constructor
- def run(self): Runs the test step into a thread. | Implement the Python class `ThreadStepRunner` described below.
Class description:
Implements thread which runs a test step
Method signatures and docstrings:
- def __init__(self, queue, execution_queue, context): Constructor
- def run(self): Runs the test step into a thread.
<|skeleton|>
class ThreadStepRunner:
"... | 7bf09f20f117fc74d02b7635305ce664b65cdcba | <|skeleton|>
class ThreadStepRunner:
"""Implements thread which runs a test step"""
def __init__(self, queue, execution_queue, context):
"""Constructor"""
<|body_0|>
def run(self):
"""Runs the test step into a thread."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadStepRunner:
"""Implements thread which runs a test step"""
def __init__(self, queue, execution_queue, context):
"""Constructor"""
threading.Thread.__init__(self)
self._queue = queue
self._execution_queue = execution_queue
self._context = context
def run(... | the_stack_v2_python_sparse | acs/acs/Core/TestStep/ThreadStepRunner.py | intel/test-framework-and-suites-for-android | train | 9 |
8bb5cb022236d09dc22f68625da29eaebc4f45c9 | [
"m, n = (len(word1), len(word2))\nif not m or not n:\n return m or n\ndp = [[0] * (n + 1) for i in xrange(m + 1)]\nfor i in xrange(m):\n for j in xrange(n):\n if word1[i] == word2[j]:\n dp[i + 1][j + 1] = dp[i][j] + 1\n else:\n dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j +... | <|body_start_0|>
m, n = (len(word1), len(word2))
if not m or not n:
return m or n
dp = [[0] * (n + 1) for i in xrange(m + 1)]
for i in xrange(m):
for j in xrange(n):
if word1[i] == word2[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minDistance1(self, word1, word2):
""":type word1: str :type word2: str :rtype: int LCS的变形题目"""
<|body_0|>
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int 节省了空间,时间复杂度没变"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_007685 | 1,786 | no_license | [
{
"docstring": ":type word1: str :type word2: str :rtype: int LCS的变形题目",
"name": "minDistance1",
"signature": "def minDistance1(self, word1, word2)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int 节省了空间,时间复杂度没变",
"name": "minDistance",
"signature": "def minDistance(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance1(self, word1, word2): :type word1: str :type word2: str :rtype: int LCS的变形题目
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minDistance1(self, word1, word2): :type word1: str :type word2: str :rtype: int LCS的变形题目
- def minDistance(self, word1, word2): :type word1: str :type word2: str :rtype: int ... | 9687f8e743a8b6396fff192f22b5256d1025f86b | <|skeleton|>
class Solution:
def minDistance1(self, word1, word2):
""":type word1: str :type word2: str :rtype: int LCS的变形题目"""
<|body_0|>
def minDistance(self, word1, word2):
""":type word1: str :type word2: str :rtype: int 节省了空间,时间复杂度没变"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minDistance1(self, word1, word2):
""":type word1: str :type word2: str :rtype: int LCS的变形题目"""
m, n = (len(word1), len(word2))
if not m or not n:
return m or n
dp = [[0] * (n + 1) for i in xrange(m + 1)]
for i in xrange(m):
for j in... | the_stack_v2_python_sparse | 2017/dp/Delete_Operation_for_Two_Strings.py | buhuipao/LeetCode | train | 5 | |
e4ff882ac432ed2ee43f9e7487b700100fccbea4 | [
"super(Slic, self).__init__(paramlist)\nself.params['algorithm'] = 'Slic'\nself.params['n_segments'] = 5\nself.params['beta1'] = 2\nself.params['max_iter'] = 10\nself.params['alpha1'] = 0.5\nself.paramindexes = ['n_segments', 'alpha1', 'beta1', 'max_iter']\nself.slico = False\nself.set_params(paramlist)",
"compac... | <|body_start_0|>
super(Slic, self).__init__(paramlist)
self.params['algorithm'] = 'Slic'
self.params['n_segments'] = 5
self.params['beta1'] = 2
self.params['max_iter'] = 10
self.params['alpha1'] = 0.5
self.paramindexes = ['n_segments', 'alpha1', 'beta1', 'max_iter... | Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image compactness -- float, Balances color proximity and space proximity. Highe... | Slic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Slic:
"""Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image compactness -- float, Balances color prox... | stack_v2_sparse_classes_36k_train_007686 | 29,598 | permissive | [
{
"docstring": "Get parameters from parameter list that are used in segmentation algorithm. Assign default values to these parameters.",
"name": "__init__",
"signature": "def __init__(self, paramlist=None)"
},
{
"docstring": "Evaluate segmentation algorithm on training image. Keyword arguments: ... | 2 | stack_v2_sparse_classes_30k_train_001338 | Implement the Python class `Slic` described below.
Class description:
Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image co... | Implement the Python class `Slic` described below.
Class description:
Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image co... | 9246b8b20510d4c89357a6764ed96b919eb92d5a | <|skeleton|>
class Slic:
"""Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image compactness -- float, Balances color prox... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Slic:
"""Perform the Slic segmentation algorithm. Segments k-means clustering in Color space (x, y, z). Returns a 2D or 3D array of labels. Parameters: image -- ndarray, input image n_segments -- int, approximate number of labels in segmented output image compactness -- float, Balances color proximity and spa... | the_stack_v2_python_sparse | see/Segmentors.py | Deepak768/see-segment | train | 0 |
49d6a7aa70803626458b63f6ed532d107f95e480 | [
"self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"xh = np.concatenate((h_prev, x_t), axis=1)\na_next = np.tanh(np.dot(xh, self.Wh) + self.bh)\ny_pred = np.dot(a_next, self.Wy) + self.by\ny_pred = np.exp(y_pred) / np.sum... | <|body_start_0|>
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
xh = np.concatenate((h_prev, x_t), axis=1)
a_next = np.tanh(np.dot(xh, self.Wh) + se... | Structure of just one RNN cell | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""Structure of just one RNN cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the concatenated hidden state and input data * Wy and by are ... | stack_v2_sparse_classes_36k_train_007687 | 1,560 | no_license | [
{
"docstring": "* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the concatenated hidden state and input data * Wy and by are for the output * The weights should be initialized using a random normal distribution in t... | 2 | null | Implement the Python class `RNNCell` described below.
Class description:
Structure of just one RNN cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the ... | Implement the Python class `RNNCell` described below.
Class description:
Structure of just one RNN cell
Method signatures and docstrings:
- def __init__(self, i, h, o): * i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the ... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class RNNCell:
"""Structure of just one RNN cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the concatenated hidden state and input data * Wy and by are ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""Structure of just one RNN cell"""
def __init__(self, i, h, o):
"""* i is the dimensionality of the data * h is the dimensionality of the hidden state * o is the dimensionality of the outputs * Wh and bh are for the concatenated hidden state and input data * Wy and by are for the outpu... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
53d0ee05c08d78651c13ea454d93bb3477f8a97d | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n tango.Except.throw_exception(f'ReleaseResources() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke ReleaseResources command on mccsmasterleafnode.', 'mccsmasterleafnode.ReleaseResources()', tan... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:
tango.Except.throw_exception(f'ReleaseResources() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke ReleaseResources command on mccsmasterleafnode.', 'mccsmasterleafno... | A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster. | ReleaseResources | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReleaseResources:
"""A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster."""
def check_allowed(self):
"""Checks whether the command is allowed to be run in the current sta... | stack_v2_sparse_classes_36k_train_007688 | 5,574 | permissive | [
{
"docstring": "Checks whether the command is allowed to be run in the current state :return: True if this command is allowed to be run in current device state :rtype: boolean :raises: ValueError if input argument json string contains invalid value DevFailed if this command is not allowed to be run in current d... | 3 | null | Implement the Python class `ReleaseResources` described below.
Class description:
A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster.
Method signatures and docstrings:
- def check_allowed(self): Checks wh... | Implement the Python class `ReleaseResources` described below.
Class description:
A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster.
Method signatures and docstrings:
- def check_allowed(self): Checks wh... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class ReleaseResources:
"""A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster."""
def check_allowed(self):
"""Checks whether the command is allowed to be run in the current sta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReleaseResources:
"""A class for MccsMasterLeafNode's ReleaseResources() command. It invokes ReleaseResources command on MccsMaster and releases all the resources assigned to MccsMaster."""
def check_allowed(self):
"""Checks whether the command is allowed to be run in the current state :return: T... | the_stack_v2_python_sparse | temp_src/ska_tmc_mccsmasterleafnode_low/release_resources_command.py | ska-telescope/tmc-prototype | train | 4 |
ae885651d0836d41a7e78c77fb363b93783bb1af | [
"Toplevel.__init__(self, master, **kw)\nself.master = master\nself.overrideredirect(1)\nself.stopin = False\nself.stopout = False",
"alpha = self.attributes('-alpha')\nalpha += 0.05\nif alpha < 1.0 and self.stopin is False:\n self.attributes('-alpha', alpha)\n self.after(2, self.fadein)\nelif alpha == 1.0:\... | <|body_start_0|>
Toplevel.__init__(self, master, **kw)
self.master = master
self.overrideredirect(1)
self.stopin = False
self.stopout = False
<|end_body_0|>
<|body_start_1|>
alpha = self.attributes('-alpha')
alpha += 0.05
if alpha < 1.0 and self.stopin is... | Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off | FadingWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FadingWindow:
"""Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off"""
def __init__(self, master, **kw):
"""Initialize the fading window to Toplevel :param master: parent widget"""
<|body_0|>
def fadein(se... | stack_v2_sparse_classes_36k_train_007689 | 9,353 | no_license | [
{
"docstring": "Initialize the fading window to Toplevel :param master: parent widget",
"name": "__init__",
"signature": "def __init__(self, master, **kw)"
},
{
"docstring": ":param event: passed by functions and binders",
"name": "fadein",
"signature": "def fadein(self, event=None)"
}... | 3 | stack_v2_sparse_classes_30k_train_007777 | Implement the Python class `FadingWindow` described below.
Class description:
Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off
Method signatures and docstrings:
- def __init__(self, master, **kw): Initialize the fading window to Toplevel :param maste... | Implement the Python class `FadingWindow` described below.
Class description:
Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off
Method signatures and docstrings:
- def __init__(self, master, **kw): Initialize the fading window to Toplevel :param maste... | f02084d31961aa1ac3d9507eb7fe682fb6a40009 | <|skeleton|>
class FadingWindow:
"""Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off"""
def __init__(self, master, **kw):
"""Initialize the fading window to Toplevel :param master: parent widget"""
<|body_0|>
def fadein(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FadingWindow:
"""Window with fade in and fade out effects. This window is not a regular window. The Windows decorators are turned off"""
def __init__(self, master, **kw):
"""Initialize the fading window to Toplevel :param master: parent widget"""
Toplevel.__init__(self, master, **kw)
... | the_stack_v2_python_sparse | customwidgets.py | prerakl123/tkcalculator | train | 0 |
ca5ffacf871e4b693168741671f9faaa811655bb | [
"web3 = None\nif isinstance(web3_or_provider, BaseProvider):\n web3 = Web3(web3_or_provider)\nelif isinstance(web3_or_provider, Web3):\n web3 = web3_or_provider\nif web3 is None:\n raise TypeError(\"Expected parameter 'web3_or_provider' to be an instance of either\" + ' Web3 or BaseProvider')\nself._web3_e... | <|body_start_0|>
web3 = None
if isinstance(web3_or_provider, BaseProvider):
web3 = Web3(web3_or_provider)
elif isinstance(web3_or_provider, Web3):
web3 = web3_or_provider
if web3 is None:
raise TypeError("Expected parameter 'web3_or_provider' to be an ... | Base class for wrapping an Ethereum smart contract method. | ContractMethod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContractMethod:
"""Base class for wrapping an Ethereum smart contract method."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, validator: Validator=None):
"""Instantiate the object. :param provider: Instance of :class:`web3.providers.base.Base... | stack_v2_sparse_classes_36k_train_007690 | 2,917 | permissive | [
{
"docstring": "Instantiate the object. :param provider: Instance of :class:`web3.providers.base.BaseProvider` :param contract_address: Where the contract has been deployed to. :param validator: Used to validate method inputs.",
"name": "__init__",
"signature": "def __init__(self, web3_or_provider: Unio... | 3 | stack_v2_sparse_classes_30k_test_000405 | Implement the Python class `ContractMethod` described below.
Class description:
Base class for wrapping an Ethereum smart contract method.
Method signatures and docstrings:
- def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, validator: Validator=None): Instantiate the object. :par... | Implement the Python class `ContractMethod` described below.
Class description:
Base class for wrapping an Ethereum smart contract method.
Method signatures and docstrings:
- def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, validator: Validator=None): Instantiate the object. :par... | 53b5bb16d8b4c9050a46978b6f347ef7595fe103 | <|skeleton|>
class ContractMethod:
"""Base class for wrapping an Ethereum smart contract method."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, validator: Validator=None):
"""Instantiate the object. :param provider: Instance of :class:`web3.providers.base.Base... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContractMethod:
"""Base class for wrapping an Ethereum smart contract method."""
def __init__(self, web3_or_provider: Union[Web3, BaseProvider], contract_address: str, validator: Validator=None):
"""Instantiate the object. :param provider: Instance of :class:`web3.providers.base.BaseProvider` :pa... | the_stack_v2_python_sparse | python-packages/contract_wrappers/src/zero_ex/contract_wrappers/bases.py | 0xProject/0x-monorepo | train | 1,132 |
9ba5c61cad5e64c7a3c1919f9e6300dc20991a44 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TermColumn()",
"from .term_store.set import Set\nfrom .term_store.term import Term\nfrom .term_store.set import Set\nfrom .term_store.term import Term\nfields: Dict[str, Callable[[Any], None]] = {'allowMultipleValues': lambda n: setatt... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TermColumn()
<|end_body_0|>
<|body_start_1|>
from .term_store.set import Set
from .term_store.term import Term
from .term_store.set import Set
from .term_store.term impor... | TermColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TermColumn:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TermColumn:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Term... | stack_v2_sparse_classes_36k_train_007691 | 3,553 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TermColumn",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(pa... | 3 | stack_v2_sparse_classes_30k_train_003579 | Implement the Python class `TermColumn` described below.
Class description:
Implement the TermColumn class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TermColumn: Creates a new instance of the appropriate class based on discriminator value Args: pa... | Implement the Python class `TermColumn` described below.
Class description:
Implement the TermColumn class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TermColumn: Creates a new instance of the appropriate class based on discriminator value Args: pa... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TermColumn:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TermColumn:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Term... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TermColumn:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TermColumn:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TermColumn"""
... | the_stack_v2_python_sparse | msgraph/generated/models/term_column.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
4b730d3e38b819b3c47d559efddf8d6c464e81a6 | [
"it = iter(test_inputs.split('\\n')) if test_inputs else None\n\ndef uinput():\n return next(it) if it else sys.stdin.readline().rstrip()\n[self.n] = map(int, uinput().split())\nself.numa = [s == '>' for s in uinput()]\nself.numb = list(map(int, uinput().split()))",
"result = 'FINITE'\npos = 0\nvis = set([])\n... | <|body_start_0|>
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n] = map(int, uinput().split())
self.numa = [s == '>' for s in uinput()]
self.numb = list(map(int, uinput().split... | Gh representation | Gh | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gh:
"""Gh representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
it = iter(test_inputs.split('\n... | stack_v2_sparse_classes_36k_train_007692 | 3,180 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, test_inputs=None)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009487 | Implement the Python class `Gh` described below.
Class description:
Gh representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Gh` described below.
Class description:
Gh representation
Method signatures and docstrings:
- def __init__(self, test_inputs=None): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Gh:
"""Gh representation"""
def __init__(self, ... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Gh:
"""Gh representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Gh:
"""Gh representation"""
def __init__(self, test_inputs=None):
"""Default constructor"""
it = iter(test_inputs.split('\n')) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
[self.n] = map(int, uinput().split())... | the_stack_v2_python_sparse | codeforces/669B_gh.py | snsokolov/contests | train | 1 |
12a0fdae3314c0cf443252f3556a8781433a6af4 | [
"self.lock: threading.RLock = threading.RLock()\nself.queue: list[Event] = []\nself.eventnum: int = 0\nself.timer: Optional[Timer] = None\nself.running: bool = False\nself.start: Optional[float] = None",
"schedule = False\nwhile True:\n with self.lock:\n if not self.running or not self.queue:\n ... | <|body_start_0|>
self.lock: threading.RLock = threading.RLock()
self.queue: list[Event] = []
self.eventnum: int = 0
self.timer: Optional[Timer] = None
self.running: bool = False
self.start: Optional[float] = None
<|end_body_0|>
<|body_start_1|>
schedule = False
... | Provides an event loop for running events. | EventLoop | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventLoop:
"""Provides an event loop for running events."""
def __init__(self) -> None:
"""Creates a EventLoop instance."""
<|body_0|>
def _run_events(self) -> None:
"""Run events. :return: nothing"""
<|body_1|>
def _schedule_event(self) -> None:
... | stack_v2_sparse_classes_36k_train_007693 | 6,786 | permissive | [
{
"docstring": "Creates a EventLoop instance.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Run events. :return: nothing",
"name": "_run_events",
"signature": "def _run_events(self) -> None"
},
{
"docstring": "Schedule event. :return: nothing"... | 6 | null | Implement the Python class `EventLoop` described below.
Class description:
Provides an event loop for running events.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a EventLoop instance.
- def _run_events(self) -> None: Run events. :return: nothing
- def _schedule_event(self) -> None: Schedul... | Implement the Python class `EventLoop` described below.
Class description:
Provides an event loop for running events.
Method signatures and docstrings:
- def __init__(self) -> None: Creates a EventLoop instance.
- def _run_events(self) -> None: Run events. :return: nothing
- def _schedule_event(self) -> None: Schedul... | 20071eed2e73a2287aa385698dd604f4933ae7ff | <|skeleton|>
class EventLoop:
"""Provides an event loop for running events."""
def __init__(self) -> None:
"""Creates a EventLoop instance."""
<|body_0|>
def _run_events(self) -> None:
"""Run events. :return: nothing"""
<|body_1|>
def _schedule_event(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventLoop:
"""Provides an event loop for running events."""
def __init__(self) -> None:
"""Creates a EventLoop instance."""
self.lock: threading.RLock = threading.RLock()
self.queue: list[Event] = []
self.eventnum: int = 0
self.timer: Optional[Timer] = None
... | the_stack_v2_python_sparse | daemon/core/location/event.py | coreemu/core | train | 606 |
b961181792ef7090556b0f141e6c6eef1e0bdf8c | [
"self.project = project\nself.previously_indexed = []\nself.logger = logging.getLogger(__name__)\nself.project_logger = ProjectLogger(self.logger, project)",
"without_stops = []\nfor word in words:\n if word.word.lemma not in app.config['STOPWORDS']:\n without_stops.append(word)\nreturn without_stops",
... | <|body_start_0|>
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = ProjectLogger(self.logger, project)
<|end_body_0|>
<|body_start_1|>
without_stops = []
for word in words:
if word.word.lemma n... | Process given input into Sequences. | SequenceProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_36k_train_007694 | 9,006 | permissive | [
{
"docstring": "Set up local variables for the SequenceProcessor.",
"name": "__init__",
"signature": "def __init__(self, project)"
},
{
"docstring": "Remove every sort of stop from the sentences. :param list words: A list of WordInSentence objects. :return list: The list without stops.",
"na... | 4 | null | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | Implement the Python class `SequenceProcessor` described below.
Class description:
Process given input into Sequences.
Method signatures and docstrings:
- def __init__(self, project): Set up local variables for the SequenceProcessor.
- def remove_stops(self, words): Remove every sort of stop from the sentences. :para... | a45102c1848c93360d3815187783756dc5e16156 | <|skeleton|>
class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
<|body_0|>
def remove_stops(self, words):
"""Remove every sort of stop from the sentences. :param list words: A list ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceProcessor:
"""Process given input into Sequences."""
def __init__(self, project):
"""Set up local variables for the SequenceProcessor."""
self.project = project
self.previously_indexed = []
self.logger = logging.getLogger(__name__)
self.project_logger = Pro... | the_stack_v2_python_sparse | app/preprocessor/sequenceprocessor.py | mkabbasi/wordseer | train | 0 |
fe69397c12eb30c0ae414ac8f0691f2ea9bdcbe0 | [
"if not root:\n return ''\n\ndef preorder(di: dict, root: TreeNode, idx: int=0):\n di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.right else None)\n if root.left:\n preorder(di, root.left, idx * 2 + 1)\n if root.right:\n preorder(di, root.right, idx * 2 + 2)\n... | <|body_start_0|>
if not root:
return ''
def preorder(di: dict, root: TreeNode, idx: int=0):
di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.right else None)
if root.left:
preorder(di, root.left, idx * 2 + 1)
if... | 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_007695 | 3,028 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 89755fc95c2bace7e644af189ec29df9a2ffb277 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
def preorder(di: dict, root: TreeNode, idx: int=0):
di[idx] = (root.val, idx * 2 + 1 if root.left else None, idx * 2 + 2 if root.r... | the_stack_v2_python_sparse | OnlineJudge/LeetCode/第1个进度/297.二叉树的序列化与反序列化.py | CrazyIEEE/algorithm | train | 0 | |
6c077378057a147ad62a87fa9db534916040c448 | [
"n = top - bottom + 1\nif n == 1:\n return s\nmid = n // 2\nlow, high = (-1, -1)\nl, r = (mid, mid)\nif not n % 2:\n l = mid - 1\nl_substr = self.longestPalindrome(s[:mid])\nr_substr = self.longestPalindrome(s[mid:])\nwhile l and r < top:\n if s[l] == s[r]:\n low, high = (l, r)\n l, r = (l - ... | <|body_start_0|>
n = top - bottom + 1
if n == 1:
return s
mid = n // 2
low, high = (-1, -1)
l, r = (mid, mid)
if not n % 2:
l = mid - 1
l_substr = self.longestPalindrome(s[:mid])
r_substr = self.longestPalindrome(s[mid:])
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def is_longest(self, s, bottom, top):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = top - bottom + 1
if n == 1:
... | stack_v2_sparse_classes_36k_train_007696 | 1,188 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "is_longest",
"signature": "def is_longest(self, s, bottom, top)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000720 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_longest(self, s, bottom, top): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def is_longest(self, s, bottom, top): :type s: str :rtype: str
- def longestPalindrome(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def is_longest(self, ... | 315693f03faecef72c9d73a8e40fee7c6b75e97d | <|skeleton|>
class Solution:
def is_longest(self, s, bottom, top):
""":type s: str :rtype: str"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def is_longest(self, s, bottom, top):
""":type s: str :rtype: str"""
n = top - bottom + 1
if n == 1:
return s
mid = n // 2
low, high = (-1, -1)
l, r = (mid, mid)
if not n % 2:
l = mid - 1
l_substr = self.longestP... | the_stack_v2_python_sparse | Easy/longest_palindromic_substring.py | Travmatth/LeetCode | train | 0 | |
39c84356edbc37cdbc316ab07b9c1bfd7b556fa3 | [
"self.graph = GraphFactory.load_db_into_graph()\nself.all_profiles = models.Profile.objects.all()\nself.all_profiles_count = len(self.all_profiles)",
"current_profile_count = 0\nfor profile in self.all_profiles:\n start_ms = time.time() * 1000.0\n profile_id = profile.id\n current_profile_count = current... | <|body_start_0|>
self.graph = GraphFactory.load_db_into_graph()
self.all_profiles = models.Profile.objects.all()
self.all_profiles_count = len(self.all_profiles)
<|end_body_0|>
<|body_start_1|>
current_profile_count = 0
for profile in self.all_profiles:
start_ms = ti... | Graph Collaborative Filtering based on Bookmarkes | GraphCollaborativeFilteringBaseRecommender | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphCollaborativeFilteringBaseRecommender:
"""Graph Collaborative Filtering based on Bookmarkes"""
def initiate(self):
"""Initiate any variables needed for recommendation_logic function"""
<|body_0|>
def recommendation_logic(self):
"""Recommendation logic"""
... | stack_v2_sparse_classes_36k_train_007697 | 31,433 | permissive | [
{
"docstring": "Initiate any variables needed for recommendation_logic function",
"name": "initiate",
"signature": "def initiate(self)"
},
{
"docstring": "Recommendation logic",
"name": "recommendation_logic",
"signature": "def recommendation_logic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000033 | Implement the Python class `GraphCollaborativeFilteringBaseRecommender` described below.
Class description:
Graph Collaborative Filtering based on Bookmarkes
Method signatures and docstrings:
- def initiate(self): Initiate any variables needed for recommendation_logic function
- def recommendation_logic(self): Recomm... | Implement the Python class `GraphCollaborativeFilteringBaseRecommender` described below.
Class description:
Graph Collaborative Filtering based on Bookmarkes
Method signatures and docstrings:
- def initiate(self): Initiate any variables needed for recommendation_logic function
- def recommendation_logic(self): Recomm... | d31d00bb8a28a8d0c999813f616b398f41516244 | <|skeleton|>
class GraphCollaborativeFilteringBaseRecommender:
"""Graph Collaborative Filtering based on Bookmarkes"""
def initiate(self):
"""Initiate any variables needed for recommendation_logic function"""
<|body_0|>
def recommendation_logic(self):
"""Recommendation logic"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphCollaborativeFilteringBaseRecommender:
"""Graph Collaborative Filtering based on Bookmarkes"""
def initiate(self):
"""Initiate any variables needed for recommendation_logic function"""
self.graph = GraphFactory.load_db_into_graph()
self.all_profiles = models.Profile.objects.a... | the_stack_v2_python_sparse | ozpcenter/recommend/recommend.py | ozoneplatform/ozp-backend | train | 1 |
3e539e4aa4ae3280e9ab83ec584ba8902f8d3c0a | [
"if authorization_header is None:\n return None\nif isinstance(authorization_header, str) is False:\n return None\ntry:\n auth_type, auth_str = authorization_header.split(' ')\n if auth_type != 'Basic':\n return None\nexcept ValueError:\n return None\nreturn auth_str",
"from base64 import b6... | <|body_start_0|>
if authorization_header is None:
return None
if isinstance(authorization_header, str) is False:
return None
try:
auth_type, auth_str = authorization_header.split(' ')
if auth_type != 'Basic':
return None
exc... | Basic Authentication Object | BasicAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuth:
"""Basic Authentication Object"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Accept authorization and validate"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header: str) -> str:
... | stack_v2_sparse_classes_36k_train_007698 | 3,018 | no_license | [
{
"docstring": "Accept authorization and validate",
"name": "extract_base64_authorization_header",
"signature": "def extract_base64_authorization_header(self, authorization_header: str) -> str"
},
{
"docstring": "decode valid auth payload",
"name": "decode_base64_authorization_header",
"... | 5 | stack_v2_sparse_classes_30k_train_000133 | Implement the Python class `BasicAuth` described below.
Class description:
Basic Authentication Object
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Accept authorization and validate
- def decode_base64_authorization_header(self, base64_authorizat... | Implement the Python class `BasicAuth` described below.
Class description:
Basic Authentication Object
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Accept authorization and validate
- def decode_base64_authorization_header(self, base64_authorizat... | ece925eabc1d1e22055f1b4d3f052b571e1c4400 | <|skeleton|>
class BasicAuth:
"""Basic Authentication Object"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Accept authorization and validate"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header: str) -> str:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicAuth:
"""Basic Authentication Object"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Accept authorization and validate"""
if authorization_header is None:
return None
if isinstance(authorization_header, str) is False:
... | the_stack_v2_python_sparse | 0x06-Basic_authentication/api/v1/auth/basic_auth.py | zacwoll/holbertonschool-web_back_end | train | 0 |
b64c766c31008ab608aa0a2b8add7a43f574546a | [
"arguments.AddInstancesResourceArg(parser, 'to list clusters for')\nparser.display_info.AddFormat('\\n table(\\n name.segment(3):sort=1:label=INSTANCE,\\n name.basename():sort=2:label=NAME,\\n location.basename():label=ZONE,\\n serveNodes:label=NODES,\\n ... | <|body_start_0|>
arguments.AddInstancesResourceArg(parser, 'to list clusters for')
parser.display_info.AddFormat('\n table(\n name.segment(3):sort=1:label=INSTANCE,\n name.basename():sort=2:label=NAME,\n location.basename():label=ZONE,\n serveNodes:la... | List existing Bigtable clusters. | ListClusters | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListClusters:
"""List existing Bigtable clusters."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that we... | stack_v2_sparse_classes_36k_train_007699 | 3,045 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Yields: Some value t... | 2 | null | Implement the Python class `ListClusters` described below.
Class description:
List existing Bigtable clusters.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All ... | Implement the Python class `ListClusters` described below.
Class description:
List existing Bigtable clusters.
Method signatures and docstrings:
- def Args(parser): Register flags for this command.
- def Run(self, args): This is what gets called when the user runs this command. Args: args: an argparse namespace. All ... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class ListClusters:
"""List existing Bigtable clusters."""
def Args(parser):
"""Register flags for this command."""
<|body_0|>
def Run(self, args):
"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that we... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ListClusters:
"""List existing Bigtable clusters."""
def Args(parser):
"""Register flags for this command."""
arguments.AddInstancesResourceArg(parser, 'to list clusters for')
parser.display_info.AddFormat('\n table(\n name.segment(3):sort=1:label=INSTANCE,\n ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/bigtable/clusters/list.py | bopopescu/socialliteapp | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.