blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
782fbea41e4b4c63f4320df50e0b9333186b49df | [
"if not matrix:\n return []\npath = []\nn, m = (len(matrix), len(matrix[0]))\nl, r, t, b = (0, m - 1, 0, n - 1)\nwhile True:\n for i in range(l, r + 1):\n path.append(matrix[t][i])\n t += 1\n if t > b:\n break\n for i in range(t, b + 1):\n path.append(matrix[i][r])\n r -= 1\n ... | <|body_start_0|>
if not matrix:
return []
path = []
n, m = (len(matrix), len(matrix[0]))
l, r, t, b = (0, m - 1, 0, n - 1)
while True:
for i in range(l, r + 1):
path.append(matrix[t][i])
t += 1
if t > b:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def reverseSpiralOrder(self, matrix):
"""逆时针打印 :param matrix: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not matrix:
... | stack_v2_sparse_classes_75kplus_train_003400 | 2,262 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "spiralOrder",
"signature": "def spiralOrder(self, matrix)"
},
{
"docstring": "逆时针打印 :param matrix: :return:",
"name": "reverseSpiralOrder",
"signature": "def reverseSpiralOrder(self, matrix)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def reverseSpiralOrder(self, matrix): 逆时针打印 :param matrix: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def spiralOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def reverseSpiralOrder(self, matrix): 逆时针打印 :param matrix: :return:
<|skeleton|>
class Solution:... | 97cc61fefe0bedf5161687aab92fb09b0df990e2 | <|skeleton|>
class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def reverseSpiralOrder(self, matrix):
"""逆时针打印 :param matrix: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def spiralOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
if not matrix:
return []
path = []
n, m = (len(matrix), len(matrix[0]))
l, r, t, b = (0, m - 1, 0, n - 1)
while True:
for i in range(l, r + 1):... | the_stack_v2_python_sparse | code/other/spiralOrder.py | JiaXingBinggan/For_work | train | 0 | |
85f47f0d3e6a9c0418d427d00de354e8fc2f4223 | [
"self.plugin._regrid_and_populate(self.temperature, self.humidity, self.pressure, self.uwind, self.vwind, self.orography_cube)\nplugin_cubes = [self.plugin.temperature, self.plugin.humidity, self.plugin.pressure, self.plugin.uwind, self.plugin.vwind, self.plugin.topography]\nfor cube in plugin_cubes:\n self.asse... | <|body_start_0|>
self.plugin._regrid_and_populate(self.temperature, self.humidity, self.pressure, self.uwind, self.vwind, self.orography_cube)
plugin_cubes = [self.plugin.temperature, self.plugin.humidity, self.plugin.pressure, self.plugin.uwind, self.plugin.vwind, self.plugin.topography]
for cu... | Test the _regrid_and_populate method | Test__regrid_and_populate | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__regrid_and_populate:
"""Test the _regrid_and_populate method"""
def test_basic(self):
"""Test function populates class instance"""
<|body_0|>
def test_variables(self):
"""Test variable values are sensible"""
<|body_1|>
def test_vgradz(self):
... | stack_v2_sparse_classes_75kplus_train_003401 | 34,979 | permissive | [
{
"docstring": "Test function populates class instance",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test variable values are sensible",
"name": "test_variables",
"signature": "def test_variables(self)"
},
{
"docstring": "Test values of vgradz are... | 3 | stack_v2_sparse_classes_30k_test_002447 | Implement the Python class `Test__regrid_and_populate` described below.
Class description:
Test the _regrid_and_populate method
Method signatures and docstrings:
- def test_basic(self): Test function populates class instance
- def test_variables(self): Test variable values are sensible
- def test_vgradz(self): Test v... | Implement the Python class `Test__regrid_and_populate` described below.
Class description:
Test the _regrid_and_populate method
Method signatures and docstrings:
- def test_basic(self): Test function populates class instance
- def test_variables(self): Test variable values are sensible
- def test_vgradz(self): Test v... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__regrid_and_populate:
"""Test the _regrid_and_populate method"""
def test_basic(self):
"""Test function populates class instance"""
<|body_0|>
def test_variables(self):
"""Test variable values are sensible"""
<|body_1|>
def test_vgradz(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__regrid_and_populate:
"""Test the _regrid_and_populate method"""
def test_basic(self):
"""Test function populates class instance"""
self.plugin._regrid_and_populate(self.temperature, self.humidity, self.pressure, self.uwind, self.vwind, self.orography_cube)
plugin_cubes = [se... | the_stack_v2_python_sparse | improver_tests/orographic_enhancement/test_OrographicEnhancement.py | metoppv/improver | train | 101 |
ee8f359bb640c4a031ca203cfef6555d929d38ee | [
"super(PreTwoStem, self).__init__()\nself._C = desc.C\nself.stems = nn.ModuleList()\nstem0 = nn.Sequential(nn.Conv2d(3, self._C // 2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(self._C // 2), nn.ReLU(inplace=True), nn.Conv2d(self._C // 2, self._C, 3, stride=2, padding=1, bias=False), nn.BatchNo... | <|body_start_0|>
super(PreTwoStem, self).__init__()
self._C = desc.C
self.stems = nn.ModuleList()
stem0 = nn.Sequential(nn.Conv2d(3, self._C // 2, kernel_size=3, stride=2, padding=1, bias=False), nn.BatchNorm2d(self._C // 2), nn.ReLU(inplace=True), nn.Conv2d(self._C // 2, self._C, 3, str... | Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config | PreTwoStem | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreTwoStem:
"""Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config"""
def __init__(self, desc):
"""Init PreTwoStem."""
<|body_0|>
def forward(self, x):
"""Forward function of PreTwoStem."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_003402 | 7,297 | permissive | [
{
"docstring": "Init PreTwoStem.",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Forward function of PreTwoStem.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024665 | Implement the Python class `PreTwoStem` described below.
Class description:
Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init PreTwoStem.
- def forward(self, x): Forward function of PreTwoStem. | Implement the Python class `PreTwoStem` described below.
Class description:
Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config
Method signatures and docstrings:
- def __init__(self, desc): Init PreTwoStem.
- def forward(self, x): Forward function of PreTwoStem.
<|skeleton|>
cla... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class PreTwoStem:
"""Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config"""
def __init__(self, desc):
"""Init PreTwoStem."""
<|body_0|>
def forward(self, x):
"""Forward function of PreTwoStem."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PreTwoStem:
"""Class of two stems convolution. :param desc: description of PreTwoStem :type desc: Config"""
def __init__(self, desc):
"""Init PreTwoStem."""
super(PreTwoStem, self).__init__()
self._C = desc.C
self.stems = nn.ModuleList()
stem0 = nn.Sequential(nn.Co... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/blocks/darts_ops.py | Huawei-Ascend/modelzoo | train | 1 |
d205a0585ccfdbb1075d2b33e40a4b0bbbd1cd71 | [
"super().__init__()\nself.decoder = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout(0.8), nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True))\nself.layer = nn.ConvTranspose2d(1280, num_classes, kernel_size=2, stride=2, dilation=1)",
"pool_3, pool_4 = pools\nx = self.deco... | <|body_start_0|>
super().__init__()
self.decoder = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout(0.8), nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True))
self.layer = nn.ConvTranspose2d(1280, num_classes, kernel_size=2, stride=2, dilation=1)
<|end_bo... | Column Decoder. | ColumnDecoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnDecoder:
"""Column Decoder."""
def __init__(self, num_classes: int):
"""Initialize Column Decoder. Args: num_classes (int): Number of classes per point."""
<|body_0|>
def forward(self, x, pools):
"""Forward pass. Args: x (tensor): Batch of images to perform... | stack_v2_sparse_classes_75kplus_train_003403 | 5,468 | no_license | [
{
"docstring": "Initialize Column Decoder. Args: num_classes (int): Number of classes per point.",
"name": "__init__",
"signature": "def __init__(self, num_classes: int)"
},
{
"docstring": "Forward pass. Args: x (tensor): Batch of images to perform forward-pass. pools (Tuple[tensor, tensor]): Th... | 2 | stack_v2_sparse_classes_30k_train_017293 | Implement the Python class `ColumnDecoder` described below.
Class description:
Column Decoder.
Method signatures and docstrings:
- def __init__(self, num_classes: int): Initialize Column Decoder. Args: num_classes (int): Number of classes per point.
- def forward(self, x, pools): Forward pass. Args: x (tensor): Batch... | Implement the Python class `ColumnDecoder` described below.
Class description:
Column Decoder.
Method signatures and docstrings:
- def __init__(self, num_classes: int): Initialize Column Decoder. Args: num_classes (int): Number of classes per point.
- def forward(self, x, pools): Forward pass. Args: x (tensor): Batch... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ColumnDecoder:
"""Column Decoder."""
def __init__(self, num_classes: int):
"""Initialize Column Decoder. Args: num_classes (int): Number of classes per point."""
<|body_0|>
def forward(self, x, pools):
"""Forward pass. Args: x (tensor): Batch of images to perform... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColumnDecoder:
"""Column Decoder."""
def __init__(self, num_classes: int):
"""Initialize Column Decoder. Args: num_classes (int): Number of classes per point."""
super().__init__()
self.decoder = nn.Sequential(nn.Conv2d(512, 512, kernel_size=1), nn.ReLU(inplace=True), nn.Dropout(0... | the_stack_v2_python_sparse | generated/test_tomassosorio_OCR_tablenet.py | jansel/pytorch-jit-paritybench | train | 35 |
c3e555949a1a1941f27d4bd1b32bd71b4ea17f08 | [
"self._translation = translation\nself._rotation = rotation\nself._latent_space_size = latent_space_size\nself._is_training = is_training\nself._decoder_pose = self.decoder_pose",
"translation_decoder = tf.layers.dense(inputs=self._translation, units=self._latent_space_size, activation=None, kernel_initializer=tf... | <|body_start_0|>
self._translation = translation
self._rotation = rotation
self._latent_space_size = latent_space_size
self._is_training = is_training
self._decoder_pose = self.decoder_pose
<|end_body_0|>
<|body_start_1|>
translation_decoder = tf.layers.dense(inputs=self... | Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to decode the object's segmentation mask by decoder class. | DecoderPose | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderPose:
"""Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to decode the object's segmentation mask ... | stack_v2_sparse_classes_75kplus_train_003404 | 2,684 | no_license | [
{
"docstring": "Constructor to Decoder_Pose class Initializes decoder_pose class variables",
"name": "__init__",
"signature": "def __init__(self, translation, rotation, latent_space_size, is_training=True)"
},
{
"docstring": "Returns latent vector from rotation and translation parameters Fully c... | 2 | null | Implement the Python class `DecoderPose` described below.
Class description:
Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to... | Implement the Python class `DecoderPose` described below.
Class description:
Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to... | 92ef2bb115068deec3b37af5392a8e5fb7a4b502 | <|skeleton|>
class DecoderPose:
"""Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to decode the object's segmentation mask ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderPose:
"""Returns fused latent vector from the pose predicted by regression layers in the model. This class takes outputs from rotation and translation regression networks, encodes and fuse the latent vectors. The output from this model is then used to decode the object's segmentation mask by decoder cl... | the_stack_v2_python_sparse | packages/object_pose_estimation/apps/pose_cnn_decoder/training/decoder_pose.py | stevelimyh/Lidar_Backpack_ISAAC_SDK | train | 1 |
bf3fdc7671b34d67c88c53a2f3a75929b8c46927 | [
"if CommonConf.RSU_PROCESS:\n logger.info('===========重启天线============')\n CommonConf.RSU_PROCESS.terminate()\nCommonConf.RSU_PROCESS = Process(target=main2.run_etc_toll)\nCommonConf.RSU_PROCESS.start()",
"upload_rsu_heartbeat_dict = dict(park_code=CommonConf.ETC_CONF_DICT['etc'][0]['park_code'], dev_code=C... | <|body_start_0|>
if CommonConf.RSU_PROCESS:
logger.info('===========重启天线============')
CommonConf.RSU_PROCESS.terminate()
CommonConf.RSU_PROCESS = Process(target=main2.run_etc_toll)
CommonConf.RSU_PROCESS.start()
<|end_body_0|>
<|body_start_1|>
upload_rsu_heartbe... | RsuStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RsuStatus:
def restart_rsu_control():
"""重启天线服务 @return:"""
<|body_0|>
def check_rsu_heartbeat(callback):
"""检测天线心跳状态, 心跳停止过长,重启天线 @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if CommonConf.RSU_PROCESS:
logger.info('=========... | stack_v2_sparse_classes_75kplus_train_003405 | 3,475 | no_license | [
{
"docstring": "重启天线服务 @return:",
"name": "restart_rsu_control",
"signature": "def restart_rsu_control()"
},
{
"docstring": "检测天线心跳状态, 心跳停止过长,重启天线 @return:",
"name": "check_rsu_heartbeat",
"signature": "def check_rsu_heartbeat(callback)"
}
] | 2 | null | Implement the Python class `RsuStatus` described below.
Class description:
Implement the RsuStatus class.
Method signatures and docstrings:
- def restart_rsu_control(): 重启天线服务 @return:
- def check_rsu_heartbeat(callback): 检测天线心跳状态, 心跳停止过长,重启天线 @return: | Implement the Python class `RsuStatus` described below.
Class description:
Implement the RsuStatus class.
Method signatures and docstrings:
- def restart_rsu_control(): 重启天线服务 @return:
- def check_rsu_heartbeat(callback): 检测天线心跳状态, 心跳停止过长,重启天线 @return:
<|skeleton|>
class RsuStatus:
def restart_rsu_control():
... | 3e854b6cb479497e44fb36a77e4f4ccef803d911 | <|skeleton|>
class RsuStatus:
def restart_rsu_control():
"""重启天线服务 @return:"""
<|body_0|>
def check_rsu_heartbeat(callback):
"""检测天线心跳状态, 心跳停止过长,重启天线 @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RsuStatus:
def restart_rsu_control():
"""重启天线服务 @return:"""
if CommonConf.RSU_PROCESS:
logger.info('===========重启天线============')
CommonConf.RSU_PROCESS.terminate()
CommonConf.RSU_PROCESS = Process(target=main2.run_etc_toll)
CommonConf.RSU_PROCESS.start(... | the_stack_v2_python_sparse | rsu_controller/service/check_rsu_status.py | crazyfox07/rsu-langneng | train | 0 | |
700b9dfcf44c2bf2aa43cdad2a3fb54f4b8c4bff | [
"super().__init__(self.PROBLEM_NAME)\nself.input_list = input_list\nself.min_value = min_value\nself.max_value = max_value",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nif len(self.input_list) == 0:\n return range(0, self.max_value + 1)\nrange_list = []\nfor i in range(len(self.input_list)):\n ... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
self.min_value = min_value
self.max_value = max_value
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
if len(self.input_list) == 0:
ret... | MissingRanges | MissingRanges | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MissingRanges:
"""MissingRanges"""
def __init__(self, input_list, min_value, max_value):
"""Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) (runtime) and O(1) (... | stack_v2_sparse_classes_75kplus_train_003406 | 3,054 | no_license | [
{
"docstring": "Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_list, min_value, max_value)"
},
{
"docstring": "Solve the problem Note: O(n) (runtime) and O(1) (space) works by iterating the inpu... | 2 | stack_v2_sparse_classes_30k_train_015603 | Implement the Python class `MissingRanges` described below.
Class description:
MissingRanges
Method signatures and docstrings:
- def __init__(self, input_list, min_value, max_value): Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None
- def solve(self): Solve the problem Note: O(n)... | Implement the Python class `MissingRanges` described below.
Class description:
MissingRanges
Method signatures and docstrings:
- def __init__(self, input_list, min_value, max_value): Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None
- def solve(self): Solve the problem Note: O(n)... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class MissingRanges:
"""MissingRanges"""
def __init__(self, input_list, min_value, max_value):
"""Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Solve the problem Note: O(n) (runtime) and O(1) (... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MissingRanges:
"""MissingRanges"""
def __init__(self, input_list, min_value, max_value):
"""Missing Ranges Args: input_list: Contains a list of integers Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
self.input_list = input_list
self.min_value = min_valu... | the_stack_v2_python_sparse | python/problems/array/missing_ranges.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
17f28dec79bd7e85c81a30a9f3c740a50eb9355c | [
"if not email:\n raise ValueError('Users must have an email')\nif not username:\n raise ValueError('Users must have an username')\nuser = self.model(username=username, email=email, password=password, last_name=last_name, first_name=first_name)\nuser.is_active = True\nuser.set_password(password)\nuser.save(usi... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email')
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username, email=email, password=password, last_name=last_name, first_name=first_name)
user.is_ac... | AuthUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
<|body_0|>
def create_superuser(self, ... | stack_v2_sparse_classes_75kplus_train_003407 | 31,843 | no_license | [
{
"docstring": "ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト",
"name": "create_user",
"signature": "def create_user(self, username, email, password, last_name, first_name)"
},
{
"docstring": "スーパーユーザ作... | 2 | stack_v2_sparse_classes_30k_train_022479 | Implement the Python class `AuthUserManager` described below.
Class description:
Implement the AuthUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password, last_name, first_name): ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name:... | Implement the Python class `AuthUserManager` described below.
Class description:
Implement the AuthUserManager class.
Method signatures and docstrings:
- def create_user(self, username, email, password, last_name, first_name): ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name:... | ee51f79e8d5c68b40c2fbd96272bbe2cc657a849 | <|skeleton|>
class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
<|body_0|>
def create_superuser(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthUserManager:
def create_user(self, username, email, password, last_name, first_name):
"""ユーザ作成 :param username: ユーザID :param email: メールアドレス :param password: パスワード :param last_name: 苗字 :param first_name: 名前 :return: AuthUserオブジェクト"""
if not email:
raise ValueError('Users must ha... | the_stack_v2_python_sparse | account/models.py | adusu-masaomi/adusu-python-account | train | 0 | |
a799cfd14346c071f58a6015e542fbc498a0d24e | [
"retflg, retstr = service.LogDetailBusiness.view_logdetail_get(request, itemid)\nif retflg:\n return Response(retstr, status=status.HTTP_200_OK)\nelse:\n return Response(retstr, status=status.HTTP_500_INTERNAL_SERVER_ERROR)",
"retflg, retstr = service.LogDetailBusiness.delete_log(request, itemid)\nif retflg... | <|body_start_0|>
retflg, retstr = service.LogDetailBusiness.view_logdetail_get(request, itemid)
if retflg:
return Response(retstr, status=status.HTTP_200_OK)
else:
return Response(retstr, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
<|end_body_0|>
<|body_start_1|>
... | operate one log file get :get log detail delete:Delete selected log | LogDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogDetail:
"""operate one log file get :get log detail delete:Delete selected log"""
def get(self, request, itemid, format=None):
"""Get log detail."""
<|body_0|>
def delete(self, request, itemid, format=None):
"""Delete selected log."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_003408 | 1,925 | no_license | [
{
"docstring": "Get log detail.",
"name": "get",
"signature": "def get(self, request, itemid, format=None)"
},
{
"docstring": "Delete selected log.",
"name": "delete",
"signature": "def delete(self, request, itemid, format=None)"
}
] | 2 | null | Implement the Python class `LogDetail` described below.
Class description:
operate one log file get :get log detail delete:Delete selected log
Method signatures and docstrings:
- def get(self, request, itemid, format=None): Get log detail.
- def delete(self, request, itemid, format=None): Delete selected log. | Implement the Python class `LogDetail` described below.
Class description:
operate one log file get :get log detail delete:Delete selected log
Method signatures and docstrings:
- def get(self, request, itemid, format=None): Get log detail.
- def delete(self, request, itemid, format=None): Delete selected log.
<|skel... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class LogDetail:
"""operate one log file get :get log detail delete:Delete selected log"""
def get(self, request, itemid, format=None):
"""Get log detail."""
<|body_0|>
def delete(self, request, itemid, format=None):
"""Delete selected log."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogDetail:
"""operate one log file get :get log detail delete:Delete selected log"""
def get(self, request, itemid, format=None):
"""Get log detail."""
retflg, retstr = service.LogDetailBusiness.view_logdetail_get(request, itemid)
if retflg:
return Response(retstr, sta... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/log/views.py | sdtimothy8/Coding | train | 0 |
b8314c876129b1e808f0275672eb8d49bfd1e38d | [
"connection = connections[using or 'default']\nwith transaction.atomic():\n with connection.schema_editor() as schema_editor:\n for partition in self.creations:\n partition.create(self.config.model, cast('PostgresSchemaEditor', schema_editor), comment=AUTO_PARTITIONED_COMMENT)\n for part... | <|body_start_0|>
connection = connections[using or 'default']
with transaction.atomic():
with connection.schema_editor() as schema_editor:
for partition in self.creations:
partition.create(self.config.model, cast('PostgresSchemaEditor', schema_editor), com... | Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model. | PostgresModelPartitioningPlan | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostgresModelPartitioningPlan:
"""Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model."""
def apply(self, using: Optional[str]) -> None:
"""Applies this partitioning plan by creating and dele... | stack_v2_sparse_classes_75kplus_train_003409 | 3,768 | permissive | [
{
"docstring": "Applies this partitioning plan by creating and deleting the planned partitions. Applying the plan runs in a transaction. Arguments: using: Optional name of the database connection to use.",
"name": "apply",
"signature": "def apply(self, using: Optional[str]) -> None"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_008766 | Implement the Python class `PostgresModelPartitioningPlan` described below.
Class description:
Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model.
Method signatures and docstrings:
- def apply(self, using: Optional[str]) -> ... | Implement the Python class `PostgresModelPartitioningPlan` described below.
Class description:
Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model.
Method signatures and docstrings:
- def apply(self, using: Optional[str]) -> ... | e5503cb3f3c1b7959bd55253d3a79296f4c8f0ef | <|skeleton|>
class PostgresModelPartitioningPlan:
"""Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model."""
def apply(self, using: Optional[str]) -> None:
"""Applies this partitioning plan by creating and dele... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostgresModelPartitioningPlan:
"""Describes the partitions that are going to be created/deleted for a particular partitioning config. A "partitioning config" applies to one model."""
def apply(self, using: Optional[str]) -> None:
"""Applies this partitioning plan by creating and deleting the plan... | the_stack_v2_python_sparse | psqlextra/partitioning/plan.py | SectorLabs/django-postgres-extra | train | 645 |
eb1dae0ae5675024be34465338bfeeed1f504026 | [
"super(CenterLoss, self).__init__()\nself.class_number = class_number\nself.feature_number = feature_number\n'将中心点定义为可以学习的参数'\nself.center_point = nn.Parameter(torch.randn(class_number, feature_number), requires_grad=True)\n'\\n [1,0],\\n [0.809016994374947424,0.587785252292],\\n [0... | <|body_start_0|>
super(CenterLoss, self).__init__()
self.class_number = class_number
self.feature_number = feature_number
'将中心点定义为可以学习的参数'
self.center_point = nn.Parameter(torch.randn(class_number, feature_number), requires_grad=True)
'\n [1,0],\n [0... | CenterLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterLoss:
def __init__(self, feature_number, class_number):
"""初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量"""
<|body_0|>
def forward(self, feature, target):
"""计算中心损失 :param feature: 特征向量。 :param target: 分类标签,未进行one_hot处理的。 :return: 损... | stack_v2_sparse_classes_75kplus_train_003410 | 1,967 | no_license | [
{
"docstring": "初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量",
"name": "__init__",
"signature": "def __init__(self, feature_number, class_number)"
},
{
"docstring": "计算中心损失 :param feature: 特征向量。 :param target: 分类标签,未进行one_hot处理的。 :return: 损失",
"name": "forward",... | 2 | stack_v2_sparse_classes_30k_train_002105 | Implement the Python class `CenterLoss` described below.
Class description:
Implement the CenterLoss class.
Method signatures and docstrings:
- def __init__(self, feature_number, class_number): 初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量
- def forward(self, feature, target): 计算中心损失 :par... | Implement the Python class `CenterLoss` described below.
Class description:
Implement the CenterLoss class.
Method signatures and docstrings:
- def __init__(self, feature_number, class_number): 初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量
- def forward(self, feature, target): 计算中心损失 :par... | f13669f65a636d31a033681b7849bfebe0dc3e8c | <|skeleton|>
class CenterLoss:
def __init__(self, feature_number, class_number):
"""初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量"""
<|body_0|>
def forward(self, feature, target):
"""计算中心损失 :param feature: 特征向量。 :param target: 分类标签,未进行one_hot处理的。 :return: 损... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CenterLoss:
def __init__(self, feature_number, class_number):
"""初始化中心损失(center loss) :param feature_number:特征的数量 :param class_number:分类的数量"""
super(CenterLoss, self).__init__()
self.class_number = class_number
self.feature_number = feature_number
'将中心点定义为可以学习的参数'
... | the_stack_v2_python_sparse | Chapter03/C03CenterLoss.py | shituo123456/Learn-DeepLearning | train | 0 | |
fbe24aa6d7b0d8824a38d3abfe948dedad94a9f2 | [
"def city_validate(candidate):\n return candidate['city'] == city\n\ndef state_validate(candidate):\n return candidate['state'] == state\n\ndef country_validate(candidate):\n return candidate['country'] == country\npipeline = []\nif city:\n pipeline.append(city_validate)\nif state:\n pipeline.append(... | <|body_start_0|>
def city_validate(candidate):
return candidate['city'] == city
def state_validate(candidate):
return candidate['state'] == state
def country_validate(candidate):
return candidate['country'] == country
pipeline = []
if city:
... | Handler for location based Queries | Globe | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Globe:
"""Handler for location based Queries"""
def _from_geolite(self, city=None, state=None, country=None):
"""Grabs entry from geolite file"""
<|body_0|>
def _from_googlemaps(self, **params):
"""Use google maps API to lookup a location. This is intended to be ... | stack_v2_sparse_classes_75kplus_train_003411 | 7,082 | no_license | [
{
"docstring": "Grabs entry from geolite file",
"name": "_from_geolite",
"signature": "def _from_geolite(self, city=None, state=None, country=None)"
},
{
"docstring": "Use google maps API to lookup a location. This is intended to be a fallback for geolite look ups",
"name": "_from_googlemaps... | 4 | null | Implement the Python class `Globe` described below.
Class description:
Handler for location based Queries
Method signatures and docstrings:
- def _from_geolite(self, city=None, state=None, country=None): Grabs entry from geolite file
- def _from_googlemaps(self, **params): Use google maps API to lookup a location. Th... | Implement the Python class `Globe` described below.
Class description:
Handler for location based Queries
Method signatures and docstrings:
- def _from_geolite(self, city=None, state=None, country=None): Grabs entry from geolite file
- def _from_googlemaps(self, **params): Use google maps API to lookup a location. Th... | 20af9e9a45eb34ec130107c70da2a3de4d498a54 | <|skeleton|>
class Globe:
"""Handler for location based Queries"""
def _from_geolite(self, city=None, state=None, country=None):
"""Grabs entry from geolite file"""
<|body_0|>
def _from_googlemaps(self, **params):
"""Use google maps API to lookup a location. This is intended to be ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Globe:
"""Handler for location based Queries"""
def _from_geolite(self, city=None, state=None, country=None):
"""Grabs entry from geolite file"""
def city_validate(candidate):
return candidate['city'] == city
def state_validate(candidate):
return candidate... | the_stack_v2_python_sparse | cybler/cybler/data/globe.py | adamsar/project-cybler | train | 0 |
8c3b144ac67974f730186f29488ab44f7e6abddb | [
"modules_data = data[src]\nif modules_data.shape[-1] == 1:\n return modules_data.squeeze(axis=-1)\nelse:\n raise NotImplementedError('Number of modules > 1')",
"modules_data = data[src]\nif modules_data.shape[0] == 1:\n return modules_data.squeeze(axis=0)\nelse:\n raise NotImplementedError('Number of ... | <|body_start_0|>
modules_data = data[src]
if modules_data.shape[-1] == 1:
return modules_data.squeeze(axis=-1)
else:
raise NotImplementedError('Number of modules > 1')
<|end_body_0|>
<|body_start_1|>
modules_data = data[src]
if modules_data.shape[0] == 1:... | JungFrauImageAssembler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src):
"""Override. Calibrated data only. - calibrated, "data.adc", (y, x, modules) - raw, "data.adc", TODO -> (y, x)"""
<|body_0|>
def _get_modules_file(self, data, src):
"""Override. - calibrated, "data.adc... | stack_v2_sparse_classes_75kplus_train_003412 | 26,417 | permissive | [
{
"docstring": "Override. Calibrated data only. - calibrated, \"data.adc\", (y, x, modules) - raw, \"data.adc\", TODO -> (y, x)",
"name": "_get_modules_bridge",
"signature": "def _get_modules_bridge(self, data, src)"
},
{
"docstring": "Override. - calibrated, \"data.adc\", (modules, y, x) - raw,... | 2 | stack_v2_sparse_classes_30k_train_019418 | Implement the Python class `JungFrauImageAssembler` described below.
Class description:
Implement the JungFrauImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src): Override. Calibrated data only. - calibrated, "data.adc", (y, x, modules) - raw, "data.adc", TODO -> (y, x)
... | Implement the Python class `JungFrauImageAssembler` described below.
Class description:
Implement the JungFrauImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src): Override. Calibrated data only. - calibrated, "data.adc", (y, x, modules) - raw, "data.adc", TODO -> (y, x)
... | 578c6035af023575a5c026b0391d15884ca1df60 | <|skeleton|>
class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src):
"""Override. Calibrated data only. - calibrated, "data.adc", (y, x, modules) - raw, "data.adc", TODO -> (y, x)"""
<|body_0|>
def _get_modules_file(self, data, src):
"""Override. - calibrated, "data.adc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JungFrauImageAssembler:
def _get_modules_bridge(self, data, src):
"""Override. Calibrated data only. - calibrated, "data.adc", (y, x, modules) - raw, "data.adc", TODO -> (y, x)"""
modules_data = data[src]
if modules_data.shape[-1] == 1:
return modules_data.squeeze(axis=-1)
... | the_stack_v2_python_sparse | extra_foam/pipeline/processors/image_assembler.py | scottwedge/EXtra-foam | train | 0 | |
65e6c97f8709de172e0c2bec40d42f93c5f91c43 | [
"self.cancelled = cancelled\nself.environment = environment\nself.failed = failed\nself.id = id\nself.name = name\nself.parent_source_id = parent_source_id\nself.parent_source_name = parent_source_name\nself.running = running\nself.successful = successful\nself.total = total\nself.trends = trends",
"if dictionary... | <|body_start_0|>
self.cancelled = cancelled
self.environment = environment
self.failed = failed
self.id = id
self.name = name
self.parent_source_id = parent_source_id
self.parent_source_name = parent_source_name
self.running = running
self.successf... | Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies environment. Supported environment types such as 'kView', 'kSQL', 'kVMware', etc. NOTE: ... | ProtectionTrend | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionTrend:
"""Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies environment. Supported environment types such... | stack_v2_sparse_classes_75kplus_train_003413 | 7,571 | permissive | [
{
"docstring": "Constructor for the ProtectionTrend class",
"name": "__init__",
"signature": "def __init__(self, cancelled=None, environment=None, failed=None, id=None, name=None, parent_source_id=None, parent_source_name=None, running=None, successful=None, total=None, trends=None)"
},
{
"docst... | 2 | null | Implement the Python class `ProtectionTrend` described below.
Class description:
Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies enviro... | Implement the Python class `ProtectionTrend` described below.
Class description:
Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies enviro... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class ProtectionTrend:
"""Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies environment. Supported environment types such... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectionTrend:
"""Implementation of the 'ProtectionTrend' model. Specifies details of a protected object with it's protection trends. Attributes: cancelled (long|int): Specifies number of cancelled runs across trends. environment (string): Specifies environment. Supported environment types such as 'kView', ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_trend.py | hsantoyo2/management-sdk-python | train | 0 |
0cbb2057d014f5c58a1cc4fd64588a9067d597ab | [
"data = '{\"sex\":\"S01\",\"isFather\":\"F04\",\"attributeValue\":\"V00\",\"grade\":\"G07\",\"belongSchoolId\":24,\"intentLevel\":\"I02\",\"businessType\":\"B01\",\"custStatus\":\"S01\",\"custType\":\"T00\",\"custName\":\"%s\",\"schoolId\":\"33\",\"schoolName\":\"四基初级中学\",\"infoId\":1073,\"infoType\":\"T01\",\"info... | <|body_start_0|>
data = '{"sex":"S01","isFather":"F04","attributeValue":"V00","grade":"G07","belongSchoolId":24,"intentLevel":"I02","businessType":"B01","custStatus":"S01","custType":"T00","custName":"%s","schoolId":"33","schoolName":"四基初级中学","infoId":1073,"infoType":"T01","infoName":"高分云信息单","phoneInfo":"13800... | CrmRequest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrmRequest:
def save_customer_info(customer_name):
"""输入客户名称生成客户信息 @param customer_name: @return:"""
<|body_0|>
def allot_order(customer_id):
"""将客户id分单给高分云顾问2 @param customer_id: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = '{"se... | stack_v2_sparse_classes_75kplus_train_003414 | 1,384 | no_license | [
{
"docstring": "输入客户名称生成客户信息 @param customer_name: @return:",
"name": "save_customer_info",
"signature": "def save_customer_info(customer_name)"
},
{
"docstring": "将客户id分单给高分云顾问2 @param customer_id: @return:",
"name": "allot_order",
"signature": "def allot_order(customer_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026126 | Implement the Python class `CrmRequest` described below.
Class description:
Implement the CrmRequest class.
Method signatures and docstrings:
- def save_customer_info(customer_name): 输入客户名称生成客户信息 @param customer_name: @return:
- def allot_order(customer_id): 将客户id分单给高分云顾问2 @param customer_id: @return: | Implement the Python class `CrmRequest` described below.
Class description:
Implement the CrmRequest class.
Method signatures and docstrings:
- def save_customer_info(customer_name): 输入客户名称生成客户信息 @param customer_name: @return:
- def allot_order(customer_id): 将客户id分单给高分云顾问2 @param customer_id: @return:
<|skeleton|>
c... | 16bd1ecf5d1c7afa02a3721effb8a0bf078aed67 | <|skeleton|>
class CrmRequest:
def save_customer_info(customer_name):
"""输入客户名称生成客户信息 @param customer_name: @return:"""
<|body_0|>
def allot_order(customer_id):
"""将客户id分单给高分云顾问2 @param customer_id: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrmRequest:
def save_customer_info(customer_name):
"""输入客户名称生成客户信息 @param customer_name: @return:"""
data = '{"sex":"S01","isFather":"F04","attributeValue":"V00","grade":"G07","belongSchoolId":24,"intentLevel":"I02","businessType":"B01","custStatus":"S01","custType":"T00","custName":"%s","scho... | the_stack_v2_python_sparse | func/api_request.py | quanbanno2/new_crm_poium | train | 0 | |
880a58947d4149155008dfcc994b3084ca813d5c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jgrishey', 'jgrishey')\nif trial:\n stations = list(repo['jgrishey.redlineStations'].find(None, ['_id', 'lat', 'lon']))[:20]\n crimes = list(repo['jgrishey.crime'].find(None, ['_id', 'lat', 'long']... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jgrishey', 'jgrishey')
if trial:
stations = list(repo['jgrishey.redlineStations'].find(None, ['_id', 'lat', 'lon']))[:20]
crimes =... | crimeStationStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class crimeStationStats:
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 everyt... | stack_v2_sparse_classes_75kplus_train_003415 | 4,577 | 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_test_002631 | Implement the Python class `crimeStationStats` described below.
Class description:
Implement the crimeStationStats 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... | Implement the Python class `crimeStationStats` described below.
Class description:
Implement the crimeStationStats 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... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class crimeStationStats:
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 everyt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class crimeStationStats:
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('jgrishey', 'jgrishey')
if... | the_stack_v2_python_sparse | jgrishey/crimeStationStats.py | lingyigu/course-2017-spr-proj | train | 0 | |
8b36c256a464f6753e73a4170f4da4db1cd8844c | [
"html = helpers.get_content(url)\nif not html:\n return None\nsoup = BeautifulSoup(html)\ntry:\n headline = soup.h1.string\nexcept AttributeError:\n log.error('Exception trying to scrape CBC headline from %s' % url)\n return None\narticle = soup.find('div', attrs={'class': 'story-content'})\nparagraphs ... | <|body_start_0|>
html = helpers.get_content(url)
if not html:
return None
soup = BeautifulSoup(html)
try:
headline = soup.h1.string
except AttributeError:
log.error('Exception trying to scrape CBC headline from %s' % url)
return Non... | Methods for interacting with the CBC website. | CBC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBC:
"""Methods for interacting with the CBC website."""
def get_article(self, url):
"""Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article at that url, or None if unable to scrape the article."""
... | stack_v2_sparse_classes_75kplus_train_003416 | 1,894 | no_license | [
{
"docstring": "Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article at that url, or None if unable to scrape the article.",
"name": "get_article",
"signature": "def get_article(self, url)"
},
{
"docstring": "Im... | 2 | stack_v2_sparse_classes_30k_train_032946 | Implement the Python class `CBC` described below.
Class description:
Methods for interacting with the CBC website.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article a... | Implement the Python class `CBC` described below.
Class description:
Methods for interacting with the CBC website.
Method signatures and docstrings:
- def get_article(self, url): Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article a... | b1adf7d582eb78623a44611dc07749823da84d5f | <|skeleton|>
class CBC:
"""Methods for interacting with the CBC website."""
def get_article(self, url):
"""Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article at that url, or None if unable to scrape the article."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CBC:
"""Methods for interacting with the CBC website."""
def get_article(self, url):
"""Implementation for getting an article from the CBC. url: A URL in the cbc.ca/news/* domain. Returns: The Article representing the article at that url, or None if unable to scrape the article."""
html =... | the_stack_v2_python_sparse | analysis/scraping/cbc.py | pandrewhk/perspectives | train | 0 |
93b2672e00d2ecace8046d2daca17449173d9003 | [
"super(PositionEmbedding, self).__init__()\nself.dim = dim\nself.freq = freq",
"device = inputs.device\nmax_length = inputs.shape[1]\nembedding_store = PositionEmbedding._embeddings.__dict__\ndevice_store = embedding_store.get(device, {})\nif not device_store or self.dim not in device_store or device_store[self.d... | <|body_start_0|>
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
<|end_body_0|>
<|body_start_1|>
device = inputs.device
max_length = inputs.shape[1]
embedding_store = PositionEmbedding._embeddings.__dict__
device_store = embedding_store.... | Produce position embeddings | PositionEmbedding | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_75kplus_train_003417 | 3,716 | permissive | [
{
"docstring": "Initialize the PositionEmbedding",
"name": "__init__",
"signature": "def __init__(self, dim, freq=10000.0)"
},
{
"docstring": "Implement the forward pass of the embedding",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_034893 | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding
<|skeleton|>
class Positi... | 0fa4adffa825af4a62b6e739b59c4125a7b6698e | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
def forward(self, inputs):
"""Implement the forward pas... | the_stack_v2_python_sparse | models/embeddings.py | fallcat/synst | train | 1 |
c03f7d258c3bf2be5f8fd28ad661b6fd04e75c21 | [
"BasicExperimentView.__init__(self)\nself.title = title\nself.descr = descr\nself.series = series\nself.separator = separator\nself.link_text = link_text\nself.run_link_text = run_link_text",
"file.write('defaultTableView')\nfields = {}\nif not self.title is None:\n func = lambda file, indent: file.write(encod... | <|body_start_0|>
BasicExperimentView.__init__(self)
self.title = title
self.descr = descr
self.series = series
self.separator = separator
self.link_text = link_text
self.run_link_text = run_link_text
<|end_body_0|>
<|body_start_1|>
file.write('defaultTabl... | It saves the simulation results in CSV file(s). | TableView | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TableView:
"""It saves the simulation results in CSV file(s)."""
def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None):
"""Initializes a new instance."""
<|body_0|>
def write(self, file, indent=''):
"""Write t... | stack_v2_sparse_classes_75kplus_train_003418 | 2,095 | permissive | [
{
"docstring": "Initializes a new instance.",
"name": "__init__",
"signature": "def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None)"
},
{
"docstring": "Write the view definition in the file.",
"name": "write",
"signature": "def writ... | 2 | null | Implement the Python class `TableView` described below.
Class description:
It saves the simulation results in CSV file(s).
Method signatures and docstrings:
- def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None): Initializes a new instance.
- def write(self, file... | Implement the Python class `TableView` described below.
Class description:
It saves the simulation results in CSV file(s).
Method signatures and docstrings:
- def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None): Initializes a new instance.
- def write(self, file... | 5c112015f9af6ba1974a3b208842da01e705f9ac | <|skeleton|>
class TableView:
"""It saves the simulation results in CSV file(s)."""
def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None):
"""Initializes a new instance."""
<|body_0|>
def write(self, file, indent=''):
"""Write t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TableView:
"""It saves the simulation results in CSV file(s)."""
def __init__(self, title=None, descr=None, series=None, separator=None, link_text=None, run_link_text=None):
"""Initializes a new instance."""
BasicExperimentView.__init__(self)
self.title = title
self.descr ... | the_stack_v2_python_sparse | simulation/aivika/modeler/experiment/base/table.py | dsorokin/aivika-modeler | train | 0 |
eaaf6cd5eb0f8eefbb0efe104b5714abf25adef3 | [
"inputSpecification = super().getInputSpecification()\ninputSpecification.addSubSimple('xmlNodeExample', InputTypes.StringType)\nreturn inputSpecification",
"super().__init__()\nself.setInputDataType('dict')\nself.keepInputMeta(True)\nself.outputMultipleRealizations = True\nself.validDataType = ['HistorySet']",
... | <|body_start_0|>
inputSpecification = super().getInputSpecification()
inputSpecification.addSubSimple('xmlNodeExample', InputTypes.StringType)
return inputSpecification
<|end_body_0|>
<|body_start_1|>
super().__init__()
self.setInputDataType('dict')
self.keepInputMeta(Tr... | This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run | testInterfacedPP | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_75kplus_train_003419 | 3,631 | permissive | [
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for which we are retrieving the specification @ Out, inputSpecification, InputData.ParameterInput, class to use for specifying input of cls.",
"name": "getInputSpecification",
"signatur... | 5 | stack_v2_sparse_classes_30k_train_018992 | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run
Method signatures and do... | Implement the Python class `testInterfacedPP` described below.
Class description:
This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run
Method signatures and do... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class testInterfacedPP:
"""This class represents the most basic interfaced post-processor This class inherits form the base class PostProcessorInterfaceBase and it contains the three methods that need to be implemented: - initialize - run"""
def getInputSpecification(cls):
"""Method to get a reference ... | the_stack_v2_python_sparse | plugins/ExamplePlugin/src/testInterfacedPP.py | idaholab/raven | train | 201 |
0041a4611c5562e8f9b0cb798b5f1ca1398eaa6c | [
"self.repositories_cache_dir_name = ''\nself.repositories_cache_path = ''\nself._load_repositories_cache_config()",
"config_file: ConfigParser = load_config_file()\nself.repositories_cache_dir_name = config_file.get(section='repos_cache', option='directory_name', fallback='pipwatch-cache')\nself.repositories_cach... | <|body_start_0|>
self.repositories_cache_dir_name = ''
self.repositories_cache_path = ''
self._load_repositories_cache_config()
<|end_body_0|>
<|body_start_1|>
config_file: ConfigParser = load_config_file()
self.repositories_cache_dir_name = config_file.get(section='repos_cache'... | Encompasses logic of retrieving path and directory name of Worker cache. | RepositoriesCacheMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoriesCacheMixin:
"""Encompasses logic of retrieving path and directory name of Worker cache."""
def __init__(self):
"""Create method instance."""
<|body_0|>
def _load_repositories_cache_config(self) -> None:
"""Load appropriate entries from configuration f... | stack_v2_sparse_classes_75kplus_train_003420 | 6,449 | permissive | [
{
"docstring": "Create method instance.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load appropriate entries from configuration file.",
"name": "_load_repositories_cache_config",
"signature": "def _load_repositories_cache_config(self) -> None"
}
] | 2 | stack_v2_sparse_classes_30k_train_028245 | Implement the Python class `RepositoriesCacheMixin` described below.
Class description:
Encompasses logic of retrieving path and directory name of Worker cache.
Method signatures and docstrings:
- def __init__(self): Create method instance.
- def _load_repositories_cache_config(self) -> None: Load appropriate entries... | Implement the Python class `RepositoriesCacheMixin` described below.
Class description:
Encompasses logic of retrieving path and directory name of Worker cache.
Method signatures and docstrings:
- def __init__(self): Create method instance.
- def _load_repositories_cache_config(self) -> None: Load appropriate entries... | bff0c5198d6a433a7ca9d03c82dae981d8b85dd1 | <|skeleton|>
class RepositoriesCacheMixin:
"""Encompasses logic of retrieving path and directory name of Worker cache."""
def __init__(self):
"""Create method instance."""
<|body_0|>
def _load_repositories_cache_config(self) -> None:
"""Load appropriate entries from configuration f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RepositoriesCacheMixin:
"""Encompasses logic of retrieving path and directory name of Worker cache."""
def __init__(self):
"""Create method instance."""
self.repositories_cache_dir_name = ''
self.repositories_cache_path = ''
self._load_repositories_cache_config()
def ... | the_stack_v2_python_sparse | worker/pipwatch_worker/worker/commands.py | AleksanderGondek/pipwatch | train | 1 |
5155de880b1bccfc04a73a6fe1917d7bf3696a5f | [
"objLogger.debug(Message.REQUEST)\nrequest_data = request.headers\nobjLogger.debug(request_data)\ntry:\n if 'email' in request_data:\n data = mongo_db.read({'user': request_data['email']})\n else:\n data = mongo_db.read()\nexcept KeyError as error:\n response = objResponse.send_exception(objE... | <|body_start_0|>
objLogger.debug(Message.REQUEST)
request_data = request.headers
objLogger.debug(request_data)
try:
if 'email' in request_data:
data = mongo_db.read({'user': request_data['email']})
else:
data = mongo_db.read()
... | PostsCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostsCollection:
def get(self):
"""Método de READ"""
<|body_0|>
def post(self):
"""Método de CREATE"""
<|body_1|>
def put(sefl):
"""Método de UPDATE"""
<|body_2|>
def delete(self):
"""Método de DELETE"""
<|body_3|>
<... | stack_v2_sparse_classes_75kplus_train_003421 | 5,159 | no_license | [
{
"docstring": "Método de READ",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Método de CREATE",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Método de UPDATE",
"name": "put",
"signature": "def put(sefl)"
},
{
"docstring": "Mé... | 4 | null | Implement the Python class `PostsCollection` described below.
Class description:
Implement the PostsCollection class.
Method signatures and docstrings:
- def get(self): Método de READ
- def post(self): Método de CREATE
- def put(sefl): Método de UPDATE
- def delete(self): Método de DELETE | Implement the Python class `PostsCollection` described below.
Class description:
Implement the PostsCollection class.
Method signatures and docstrings:
- def get(self): Método de READ
- def post(self): Método de CREATE
- def put(sefl): Método de UPDATE
- def delete(self): Método de DELETE
<|skeleton|>
class PostsCol... | bb7dcb99621ae5a93f24b789b60b019aa155fbf5 | <|skeleton|>
class PostsCollection:
def get(self):
"""Método de READ"""
<|body_0|>
def post(self):
"""Método de CREATE"""
<|body_1|>
def put(sefl):
"""Método de UPDATE"""
<|body_2|>
def delete(self):
"""Método de DELETE"""
<|body_3|>
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostsCollection:
def get(self):
"""Método de READ"""
objLogger.debug(Message.REQUEST)
request_data = request.headers
objLogger.debug(request_data)
try:
if 'email' in request_data:
data = mongo_db.read({'user': request_data['email']})
... | the_stack_v2_python_sparse | backend/mongo_crud/api/projeto/api/operation_basic.py | DiegoCrassus/PDM-APP1 | train | 0 | |
9791d4b1c0458cfe8247b76f095615a135a4692e | [
"if n == 0 or n == 1:\n return 1\nreturn self.fib(n - 1) + self.fib(n - 2)",
"if n == 0:\n return 1\nreturn self.fact(n - 1) * n"
] | <|body_start_0|>
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
<|end_body_0|>
<|body_start_1|>
if n == 0:
return 1
return self.fact(n - 1) * n
<|end_body_1|>
| MyMath | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
<|body_0|>
def fact(self, n):
"""Returns n!"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
<... | stack_v2_sparse_classes_75kplus_train_003422 | 2,510 | no_license | [
{
"docstring": "Returns the nth # of Fibonacci's",
"name": "fib",
"signature": "def fib(self, n)"
},
{
"docstring": "Returns n!",
"name": "fact",
"signature": "def fact(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000969 | Implement the Python class `MyMath` described below.
Class description:
Implement the MyMath class.
Method signatures and docstrings:
- def fib(self, n): Returns the nth # of Fibonacci's
- def fact(self, n): Returns n! | Implement the Python class `MyMath` described below.
Class description:
Implement the MyMath class.
Method signatures and docstrings:
- def fib(self, n): Returns the nth # of Fibonacci's
- def fact(self, n): Returns n!
<|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
... | de912b450a0ff6bb84024cdf653a0ee2f6086be1 | <|skeleton|>
class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
<|body_0|>
def fact(self, n):
"""Returns n!"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyMath:
def fib(self, n):
"""Returns the nth # of Fibonacci's"""
if n == 0 or n == 1:
return 1
return self.fib(n - 1) + self.fib(n - 2)
def fact(self, n):
"""Returns n!"""
if n == 0:
return 1
return self.fact(n - 1) * n
| the_stack_v2_python_sparse | cazzola.py | giuscri/problem-solving-workout | train | 1 | |
02eb0018f98fe66d291c2c74949d2ba4ca302c95 | [
"self._caffe = kwargs.pop('caffe')\nkwargs.setdefault('label_suffix', '')\nsuper(PositionForm, self).__init__(*args, **kwargs)\nself.fields['name'].label = u'Nazwa'\nif self.instance.id:\n self.initial['name'] = self.instance.name",
"name = self.cleaned_data['name']\nquery = Position.objects.filter(name=name, ... | <|body_start_0|>
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(PositionForm, self).__init__(*args, **kwargs)
self.fields['name'].label = u'Nazwa'
if self.instance.id:
self.initial['name'] = self.instance.name
<|end_body_0|>
<|body_star... | Responsible for checking Position model. | PositionForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionForm:
"""Responsible for checking Position model."""
def __init__(self, *args, **kwargs):
"""Initialize all Position's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Over... | stack_v2_sparse_classes_75kplus_train_003423 | 4,273 | permissive | [
{
"docstring": "Initialize all Position's fields.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Check name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Override the save method to add Caffe rel... | 3 | stack_v2_sparse_classes_30k_train_034133 | Implement the Python class `PositionForm` described below.
Class description:
Responsible for checking Position model.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Position's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override the save m... | Implement the Python class `PositionForm` described below.
Class description:
Responsible for checking Position model.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize all Position's fields.
- def clean_name(self): Check name field.
- def save(self, commit=True): Override the save m... | cdb7f5edb29255c7e874eaa6231621063210a8b0 | <|skeleton|>
class PositionForm:
"""Responsible for checking Position model."""
def __init__(self, *args, **kwargs):
"""Initialize all Position's fields."""
<|body_0|>
def clean_name(self):
"""Check name field."""
<|body_1|>
def save(self, commit=True):
"""Over... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionForm:
"""Responsible for checking Position model."""
def __init__(self, *args, **kwargs):
"""Initialize all Position's fields."""
self._caffe = kwargs.pop('caffe')
kwargs.setdefault('label_suffix', '')
super(PositionForm, self).__init__(*args, **kwargs)
sel... | the_stack_v2_python_sparse | caffe/hours/forms.py | VirrageS/io-kawiarnie | train | 3 |
79d9bd3342f73ed4f2448733d6ba2dd859315188 | [
"user_id = int(user_id)\ntry:\n user_type = UserType(user_type)\nexcept ValueError as e:\n self._sout.write(f\"{e}: valid values are {', '.join((x.value for x in UserType))}\\n\")\n return\ntry:\n fetch = asyncio.run_coroutine_threadsafe(set_user_admin(user_id, user_type), self._loop)\n user = fetch.... | <|body_start_0|>
user_id = int(user_id)
try:
user_type = UserType(user_type)
except ValueError as e:
self._sout.write(f"{e}: valid values are {', '.join((x.value for x in UserType))}\n")
return
try:
fetch = asyncio.run_coroutine_threadsafe(... | Tap2GoMonitor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tap2GoMonitor:
def do_set_user_level(self, user_id: str, user_type: str):
"""Set's a user's admin level to the provided value."""
<|body_0|>
def do_search_user(self, name: str):
"""Search a user by name."""
<|body_1|>
def do_get_bikes(self):
"""G... | stack_v2_sparse_classes_75kplus_train_003424 | 2,623 | permissive | [
{
"docstring": "Set's a user's admin level to the provided value.",
"name": "do_set_user_level",
"signature": "def do_set_user_level(self, user_id: str, user_type: str)"
},
{
"docstring": "Search a user by name.",
"name": "do_search_user",
"signature": "def do_search_user(self, name: str... | 5 | stack_v2_sparse_classes_30k_train_012135 | Implement the Python class `Tap2GoMonitor` described below.
Class description:
Implement the Tap2GoMonitor class.
Method signatures and docstrings:
- def do_set_user_level(self, user_id: str, user_type: str): Set's a user's admin level to the provided value.
- def do_search_user(self, name: str): Search a user by nam... | Implement the Python class `Tap2GoMonitor` described below.
Class description:
Implement the Tap2GoMonitor class.
Method signatures and docstrings:
- def do_set_user_level(self, user_id: str, user_type: str): Set's a user's admin level to the provided value.
- def do_search_user(self, name: str): Search a user by nam... | fc6f9230e4701cbddcb16d7257fddb9ff08bddb9 | <|skeleton|>
class Tap2GoMonitor:
def do_set_user_level(self, user_id: str, user_type: str):
"""Set's a user's admin level to the provided value."""
<|body_0|>
def do_search_user(self, name: str):
"""Search a user by name."""
<|body_1|>
def do_get_bikes(self):
"""G... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tap2GoMonitor:
def do_set_user_level(self, user_id: str, user_type: str):
"""Set's a user's admin level to the provided value."""
user_id = int(user_id)
try:
user_type = UserType(user_type)
except ValueError as e:
self._sout.write(f"{e}: valid values are... | the_stack_v2_python_sparse | server/monitor.py | dragorhast/server | train | 6 | |
1bba85d84ea79415be7dcc20045ca2da8b55279f | [
"super(Quantity, self).__init__(name, **kwargs)\nself.unit = unit\nself.data_type = data_type",
"if not isinstance(value, self.data_type):\n try:\n value = self.data_type(text_type(value))\n except ValueError:\n self.report(value, context)\n return\nreturn value if context.get('no_units... | <|body_start_0|>
super(Quantity, self).__init__(name, **kwargs)
self.unit = unit
self.data_type = data_type
<|end_body_0|>
<|body_start_1|>
if not isinstance(value, self.data_type):
try:
value = self.data_type(text_type(value))
except ValueError:
... | Quantity is a property with unit. | Quantity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quantity:
"""Quantity is a property with unit."""
def __init__(self, name, unit, data_type=int, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value with unit."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_003425 | 771 | permissive | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, name, unit, data_type=int, **kwargs)"
},
{
"docstring": "Handle value with unit.",
"name": "handle",
"signature": "def handle(self, value, context)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052112 | Implement the Python class `Quantity` described below.
Class description:
Quantity is a property with unit.
Method signatures and docstrings:
- def __init__(self, name, unit, data_type=int, **kwargs): Init method.
- def handle(self, value, context): Handle value with unit. | Implement the Python class `Quantity` described below.
Class description:
Quantity is a property with unit.
Method signatures and docstrings:
- def __init__(self, name, unit, data_type=int, **kwargs): Init method.
- def handle(self, value, context): Handle value with unit.
<|skeleton|>
class Quantity:
"""Quantit... | eea9ac18e38c930230cf81b5dca4a9af9fb10d4e | <|skeleton|>
class Quantity:
"""Quantity is a property with unit."""
def __init__(self, name, unit, data_type=int, **kwargs):
"""Init method."""
<|body_0|>
def handle(self, value, context):
"""Handle value with unit."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Quantity:
"""Quantity is a property with unit."""
def __init__(self, name, unit, data_type=int, **kwargs):
"""Init method."""
super(Quantity, self).__init__(name, **kwargs)
self.unit = unit
self.data_type = data_type
def handle(self, value, context):
"""Handle... | the_stack_v2_python_sparse | knowit/properties/quantity.py | labrys/knowit | train | 0 |
6028a26c8e733711a4f6feb199356b1674bbfc2c | [
"try:\n log_dict = req.json_body\n ActionLogDao().insert_log(log_dict)\nexcept Exception as e:\n LOG.error(str(e))\n LOG.error(traceback.format_exc())\n return outError('插入日志信息失败!')",
"try:\n info = {'condition': {'dateFrom': req.params.get('dateFrom'), 'dateTo': req.params.get('dateTo'), 'keywo... | <|body_start_0|>
try:
log_dict = req.json_body
ActionLogDao().insert_log(log_dict)
except Exception as e:
LOG.error(str(e))
LOG.error(traceback.format_exc())
return outError('插入日志信息失败!')
<|end_body_0|>
<|body_start_1|>
try:
... | Controller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Controller:
def insert_log(self, req, *args, **kwargs):
"""插入一条记录 :return:"""
<|body_0|>
def actionlog_list(self, req, *args, **kwargs):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
log_dict = req.json_body
... | stack_v2_sparse_classes_75kplus_train_003426 | 1,908 | no_license | [
{
"docstring": "插入一条记录 :return:",
"name": "insert_log",
"signature": "def insert_log(self, req, *args, **kwargs)"
},
{
"docstring": ":return:",
"name": "actionlog_list",
"signature": "def actionlog_list(self, req, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004723 | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def insert_log(self, req, *args, **kwargs): 插入一条记录 :return:
- def actionlog_list(self, req, *args, **kwargs): :return: | Implement the Python class `Controller` described below.
Class description:
Implement the Controller class.
Method signatures and docstrings:
- def insert_log(self, req, *args, **kwargs): 插入一条记录 :return:
- def actionlog_list(self, req, *args, **kwargs): :return:
<|skeleton|>
class Controller:
def insert_log(sel... | 7dfda640740507199b291d01cb8304df570f2664 | <|skeleton|>
class Controller:
def insert_log(self, req, *args, **kwargs):
"""插入一条记录 :return:"""
<|body_0|>
def actionlog_list(self, req, *args, **kwargs):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Controller:
def insert_log(self, req, *args, **kwargs):
"""插入一条记录 :return:"""
try:
log_dict = req.json_body
ActionLogDao().insert_log(log_dict)
except Exception as e:
LOG.error(str(e))
LOG.error(traceback.format_exc())
return ... | the_stack_v2_python_sparse | billing/controller/ActionLog.py | greshem/openstack_bootstrap_dashboard | train | 0 | |
a91fa25daa5f1a1027838972c8a29d383aaf128c | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')\nrepo.dropCollection('housing_percentages')\nrepo.createCollection('housing_percentages')\nrepo.raykatz_nedg_gaudiosi.housing.aggregate([{'$project': {'zi... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
repo.dropCollection('housing_percentages')
repo.createCollection('housing_percentages')
r... | housing_percentages | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class housing_percentages:
def execute(trial=False):
"""Merge zipcode info"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script wi... | stack_v2_sparse_classes_75kplus_train_003427 | 4,085 | no_license | [
{
"docstring": "Merge zipcode info",
"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 document describing that invocation event.",
"name": "p... | 2 | stack_v2_sparse_classes_30k_train_009238 | Implement the Python class `housing_percentages` described below.
Class description:
Implement the housing_percentages class.
Method signatures and docstrings:
- def execute(trial=False): Merge zipcode info
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d... | Implement the Python class `housing_percentages` described below.
Class description:
Implement the housing_percentages class.
Method signatures and docstrings:
- def execute(trial=False): Merge zipcode info
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create the provenance document d... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class housing_percentages:
def execute(trial=False):
"""Merge zipcode info"""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this script. Each run of the script wi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class housing_percentages:
def execute(trial=False):
"""Merge zipcode info"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('raykatz_nedg_gaudiosi', 'raykatz_nedg_gaudiosi')
repo.dropCollection('housing_per... | the_stack_v2_python_sparse | raykatz_nedg_gaudiosi/housing_percentages.py | ROODAY/course-2017-fal-proj | train | 3 | |
9510a83adeb81c80dd396e63d1d809a7368ae555 | [
"option_question_numbers = Interview_options.objects.filter(flag=grade).order_by('?')[:option_question_number].values('id')\nshort_question_numbers = Interview_sort_answer.objects.filter(flag=grade).order_by('?')[:short_question_number].values('id')\noption_title_id = [v for i in option_question_numbers for k, v in... | <|body_start_0|>
option_question_numbers = Interview_options.objects.filter(flag=grade).order_by('?')[:option_question_number].values('id')
short_question_numbers = Interview_sort_answer.objects.filter(flag=grade).order_by('?')[:short_question_number].values('id')
option_title_id = [v for i in o... | 将用户id和随机题目绑定一起 | UserAndTitle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAndTitle:
"""将用户id和随机题目绑定一起"""
def select_title(cls, grade, option_question_number, short_question_number):
"""随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号"""
<|body_0|>
def save_u... | stack_v2_sparse_classes_75kplus_train_003428 | 8,285 | no_license | [
{
"docstring": "随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号",
"name": "select_title",
"signature": "def select_title(cls, grade, option_question_number, short_question_number)"
},
{
"docstring": "将用户id和随机题目绑定... | 2 | stack_v2_sparse_classes_30k_train_012257 | Implement the Python class `UserAndTitle` described below.
Class description:
将用户id和随机题目绑定一起
Method signatures and docstrings:
- def select_title(cls, grade, option_question_number, short_question_number): 随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简... | Implement the Python class `UserAndTitle` described below.
Class description:
将用户id和随机题目绑定一起
Method signatures and docstrings:
- def select_title(cls, grade, option_question_number, short_question_number): 随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简... | 4febccac57bfa5f7ef46f5f57e52206c8b0a57ac | <|skeleton|>
class UserAndTitle:
"""将用户id和随机题目绑定一起"""
def select_title(cls, grade, option_question_number, short_question_number):
"""随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号"""
<|body_0|>
def save_u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserAndTitle:
"""将用户id和随机题目绑定一起"""
def select_title(cls, grade, option_question_number, short_question_number):
"""随机筛选出各个阶段需要的题目数量 :param grade: 难度 :param option_question_number: 难度等级的选择题数量 :param short_question_number: 难度等级的简答题数量 :return: 相应的题号"""
option_question_numbers = Interview_opt... | the_stack_v2_python_sparse | item/interview/backend/utils.py | soulorman/Python | train | 0 |
dc4ce169c6280093d368b95b81b5e27f8afee658 | [
"self.utils = Utils.Utils()\nself.eucacluster = eucacluster\nself.NoSQLCluster = NoSQLCluster\nself.polManager = PolicyManager('test', self.eucacluster, self.NoSQLCluster)\nself.acted = ['done']\nself.runonce = 'once'\ncluster_size = len(self.utils.get_cluster_from_db(self.utils.cluster_name))\nself.currentState = ... | <|body_start_0|>
self.utils = Utils.Utils()
self.eucacluster = eucacluster
self.NoSQLCluster = NoSQLCluster
self.polManager = PolicyManager('test', self.eucacluster, self.NoSQLCluster)
self.acted = ['done']
self.runonce = 'once'
cluster_size = len(self.utils.get_c... | MyDecisionMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
... | stack_v2_sparse_classes_75kplus_train_003429 | 7,638 | no_license | [
{
"docstring": "Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster",
"name": "__init__",
"signature": "def __init__(self, eucacluster, NoSQLClus... | 2 | stack_v2_sparse_classes_30k_train_043962 | Implement the Python class `MyDecisionMaker` described below.
Class description:
Implement the MyDecisionMaker class.
Method signatures and docstrings:
- def __init__(self, eucacluster, NoSQLCluster): Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus ... | Implement the Python class `MyDecisionMaker` described below.
Class description:
Implement the MyDecisionMaker class.
Method signatures and docstrings:
- def __init__(self, eucacluster, NoSQLCluster): Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus ... | 234c3e38f8698c5b5a5193ab1d510c6fbccd9623 | <|skeleton|>
class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
self.utils = ... | the_stack_v2_python_sparse | MyTiramola/LwlosTiramola/MyDecisionMaker.py | gioargyr/MyTiramola | train | 0 | |
32632a85dc78eef9588f422bb3ad2b38452baa05 | [
"if (delta_value := data.get('delta')):\n if isinstance(delta_value, str):\n if (internal_value := DISTRIBUTED_COST_INTERNAL.get(delta_value)):\n data['delta'] = internal_value\n if delta_value == 'cost':\n data['delta'] = 'cost_total'\nreturn super().to_internal_value(data)",... | <|body_start_0|>
if (delta_value := data.get('delta')):
if isinstance(delta_value, str):
if (internal_value := DISTRIBUTED_COST_INTERNAL.get(delta_value)):
data['delta'] = internal_value
if delta_value == 'cost':
data['delta'] =... | Serializer for handling query parameters. | OCPQueryParamSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPQueryParamSerializer:
"""Serializer for handling query parameters."""
def to_internal_value(self, data):
"""Send to internal value."""
<|body_0|>
def validate(self, data):
"""Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Vali... | stack_v2_sparse_classes_75kplus_train_003430 | 8,876 | permissive | [
{
"docstring": "Send to internal value.",
"name": "to_internal_value",
"signature": "def to_internal_value(self, data)"
},
{
"docstring": "Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Validated data Raises: (ValidationError): if field inputs are invalid",
... | 3 | stack_v2_sparse_classes_30k_train_050610 | Implement the Python class `OCPQueryParamSerializer` described below.
Class description:
Serializer for handling query parameters.
Method signatures and docstrings:
- def to_internal_value(self, data): Send to internal value.
- def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated ... | Implement the Python class `OCPQueryParamSerializer` described below.
Class description:
Serializer for handling query parameters.
Method signatures and docstrings:
- def to_internal_value(self, data): Send to internal value.
- def validate(self, data): Validate incoming data. Args: data (Dict): data to be validated ... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class OCPQueryParamSerializer:
"""Serializer for handling query parameters."""
def to_internal_value(self, data):
"""Send to internal value."""
<|body_0|>
def validate(self, data):
"""Validate incoming data. Args: data (Dict): data to be validated Returns: (Dict): Vali... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OCPQueryParamSerializer:
"""Serializer for handling query parameters."""
def to_internal_value(self, data):
"""Send to internal value."""
if (delta_value := data.get('delta')):
if isinstance(delta_value, str):
if (internal_value := DISTRIBUTED_COST_INTERNAL.get... | the_stack_v2_python_sparse | koku/api/report/ocp/serializers.py | project-koku/koku | train | 225 |
0bfc6f17eb14638f0b7e86694463ca8781d012a4 | [
"for node in orm.Node.objects.all():\n mgmt_addr = node_mgmt_address(node)\n url = NODES_NODE_API_BASE_URI_DEFAULT % {'mgmt_addr': mgmt_addr}\n orm.NodeApi.objects.create(node=node, base_uri=url, cert=node.cert)\nif not orm.Server.objects.exists():\n description = run('hostname', display=False).stdout\n... | <|body_start_0|>
for node in orm.Node.objects.all():
mgmt_addr = node_mgmt_address(node)
url = NODES_NODE_API_BASE_URI_DEFAULT % {'mgmt_addr': mgmt_addr}
orm.NodeApi.objects.create(node=node, base_uri=url, cert=node.cert)
if not orm.Server.objects.exists():
... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Create default NodeApi and ServerApi for existing objects."""
<|body_0|>
def backwards(self, orm):
"""Remove all the NodeApi and ServerApi objects."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for node in or... | stack_v2_sparse_classes_75kplus_train_003431 | 8,631 | no_license | [
{
"docstring": "Create default NodeApi and ServerApi for existing objects.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Remove all the NodeApi and ServerApi objects.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001320 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Create default NodeApi and ServerApi for existing objects.
- def backwards(self, orm): Remove all the NodeApi and ServerApi objects. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Create default NodeApi and ServerApi for existing objects.
- def backwards(self, orm): Remove all the NodeApi and ServerApi objects.
<|skeleton|>
clas... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Create default NodeApi and ServerApi for existing objects."""
<|body_0|>
def backwards(self, orm):
"""Remove all the NodeApi and ServerApi objects."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Migration:
def forwards(self, orm):
"""Create default NodeApi and ServerApi for existing objects."""
for node in orm.Node.objects.all():
mgmt_addr = node_mgmt_address(node)
url = NODES_NODE_API_BASE_URI_DEFAULT % {'mgmt_addr': mgmt_addr}
orm.NodeApi.objects.... | the_stack_v2_python_sparse | controller/apps/nodes/migrations/0013_datamigration__move__node_cert__nodeapi_cert.py | m00dy/vct-controller | train | 2 | |
f239b516fef830893dfddd9af509b3b4dd7cc26d | [
"payload = {'token': test_token}\nexpected_status = 200\noutput = requests.post(url, json=payload)\nassert output.status_code == expected_status",
"payload = {'tokfdsen': test_token}\noutput = requests.post(url, json=payload)\nexpected_status = '531'\nassert output.json()['error']['status'] == expected_status",
... | <|body_start_0|>
payload = {'token': test_token}
expected_status = 200
output = requests.post(url, json=payload)
assert output.status_code == expected_status
<|end_body_0|>
<|body_start_1|>
payload = {'tokfdsen': test_token}
output = requests.post(url, json=payload)
... | The class has to be here in order to be run before the deletion of the upload | TestSpaceUsedUploads | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSpaceUsedUploads:
"""The class has to be here in order to be run before the deletion of the upload"""
def test_post(self):
"""this test will pass the uploads/space_used method"""
<|body_0|>
def test_post_missing_parameter(self):
"""this test will fail because... | stack_v2_sparse_classes_75kplus_train_003432 | 1,237 | permissive | [
{
"docstring": "this test will pass the uploads/space_used method",
"name": "test_post",
"signature": "def test_post(self)"
},
{
"docstring": "this test will fail because of missing parameters",
"name": "test_post_missing_parameter",
"signature": "def test_post_missing_parameter(self)"
... | 3 | stack_v2_sparse_classes_30k_train_046887 | Implement the Python class `TestSpaceUsedUploads` described below.
Class description:
The class has to be here in order to be run before the deletion of the upload
Method signatures and docstrings:
- def test_post(self): this test will pass the uploads/space_used method
- def test_post_missing_parameter(self): this t... | Implement the Python class `TestSpaceUsedUploads` described below.
Class description:
The class has to be here in order to be run before the deletion of the upload
Method signatures and docstrings:
- def test_post(self): this test will pass the uploads/space_used method
- def test_post_missing_parameter(self): this t... | ba1e287dbc63e34bf9feb80b65b02c1db93ce91c | <|skeleton|>
class TestSpaceUsedUploads:
"""The class has to be here in order to be run before the deletion of the upload"""
def test_post(self):
"""this test will pass the uploads/space_used method"""
<|body_0|>
def test_post_missing_parameter(self):
"""this test will fail because... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestSpaceUsedUploads:
"""The class has to be here in order to be run before the deletion of the upload"""
def test_post(self):
"""this test will pass the uploads/space_used method"""
payload = {'token': test_token}
expected_status = 200
output = requests.post(url, json=pay... | the_stack_v2_python_sparse | pytest_suit/routes/uploads/test_spaceUsedUploads.py | HotMaps/Hotmaps-toolbox-service | train | 4 |
e1e2074cd9c8f90baffffb2d96d4f32b5f4b0646 | [
"test_response = self.client.get('/people/')\nself.assertEqual(test_response.status_code, 200)\nself.assertTrue('personnel' in test_response.context)\nself.assertTemplateUsed(test_response, 'personnel_list.html')\nself.assertEqual(test_response.context['personnel_type'], 'current')\nself.assertEqual(test_response.c... | <|body_start_0|>
test_response = self.client.get('/people/')
self.assertEqual(test_response.status_code, 200)
self.assertTrue('personnel' in test_response.context)
self.assertTemplateUsed(test_response, 'personnel_list.html')
self.assertEqual(test_response.context['personnel_type... | Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app. | PersonnelViewTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
<|body_0|>
def test_personnel_detail(self):
"""This func... | stack_v2_sparse_classes_75kplus_train_003433 | 5,452 | permissive | [
{
"docstring": "This function tests the laboratory-personnel view.",
"name": "test_laboratory_personnel",
"signature": "def test_laboratory_personnel(self)"
},
{
"docstring": "This function tests the personnel-details view.",
"name": "test_personnel_detail",
"signature": "def test_person... | 2 | stack_v2_sparse_classes_30k_train_029284 | Implement the Python class `PersonnelViewTests` described below.
Class description:
Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_laboratory_personnel(self): This function tests the laboratory-personnel view.
- def test_personnel_de... | Implement the Python class `PersonnelViewTests` described below.
Class description:
Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_laboratory_personnel(self): This function tests the laboratory-personnel view.
- def test_personnel_de... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
<|body_0|>
def test_personnel_detail(self):
"""This func... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
test_response = self.client.get('/people/')
self.assertEqual(test_response... | the_stack_v2_python_sparse | personnel/tests.py | BridgesLab/Lab-Website | train | 0 |
742f095bafe24ed22184fb4cb38b7341c3c6a85d | [
"if not nums:\n return 0\nnums = list(set(nums))\nif len(nums) < 3:\n return max(nums)\na = nums[:3]\na.sort(reverse=True)\nfor i in nums[3:]:\n if i > a[2]:\n t = 2\n while i > a[t] and t >= 0:\n t -= 1\n index = t + 1\n a.insert(index, i)\n a.pop()\nreturn a[... | <|body_start_0|>
if not nums:
return 0
nums = list(set(nums))
if len(nums) < 3:
return max(nums)
a = nums[:3]
a.sort(reverse=True)
for i in nums[3:]:
if i > a[2]:
t = 2
while i > a[t] and t >= 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int 164ms"""
<|body_0|>
def thirdMax2(self, nums):
""":type nums: List[int] :rtype: int 92ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
... | stack_v2_sparse_classes_75kplus_train_003434 | 1,254 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 164ms",
"name": "thirdMax",
"signature": "def thirdMax(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 92ms",
"name": "thirdMax2",
"signature": "def thirdMax2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046679 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int 164ms
- def thirdMax2(self, nums): :type nums: List[int] :rtype: int 92ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def thirdMax(self, nums): :type nums: List[int] :rtype: int 164ms
- def thirdMax2(self, nums): :type nums: List[int] :rtype: int 92ms
<|skeleton|>
class Solution:
def third... | 624975f767f6efa1d7361cc077eaebc344d57210 | <|skeleton|>
class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int 164ms"""
<|body_0|>
def thirdMax2(self, nums):
""":type nums: List[int] :rtype: int 92ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def thirdMax(self, nums):
""":type nums: List[int] :rtype: int 164ms"""
if not nums:
return 0
nums = list(set(nums))
if len(nums) < 3:
return max(nums)
a = nums[:3]
a.sort(reverse=True)
for i in nums[3:]:
if ... | the_stack_v2_python_sparse | 414. 第三大的数.py | dx19910707/LeetCode | train | 0 | |
f6c09b1bc696e6442fc5cadacc3cfb9f90e04232 | [
"self.times = times\nself.maxperson = persons[[0]]\nself.maxvote = [1]\nself.rec = {persons[0]: 1}\nfor i in range(1, len(times)):\n if persons[i] in self.rec:\n self.rec[persons[i]] += 1\n else:\n self.rec[persons[i]] = 1\n if self.rec[persons[i]] >= self.maxvote[i - 1]:\n self.maxvot... | <|body_start_0|>
self.times = times
self.maxperson = persons[[0]]
self.maxvote = [1]
self.rec = {persons[0]: 1}
for i in range(1, len(times)):
if persons[i] in self.rec:
self.rec[persons[i]] += 1
else:
self.rec[persons[i]] =... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.times = times
self.maxpe... | stack_v2_sparse_classes_75kplus_train_003435 | 2,492 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015569 | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | f41348fd7da3b7af9f9b2df7c01457c7bed8ce0c | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.times = times
self.maxperson = persons[[0]]
self.maxvote = [1]
self.rec = {persons[0]: 1}
for i in range(1, len(times)):
if persons[i] i... | the_stack_v2_python_sparse | LeetCode/Array/Online Election.py | mrunalhirve12/Python_CTCI-practise | train | 3 | |
a514e6a22086c20949c71e6a4a2981ccf60fb5e1 | [
"def _pars(a, b):\n return '%.3f,%.3f' % (a, b)\nfit = continuous()\nxgrid = np.linspace(1, 40, 100)\ny_norm = norm.pdf(xgrid, *fit['norm'])\ny_lognorm = lognorm.pdf(xgrid, *fit['lognorm'])\ny_gamma = gamma.pdf(xgrid, *fit['gamma'])\nfig1, ax1 = plt.subplots()\nax1.hist(fit['x'], bins=15, alpha=0.6, density=True... | <|body_start_0|>
def _pars(a, b):
return '%.3f,%.3f' % (a, b)
fit = continuous()
xgrid = np.linspace(1, 40, 100)
y_norm = norm.pdf(xgrid, *fit['norm'])
y_lognorm = lognorm.pdf(xgrid, *fit['lognorm'])
y_gamma = gamma.pdf(xgrid, *fit['gamma'])
fig1, ax1 ... | Plotting of the module. | plot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class plot:
"""Plotting of the module."""
def continuous(save=False, name='img/parameters/symptoms.png'):
"""Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): Whether to save the figure, defaultly not. name (str, opt... | stack_v2_sparse_classes_75kplus_train_003436 | 5,322 | no_license | [
{
"docstring": "Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): Whether to save the figure, defaultly not. name (str, optional): Path to save the plot to.",
"name": "continuous",
"signature": "def continuous(save=False, name='im... | 2 | stack_v2_sparse_classes_30k_train_017181 | Implement the Python class `plot` described below.
Class description:
Plotting of the module.
Method signatures and docstrings:
- def continuous(save=False, name='img/parameters/symptoms.png'): Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): ... | Implement the Python class `plot` described below.
Class description:
Plotting of the module.
Method signatures and docstrings:
- def continuous(save=False, name='img/parameters/symptoms.png'): Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): ... | 3c79101a0e5e83dd24499e628e5c506137ce69c2 | <|skeleton|>
class plot:
"""Plotting of the module."""
def continuous(save=False, name='img/parameters/symptoms.png'):
"""Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): Whether to save the figure, defaultly not. name (str, opt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class plot:
"""Plotting of the module."""
def continuous(save=False, name='img/parameters/symptoms.png'):
"""Plot symptoms' duration fitted distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): Whether to save the figure, defaultly not. name (str, optional): Path ... | the_stack_v2_python_sparse | src/covid19/symptoms.py | martinbenes1996/732A64 | train | 0 |
17c54d2b8d229df93a1fa3253153560f0dbdb003 | [
"n = len(matrix[0])\nfor r in range(n // 2 + n % 2):\n for c in range(n // 2):\n temp = matrix[n - 1 - c][r]\n matrix[n - 1 - c][r] = matrix[n - 1 - r][n - 1 - c]\n matrix[n - 1 - r][n - 1 - c] = matrix[c][n - 1 - r]\n matrix[c][n - 1 - r] = matrix[r][c]\n matrix[r][c] = temp\n... | <|body_start_0|>
n = len(matrix[0])
for r in range(n // 2 + n % 2):
for c in range(n // 2):
temp = matrix[n - 1 - c][r]
matrix[n - 1 - c][r] = matrix[n - 1 - r][n - 1 - c]
matrix[n - 1 - r][n - 1 - c] = matrix[c][n - 1 - r]
matr... | TwoDArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoDArray:
def rotate__(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:"""
<|body_0|>
def rotate_(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: Four Rect... | stack_v2_sparse_classes_75kplus_train_003437 | 2,423 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:",
"name": "rotate__",
"signature": "def rotate__(self, matrix: List[List[int]]) -> List[List[int]]"
},
{
"docstring": "Approach: Four Rectangle Rotate Time Complexity: O(N^2) Space Complexit... | 3 | stack_v2_sparse_classes_30k_train_011582 | Implement the Python class `TwoDArray` described below.
Class description:
Implement the TwoDArray class.
Method signatures and docstrings:
- def rotate__(self, matrix: List[List[int]]) -> List[List[int]]: Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:
- def rotate_(self, ma... | Implement the Python class `TwoDArray` described below.
Class description:
Implement the TwoDArray class.
Method signatures and docstrings:
- def rotate__(self, matrix: List[List[int]]) -> List[List[int]]: Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:
- def rotate_(self, ma... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class TwoDArray:
def rotate__(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:"""
<|body_0|>
def rotate_(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: Four Rect... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwoDArray:
def rotate__(self, matrix: List[List[int]]) -> List[List[int]]:
"""Approach: One Pass Time Complexity: O(N^2) Space Complexity: O(1) :param matrix: :return:"""
n = len(matrix[0])
for r in range(n // 2 + n % 2):
for c in range(n // 2):
temp = matri... | the_stack_v2_python_sparse | revisited/2d_arrays/rotate_array.py | Shiv2157k/leet_code | train | 1 | |
e1898a1123c6fa4ffc59095abae4bbbb63cbf94b | [
"self.__terminal__ = terminal\nself.__badge__ = Badge(terminal.getDBName(), post)\nself.__post__ = post\nself.__chkinp__ = CheckInput()\nself.__badges__ = self.__badge__.getBadgeNames()",
"self.__terminal__.clear()\nself.__terminal__.printCenter('Add Badge to Post')\nself.__terminal__.printCenter('Adding a badge ... | <|body_start_0|>
self.__terminal__ = terminal
self.__badge__ = Badge(terminal.getDBName(), post)
self.__post__ = post
self.__chkinp__ = CheckInput()
self.__badges__ = self.__badge__.getBadgeNames()
<|end_body_0|>
<|body_start_1|>
self.__terminal__.clear()
self.__... | A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge | BadgeScreen | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BadgeScreen:
"""A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge"""
def __init__(self, terminal, post):
"""Creates an instance of BadgeScreen Parameters: terminal: A Terminal object which allows... | stack_v2_sparse_classes_75kplus_train_003438 | 2,094 | permissive | [
{
"docstring": "Creates an instance of BadgeScreen Parameters: terminal: A Terminal object which allows this module to interface with the OS terminal post: A PostQuery object which contains useful information about the post being given a badge",
"name": "__init__",
"signature": "def __init__(self, termi... | 4 | stack_v2_sparse_classes_30k_train_010260 | Implement the Python class `BadgeScreen` described below.
Class description:
A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge
Method signatures and docstrings:
- def __init__(self, terminal, post): Creates an instance of BadgeSc... | Implement the Python class `BadgeScreen` described below.
Class description:
A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge
Method signatures and docstrings:
- def __init__(self, terminal, post): Creates an instance of BadgeSc... | e56b3acf6867278613a2a05d1fbf453f909fa45b | <|skeleton|>
class BadgeScreen:
"""A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge"""
def __init__(self, terminal, post):
"""Creates an instance of BadgeScreen Parameters: terminal: A Terminal object which allows... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BadgeScreen:
"""A screen which handles giving badges to a post/user This module is responsible for providing the UI for providing a post/user with a badge"""
def __init__(self, terminal, post):
"""Creates an instance of BadgeScreen Parameters: terminal: A Terminal object which allows this module ... | the_stack_v2_python_sparse | BadgeScreen.py | CMPUT-291-Miniproject/MiniProject-1 | train | 0 |
410fc47194c7dba0541a731fa5695dbeeb26e717 | [
"log.info('Testing Hep B Definition A')\nmccoy = self.create_provider(last='McCoy', first='Leonard')\nkirk = self.create_patient(last='Kirk', first='James', pcp=mccoy)\ntrigger_date = datetime.date(year=2010, month=2, day=15)\nself.create_lab_result(provider=mccoy, patient=kirk, date=trigger_date, alt='hepatitis_b_... | <|body_start_0|>
log.info('Testing Hep B Definition A')
mccoy = self.create_provider(last='McCoy', first='Leonard')
kirk = self.create_patient(last='Kirk', first='James', pcp=mccoy)
trigger_date = datetime.date(year=2010, month=2, day=15)
self.create_lab_result(provider=mccoy, pa... | Unit tests for Hepatitis B algorithm | Hepatitis_B_Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hepatitis_B_Test:
"""Unit tests for Hepatitis B algorithm"""
def test_definition_a(self):
"""a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper limit of normal 3. Aspartate aminotransferase (AST) >5x ... | stack_v2_sparse_classes_75kplus_train_003439 | 17,028 | no_license | [
{
"docstring": "a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper limit of normal 3. Aspartate aminotransferase (AST) >5x upper limit of normal 4. IgM antibody to Hepatitis B Core Antigen = \"REACTIVE\" (may be truncated)",
... | 2 | null | Implement the Python class `Hepatitis_B_Test` described below.
Class description:
Unit tests for Hepatitis B algorithm
Method signatures and docstrings:
- def test_definition_a(self): a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper... | Implement the Python class `Hepatitis_B_Test` described below.
Class description:
Unit tests for Hepatitis B algorithm
Method signatures and docstrings:
- def test_definition_a(self): a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper... | 516e4c8d8d4bc5161dea499201d866e5a9153c7c | <|skeleton|>
class Hepatitis_B_Test:
"""Unit tests for Hepatitis B algorithm"""
def test_definition_a(self):
"""a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper limit of normal 3. Aspartate aminotransferase (AST) >5x ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hepatitis_B_Test:
"""Unit tests for Hepatitis B algorithm"""
def test_definition_a(self):
"""a) (#1 or #2 or #3) AND #4 within 14 day period 1. ICD9 = 782.4 (jaundice, not of newborn) 2. Alanine aminotransferase (ALT) >5x upper limit of normal 3. Aspartate aminotransferase (AST) >5x upper limit o... | the_stack_v2_python_sparse | modules/disease-hepatitis-combined/tests.py | jmcvetta/esphealth | train | 1 |
4298867787ccb5d9c00f3abf7dfd28ec035826ff | [
"if not root:\n return 0\nelse:\n depth = max(self.maxDepth(root.left), self.maxDepth(root.right))\n return depth + 1",
"if not root:\n return True\nelif abs(self.maxDepth(root.left) - self.maxDepth(root.right)) <= 1:\n return self.isBalanced(root.left) and self.isBalanced(root.right)\nelse:\n r... | <|body_start_0|>
if not root:
return 0
else:
depth = max(self.maxDepth(root.left), self.maxDepth(root.right))
return depth + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return True
elif abs(self.maxDepth(root.left) - self.maxDepth(root.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
else:
... | stack_v2_sparse_classes_75kplus_train_003440 | 894 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isBalanced",
"signature": "def isBalanced(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_032661 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def isBalanced(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def isBalanced(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def maxDepth(self, r... | 86ba4a1ef1e41cbcbb0f6566a0a1e6a079ed6c02 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def isBalanced(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
else:
depth = max(self.maxDepth(root.left), self.maxDepth(root.right))
return depth + 1
def isBalanced(self, root):
""":type root: TreeNode ... | the_stack_v2_python_sparse | 110. Balanced_Binary_Tree.py | byrony/LeetCode | train | 6 | |
9bbba9581541bc3cb2a818c59d6cb78a67a09624 | [
"super(StreamPublisher, self).__init__()\nvalidate_is_instance(process, BaseService, 'No valid process provided.')\nself.stream_id = stream_id\nif stream_id:\n pubsub_cli = PubsubManagementServiceProcessClient(process=process, node=process.container.node)\n self.stream_route = pubsub_cli.read_stream_route(str... | <|body_start_0|>
super(StreamPublisher, self).__init__()
validate_is_instance(process, BaseService, 'No valid process provided.')
self.stream_id = stream_id
if stream_id:
pubsub_cli = PubsubManagementServiceProcessClient(process=process, node=process.container.node)
... | Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process. | StreamPublisher | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamPublisher:
"""Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process."""
def __init__(self, process=None, stream_id='', stream_route=None, exchange_point='', routing_... | stack_v2_sparse_classes_75kplus_train_003441 | 9,991 | permissive | [
{
"docstring": "Creates a StreamPublisher which publishes to the specified stream by default and is attached to the specified process. @param process The process which the subscriber is to be attached. @param stream_id Stream identifier for the publishing stream. @param stream_route A StreamRoute corresponding ... | 2 | stack_v2_sparse_classes_30k_test_001049 | Implement the Python class `StreamPublisher` described below.
Class description:
Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process.
Method signatures and docstrings:
- def __init__(self, proces... | Implement the Python class `StreamPublisher` described below.
Class description:
Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process.
Method signatures and docstrings:
- def __init__(self, proces... | 122c629290d27f32f2f41dafd5c12469295e8acf | <|skeleton|>
class StreamPublisher:
"""Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process."""
def __init__(self, process=None, stream_id='', stream_route=None, exchange_point='', routing_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StreamPublisher:
"""Stream Publisher maintains the "stream" concept and properly encapsulates outgoing messages in the streaming packet. Stream Publisher is intended to be used in an Ion Process."""
def __init__(self, process=None, stream_id='', stream_route=None, exchange_point='', routing_key=''):
... | the_stack_v2_python_sparse | pyon/ion/stream.py | ooici/pyon | train | 9 |
d3c505caf4248d14bd1aef1f56fed75e00188431 | [
"self.root = root\nself._verify()\nsuper().__init__(root, crs, res, transforms=transforms, cache=cache)",
"pathname = os.path.join(self.root, self.filename_glob)\nif glob.glob(pathname):\n return\nraise RuntimeError(f'Dataset not found in `root={self.root}` either specify a different `root` directory or make s... | <|body_start_0|>
self.root = root
self._verify()
super().__init__(root, crs, res, transforms=transforms, cache=cache)
<|end_body_0|>
<|body_start_1|>
pathname = os.path.join(self.root, self.filename_glob)
if glob.glob(pathname):
return
raise RuntimeError(f'Da... | Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth Data website <https://search.earthdata.nasa.gov/search/>`_ after making an ... | AsterGDEM | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsterGDEM:
"""Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth Data website <https://search.earthdata... | stack_v2_sparse_classes_75kplus_train_003442 | 4,290 | permissive | [
{
"docstring": "Initialize a new Dataset instance. Args: root: root directory where dataset can be found, here the collection of individual zip files for each tile should be found crs: :term:`coordinate reference system (CRS)` to warp to (defaults to the CRS of the first file found) res: resolution of the datas... | 3 | stack_v2_sparse_classes_30k_train_047018 | Implement the Python class `AsterGDEM` described below.
Class description:
Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth... | Implement the Python class `AsterGDEM` described below.
Class description:
Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth... | 29985861614b3b93f9ef5389469ebb98570de7dd | <|skeleton|>
class AsterGDEM:
"""Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth Data website <https://search.earthdata... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AsterGDEM:
"""Aster Global Digital Elevation Model Dataset. The `Aster Global Digital Elevation Model <https://lpdaac.usgs.gov/products/astgtmv003/>`_ dataset is a Digital Elevation Model (DEM) on a global scale. The dataset can be downloaded from the `Earth Data website <https://search.earthdata.nasa.gov/sea... | the_stack_v2_python_sparse | torchgeo/datasets/astergdem.py | microsoft/torchgeo | train | 1,724 |
d63ff4e28ee32cc506079ef3cb0039a75d68bec9 | [
"self.interface_name = interface_name\nself.ip_family = ip_family\nself.node_ids = node_ids",
"if dictionary is None:\n return None\ninterface_name = dictionary.get('interfaceName')\nip_family = dictionary.get('ipFamily')\nnode_ids = dictionary.get('nodeIds')\nreturn cls(interface_name, ip_family, node_ids)"
] | <|body_start_0|>
self.interface_name = interface_name
self.ip_family = ip_family
self.node_ids = node_ids
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
interface_name = dictionary.get('interfaceName')
ip_family = dictionary.get('ipFamily'... | Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids. | IpUnconfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IpUnconfig:
"""Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids."""
def __init__(self, interface_name=None, ip_family=None... | stack_v2_sparse_classes_75kplus_train_003443 | 1,764 | permissive | [
{
"docstring": "Constructor for the IpUnconfig class",
"name": "__init__",
"signature": "def __init__(self, interface_name=None, ip_family=None, node_ids=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of th... | 2 | null | Implement the Python class `IpUnconfig` described below.
Class description:
Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids.
Method signatures and ... | Implement the Python class `IpUnconfig` described below.
Class description:
Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids.
Method signatures and ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IpUnconfig:
"""Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids."""
def __init__(self, interface_name=None, ip_family=None... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IpUnconfig:
"""Implementation of the 'IpUnconfig' model. Specifies the unconfiguration of an IP. Attributes: interface_name (string): The interface name. ip_family (int): IpFamily of this config. node_ids (list of long|int): Node ids."""
def __init__(self, interface_name=None, ip_family=None, node_ids=No... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ip_unconfig.py | cohesity/management-sdk-python | train | 24 |
b290518c1c9a6d302932203c9e6f3da710ac5546 | [
"cas_value = 'None'\ncompound_name = re.sub('\\\\_\\\\w{1}0$', '', compound_name)\ncompound_name = re.sub('_', ' ', compound_name)\nself.get_inchi(compound_name)\nif len(self.IDs) == 0:\n compound_name = re.sub(' ', '-', compound_name)\n self.get_inchi(compound_name)\nif len(self.IDs) == 0:\n compound_name... | <|body_start_0|>
cas_value = 'None'
compound_name = re.sub('\\_\\w{1}0$', '', compound_name)
compound_name = re.sub('_', ' ', compound_name)
self.get_inchi(compound_name)
if len(self.IDs) == 0:
compound_name = re.sub(' ', '-', compound_name)
self.get_inchi... | Converts compound IDs to their InChi | CompoundTranslator | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CompoundTranslator:
"""Converts compound IDs to their InChi"""
def translate(self, compound_name):
"""Retrieve InChi's for compounds"""
<|body_0|>
def get_inchi(self, compound_name):
"""Attempt to get inchi for a compound"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_003444 | 1,699 | permissive | [
{
"docstring": "Retrieve InChi's for compounds",
"name": "translate",
"signature": "def translate(self, compound_name)"
},
{
"docstring": "Attempt to get inchi for a compound",
"name": "get_inchi",
"signature": "def get_inchi(self, compound_name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037703 | Implement the Python class `CompoundTranslator` described below.
Class description:
Converts compound IDs to their InChi
Method signatures and docstrings:
- def translate(self, compound_name): Retrieve InChi's for compounds
- def get_inchi(self, compound_name): Attempt to get inchi for a compound | Implement the Python class `CompoundTranslator` described below.
Class description:
Converts compound IDs to their InChi
Method signatures and docstrings:
- def translate(self, compound_name): Retrieve InChi's for compounds
- def get_inchi(self, compound_name): Attempt to get inchi for a compound
<|skeleton|>
class ... | 89cd62221959fd2dc2952c30de6ecbe2d511479a | <|skeleton|>
class CompoundTranslator:
"""Converts compound IDs to their InChi"""
def translate(self, compound_name):
"""Retrieve InChi's for compounds"""
<|body_0|>
def get_inchi(self, compound_name):
"""Attempt to get inchi for a compound"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CompoundTranslator:
"""Converts compound IDs to their InChi"""
def translate(self, compound_name):
"""Retrieve InChi's for compounds"""
cas_value = 'None'
compound_name = re.sub('\\_\\w{1}0$', '', compound_name)
compound_name = re.sub('_', ' ', compound_name)
self.... | the_stack_v2_python_sparse | rs/Pubchem/pubchem_inchi_translator.py | sandialabs/RetSynth | train | 4 |
2a4548b175ee3a42d29be97847c07a780669b96c | [
"self.basepath = basepath\nself.available_distributions = collections.defaultdict(list)\nself.available_architectures = collections.defaultdict(list)\nif not self.basepath or not os.path.isdir(self.basepath):\n log('sysroots are not available on this system\\n')\n return\nsysroots = os.listdir(self.basepath)\... | <|body_start_0|>
self.basepath = basepath
self.available_distributions = collections.defaultdict(list)
self.available_architectures = collections.defaultdict(list)
if not self.basepath or not os.path.isdir(self.basepath):
log('sysroots are not available on this system\n')
... | Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicates whether or not there are any available sysroots - available_distributio... | Sysroot | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sysroot:
"""Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicates whether or not there are any availab... | stack_v2_sparse_classes_75kplus_train_003445 | 33,624 | permissive | [
{
"docstring": "Scan the configured sysroot base folder for available sysroots and initialize available distribution and architecture maps.",
"name": "__init__",
"signature": "def __init__(self, basepath)"
},
{
"docstring": "Return a path to the requested distribution and architecture sysroot. R... | 3 | stack_v2_sparse_classes_30k_train_038017 | Implement the Python class `Sysroot` described below.
Class description:
Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicat... | Implement the Python class `Sysroot` described below.
Class description:
Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicat... | 84e319101d4a1200657337dcdf9ed3857fc59e03 | <|skeleton|>
class Sysroot:
"""Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicates whether or not there are any availab... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sysroot:
"""Utilities for sysroots. Public API: properties: - NotFoundError: exception class used for raising exceptions in this utility class - argparse_help: a string for arparse argument help generated based on availablity of sysroots - available: indicates whether or not there are any available sysroots -... | the_stack_v2_python_sparse | chromium/src/build/infra/utilities.py | bopopescu/ofa | train | 0 |
45fd979c1c67288958ca14a0b5be7f2a81dfbcce | [
"chat_id = self.env.context.get('active_id', False)\nding_chat = self.env['dingding.chat'].browse(chat_id)\nurl = self.env['ali.dindin.system.conf'].search([('key', '=', 'chat_send')]).value\ntoken = self.env['ali.dindin.system.conf'].search([('key', '=', 'token')]).value\ndata = {'chatid': ding_chat.chat_id, 'msg'... | <|body_start_0|>
chat_id = self.env.context.get('active_id', False)
ding_chat = self.env['dingding.chat'].browse(chat_id)
url = self.env['ali.dindin.system.conf'].search([('key', '=', 'chat_send')]).value
token = self.env['ali.dindin.system.conf'].search([('key', '=', 'token')]).value
... | DingDingSendChatMessage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DingDingSendChatMessage:
def send_dingding_test_message(self):
"""点击群会话发送群消息按钮 :return:"""
<|body_0|>
def send_message(self, ding_chat, body):
"""发送群会话消息 :return:"""
<|body_1|>
def send_work_message(self, userstr, message):
"""发送工作消息到指定员工列表 :para... | stack_v2_sparse_classes_75kplus_train_003446 | 22,701 | permissive | [
{
"docstring": "点击群会话发送群消息按钮 :return:",
"name": "send_dingding_test_message",
"signature": "def send_dingding_test_message(self)"
},
{
"docstring": "发送群会话消息 :return:",
"name": "send_message",
"signature": "def send_message(self, ding_chat, body)"
},
{
"docstring": "发送工作消息到指定员工列表 ... | 3 | stack_v2_sparse_classes_30k_train_049226 | Implement the Python class `DingDingSendChatMessage` described below.
Class description:
Implement the DingDingSendChatMessage class.
Method signatures and docstrings:
- def send_dingding_test_message(self): 点击群会话发送群消息按钮 :return:
- def send_message(self, ding_chat, body): 发送群会话消息 :return:
- def send_work_message(self... | Implement the Python class `DingDingSendChatMessage` described below.
Class description:
Implement the DingDingSendChatMessage class.
Method signatures and docstrings:
- def send_dingding_test_message(self): 点击群会话发送群消息按钮 :return:
- def send_message(self, ding_chat, body): 发送群会话消息 :return:
- def send_work_message(self... | deaf38151d022a621096e84c8495b1a51265a991 | <|skeleton|>
class DingDingSendChatMessage:
def send_dingding_test_message(self):
"""点击群会话发送群消息按钮 :return:"""
<|body_0|>
def send_message(self, ding_chat, body):
"""发送群会话消息 :return:"""
<|body_1|>
def send_work_message(self, userstr, message):
"""发送工作消息到指定员工列表 :para... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DingDingSendChatMessage:
def send_dingding_test_message(self):
"""点击群会话发送群消息按钮 :return:"""
chat_id = self.env.context.get('active_id', False)
ding_chat = self.env['dingding.chat'].browse(chat_id)
url = self.env['ali.dindin.system.conf'].search([('key', '=', 'chat_send')]).value... | the_stack_v2_python_sparse | dindin_message/models/dingding_chat.py | 007gzs/odooDingDing | train | 2 | |
e0a88edc742408be66c534e5ac106a4d0e723017 | [
"if k <= 0:\n raise ValueError('k应该大于0.')\nnodeK = phead = head.next\ni = 1\nwhile nodeK and i < k:\n nodeK, i = (nodeK.next, i + 1)\nif i < k or not nodeK:\n raise ValueError('链表节点数小于k.')\nwhile nodeK.next:\n phead, nodeK = (phead.next, nodeK.next)\nreturn phead",
"odd = even = head\nwhile even:\n ... | <|body_start_0|>
if k <= 0:
raise ValueError('k应该大于0.')
nodeK = phead = head.next
i = 1
while nodeK and i < k:
nodeK, i = (nodeK.next, i + 1)
if i < k or not nodeK:
raise ValueError('链表节点数小于k.')
while nodeK.next:
phead, node... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def theLastKNode(self, head, k):
""":type head:ListNode :type k:int :rtype:ListNode"""
<|body_0|>
def theMiddleNode1(self, head):
""":type head:ListNode :rtype:ListNode"""
<|body_1|>
def theMiddleNode2(self, head):
""":type head:ListNod... | stack_v2_sparse_classes_75kplus_train_003447 | 1,407 | no_license | [
{
"docstring": ":type head:ListNode :type k:int :rtype:ListNode",
"name": "theLastKNode",
"signature": "def theLastKNode(self, head, k)"
},
{
"docstring": ":type head:ListNode :rtype:ListNode",
"name": "theMiddleNode1",
"signature": "def theMiddleNode1(self, head)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_038109 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def theLastKNode(self, head, k): :type head:ListNode :type k:int :rtype:ListNode
- def theMiddleNode1(self, head): :type head:ListNode :rtype:ListNode
- def theMiddleNode2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def theLastKNode(self, head, k): :type head:ListNode :type k:int :rtype:ListNode
- def theMiddleNode1(self, head): :type head:ListNode :rtype:ListNode
- def theMiddleNode2(self, ... | 42a15943394ae533dcd0d5bbf52e4366ab0756ab | <|skeleton|>
class Solution:
def theLastKNode(self, head, k):
""":type head:ListNode :type k:int :rtype:ListNode"""
<|body_0|>
def theMiddleNode1(self, head):
""":type head:ListNode :rtype:ListNode"""
<|body_1|>
def theMiddleNode2(self, head):
""":type head:ListNod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def theLastKNode(self, head, k):
""":type head:ListNode :type k:int :rtype:ListNode"""
if k <= 0:
raise ValueError('k应该大于0.')
nodeK = phead = head.next
i = 1
while nodeK and i < k:
nodeK, i = (nodeK.next, i + 1)
if i < k or not ... | the_stack_v2_python_sparse | test22.py | nihao-hit/jianzhiOffer | train | 0 | |
98873d5345d3d53bc5c66ba402ff2eda49787fb5 | [
"self.v2d = vec2d\nself.i = 0\nself.j = 0",
"if self.hasNext():\n tmp = self.v2d[self.i][self.j]\n self.j += 1\n return tmp\nreturn -1",
"while self.i < len(self.v2d) and self.j == len(self.v2d[self.i]):\n self.i += 1\n self.j = 0\nreturn self.i < len(self.v2d)"
] | <|body_start_0|>
self.v2d = vec2d
self.i = 0
self.j = 0
<|end_body_0|>
<|body_start_1|>
if self.hasNext():
tmp = self.v2d[self.i][self.j]
self.j += 1
return tmp
return -1
<|end_body_1|>
<|body_start_2|>
while self.i < len(self.v2d) an... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_003448 | 833 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | stack_v2_sparse_classes_30k_train_034667 | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 832f6a8c0deb0569d3fe0dc03e4564c2d850f067 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.v2d = vec2d
self.i = 0
self.j = 0
def next(self):
""":rtype: int"""
if self.hasNext():
tmp = self.v2d[self.i][self.j]
s... | the_stack_v2_python_sparse | leetcode/251_flattenedl2dvector.py | hwillmott/csfundamentals | train | 0 | |
640a387a08a022c98fdb7b8b5ae6a1f0e44d4ced | [
"if root is None:\n return 0\nreturn 1 + max(self.getHeight(root.left), self.getHeight(root.right))",
"if root is None:\n return 0\nlheight = self.getHeight(root.left)\nrheight = self.getHeight(root.right)\nldiameter = self.diameterOfBinaryTree(root.left)\nrdiameter = self.diameterOfBinaryTree(root.right)\n... | <|body_start_0|>
if root is None:
return 0
return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
<|end_body_0|>
<|body_start_1|>
if root is None:
return 0
lheight = self.getHeight(root.left)
rheight = self.getHeight(root.right)
ldi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getHeight(self, root):
""":type root : TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if root is None:
return 0
... | stack_v2_sparse_classes_75kplus_train_003449 | 1,124 | no_license | [
{
"docstring": ":type root : TreeNode :rtype: int",
"name": "getHeight",
"signature": "def getHeight(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "diameterOfBinaryTree",
"signature": "def diameterOfBinaryTree(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027366 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getHeight(self, root): :type root : TreeNode :rtype: int
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getHeight(self, root): :type root : TreeNode :rtype: int
- def diameterOfBinaryTree(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def getHe... | 9752533bc76ce5ecb881f61e33a3bc4b20dcf666 | <|skeleton|>
class Solution:
def getHeight(self, root):
""":type root : TreeNode :rtype: int"""
<|body_0|>
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def getHeight(self, root):
""":type root : TreeNode :rtype: int"""
if root is None:
return 0
return 1 + max(self.getHeight(root.left), self.getHeight(root.right))
def diameterOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int"""
if ... | the_stack_v2_python_sparse | 543. Diameter of Binary Tree/543. Diameter of Binary Tree.py | 603lzy/LeetCode | train | 3 | |
ec2e87e055675cf26e17f8200c9f425fec1eadab | [
"data = parameter_required(('user_name', 'user_password'))\nuser = an_user.query.filter(an_user.isdelete == '0', an_user.user_name == data.get('user_name')).first_('未找到该账号或该账号被禁用')\nhash_password = hashlib.md5(data.get('user_password').encode('utf-8'))\nif user and hash_password.hexdigest() == user.user_password:\n... | <|body_start_0|>
data = parameter_required(('user_name', 'user_password'))
user = an_user.query.filter(an_user.isdelete == '0', an_user.user_name == data.get('user_name')).first_('未找到该账号或该账号被禁用')
hash_password = hashlib.md5(data.get('user_password').encode('utf-8'))
if user and hash_pass... | CUser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CUser:
def user_login(self):
"""用户登录"""
<|body_0|>
def user_password_repeat(self):
"""用户修改密码"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data = parameter_required(('user_name', 'user_password'))
user = an_user.query.filter(an_user.isdele... | stack_v2_sparse_classes_75kplus_train_003450 | 2,568 | permissive | [
{
"docstring": "用户登录",
"name": "user_login",
"signature": "def user_login(self)"
},
{
"docstring": "用户修改密码",
"name": "user_password_repeat",
"signature": "def user_password_repeat(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033033 | Implement the Python class `CUser` described below.
Class description:
Implement the CUser class.
Method signatures and docstrings:
- def user_login(self): 用户登录
- def user_password_repeat(self): 用户修改密码 | Implement the Python class `CUser` described below.
Class description:
Implement the CUser class.
Method signatures and docstrings:
- def user_login(self): 用户登录
- def user_password_repeat(self): 用户修改密码
<|skeleton|>
class CUser:
def user_login(self):
"""用户登录"""
<|body_0|>
def user_password_r... | 37a9b0d6e7a3f110ba9285a3715fec2e30bdd7d2 | <|skeleton|>
class CUser:
def user_login(self):
"""用户登录"""
<|body_0|>
def user_password_repeat(self):
"""用户修改密码"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CUser:
def user_login(self):
"""用户登录"""
data = parameter_required(('user_name', 'user_password'))
user = an_user.query.filter(an_user.isdelete == '0', an_user.user_name == data.get('user_name')).first_('未找到该账号或该账号被禁用')
hash_password = hashlib.md5(data.get('user_password').encod... | the_stack_v2_python_sparse | FanstiBgs/control/CUser.py | haobin12358/FanstiBgs | train | 0 | |
fe6a2e4d36e311d1a8627acded0608832c6e7c6f | [
"env = gym.make(env_info['name'])\ngym.Wrapper.__init__(self, env)\nself.action_type = infer_action_type(self.action_space)\nself.vision = env_info.get('vision', False)\nself.init_state = None\nreturn env",
"if self.vision:\n self.env.close()\n time.sleep(0.05)\nstate = self.env.reset()\nself.init_state = s... | <|body_start_0|>
env = gym.make(env_info['name'])
gym.Wrapper.__init__(self, env)
self.action_type = infer_action_type(self.action_space)
self.vision = env_info.get('vision', False)
self.init_state = None
return env
<|end_body_0|>
<|body_start_1|>
if self.vision:... | Encapsulate an openai gym environment. | GymEnv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GymEnv:
"""Encapsulate an openai gym environment."""
def init_env(self, env_info):
"""Create a gym environment instance. :param: the config information of environment :return: the instance of environment"""
<|body_0|>
def reset(self):
"""Reset the environment, if... | stack_v2_sparse_classes_75kplus_train_003451 | 3,035 | permissive | [
{
"docstring": "Create a gym environment instance. :param: the config information of environment :return: the instance of environment",
"name": "init_env",
"signature": "def init_env(self, env_info)"
},
{
"docstring": "Reset the environment, if visionis true, must close environment first. :retur... | 3 | null | Implement the Python class `GymEnv` described below.
Class description:
Encapsulate an openai gym environment.
Method signatures and docstrings:
- def init_env(self, env_info): Create a gym environment instance. :param: the config information of environment :return: the instance of environment
- def reset(self): Rese... | Implement the Python class `GymEnv` described below.
Class description:
Encapsulate an openai gym environment.
Method signatures and docstrings:
- def init_env(self, env_info): Create a gym environment instance. :param: the config information of environment :return: the instance of environment
- def reset(self): Rese... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class GymEnv:
"""Encapsulate an openai gym environment."""
def init_env(self, env_info):
"""Create a gym environment instance. :param: the config information of environment :return: the instance of environment"""
<|body_0|>
def reset(self):
"""Reset the environment, if... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GymEnv:
"""Encapsulate an openai gym environment."""
def init_env(self, env_info):
"""Create a gym environment instance. :param: the config information of environment :return: the instance of environment"""
env = gym.make(env_info['name'])
gym.Wrapper.__init__(self, env)
s... | the_stack_v2_python_sparse | xt/environment/gym/gym_env.py | huawei-noah/xingtian | train | 308 |
b2f145986f3915f09f9d2f0f0a72ca11727c235e | [
"if isinstance(env.action_space, gym.spaces.Box):\n raise NotImplementedError('Continous actions not implemented!')\nself.obs_dim, self.act_dim = (env.observation_space.shape[0], env.action_space.n)\nself.env = env\nself.memory = TransitionMemory(gamma)\nself.episodes_update = episodes_update\nself.actor_net = A... | <|body_start_0|>
if isinstance(env.action_space, gym.spaces.Box):
raise NotImplementedError('Continous actions not implemented!')
self.obs_dim, self.act_dim = (env.observation_space.shape[0], env.action_space.n)
self.env = env
self.memory = TransitionMemory(gamma)
sel... | The vanilla policy gradient (VPG) approach. | VPG | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VPG:
"""The vanilla policy gradient (VPG) approach."""
def __init__(self, env, episodes_update=5, gamma=0.99, lr=0.01):
"""Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent should be trained in. episodes_update : int Number episodes ... | stack_v2_sparse_classes_75kplus_train_003452 | 7,087 | no_license | [
{
"docstring": "Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent should be trained in. episodes_update : int Number episodes to collect for every optimization step. gamma : float, optional Discount factor. lr : float, optional Learning rate used for actor and ... | 4 | stack_v2_sparse_classes_30k_train_010794 | Implement the Python class `VPG` described below.
Class description:
The vanilla policy gradient (VPG) approach.
Method signatures and docstrings:
- def __init__(self, env, episodes_update=5, gamma=0.99, lr=0.01): Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent sho... | Implement the Python class `VPG` described below.
Class description:
The vanilla policy gradient (VPG) approach.
Method signatures and docstrings:
- def __init__(self, env, episodes_update=5, gamma=0.99, lr=0.01): Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent sho... | e17f6b91d04a3465bafa3239ca5baacdb07e59f7 | <|skeleton|>
class VPG:
"""The vanilla policy gradient (VPG) approach."""
def __init__(self, env, episodes_update=5, gamma=0.99, lr=0.01):
"""Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent should be trained in. episodes_update : int Number episodes ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VPG:
"""The vanilla policy gradient (VPG) approach."""
def __init__(self, env, episodes_update=5, gamma=0.99, lr=0.01):
"""Constructor. Parameters ---------- env : gym.Environment The object of the gym environment the agent should be trained in. episodes_update : int Number episodes to collect fo... | the_stack_v2_python_sparse | Vanilla Policy Gradient/vpg.py | StefanFischer/Reinforcement-Learning | train | 0 |
a9effcece3f7f39023ef30c09776734e83b61200 | [
"self.name = 'ext_schedule'\nassert start > 0\nassert end > start\nself.start = start\nself.end = end\nself.decay_factor = decay_factor\nself.count = 0",
"if self.count == 0:\n self.base_lr = mainloop.optimizer.lr.get_value()\n self.step = (self.base_lr - self.base_lr * self.decay_factor) / (self.end - self... | <|body_start_0|>
self.name = 'ext_schedule'
assert start > 0
assert end > start
self.start = start
self.end = end
self.decay_factor = decay_factor
self.count = 0
<|end_body_0|>
<|body_start_1|>
if self.count == 0:
self.base_lr = mainloop.optim... | LrLinearDecay | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LrLinearDecay:
def __init__(self, start, end, decay_factor):
""".. todo:: WRITEME"""
<|body_0|>
def exe(self, mainloop):
""".. todo:: WRITEME"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.name = 'ext_schedule'
assert start > 0
... | stack_v2_sparse_classes_75kplus_train_003453 | 19,556 | no_license | [
{
"docstring": ".. todo:: WRITEME",
"name": "__init__",
"signature": "def __init__(self, start, end, decay_factor)"
},
{
"docstring": ".. todo:: WRITEME",
"name": "exe",
"signature": "def exe(self, mainloop)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009381 | Implement the Python class `LrLinearDecay` described below.
Class description:
Implement the LrLinearDecay class.
Method signatures and docstrings:
- def __init__(self, start, end, decay_factor): .. todo:: WRITEME
- def exe(self, mainloop): .. todo:: WRITEME | Implement the Python class `LrLinearDecay` described below.
Class description:
Implement the LrLinearDecay class.
Method signatures and docstrings:
- def __init__(self, start, end, decay_factor): .. todo:: WRITEME
- def exe(self, mainloop): .. todo:: WRITEME
<|skeleton|>
class LrLinearDecay:
def __init__(self, ... | d4bc620278f3a4ce33521f23c6632ab512a38de9 | <|skeleton|>
class LrLinearDecay:
def __init__(self, start, end, decay_factor):
""".. todo:: WRITEME"""
<|body_0|>
def exe(self, mainloop):
""".. todo:: WRITEME"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LrLinearDecay:
def __init__(self, start, end, decay_factor):
""".. todo:: WRITEME"""
self.name = 'ext_schedule'
assert start > 0
assert end > start
self.start = start
self.end = end
self.decay_factor = decay_factor
self.count = 0
def exe(sel... | the_stack_v2_python_sparse | auxiliar-libraries/cle/cle/train/ext.py | oneway3124/disaggregation-vrnn | train | 0 | |
ab47bcf72d92a43b1ce1af9d0085753f18a21b55 | [
"lo, hi = (0, len(nums) - 1)\nwhile lo <= hi:\n mid = (lo + hi) // 2\n if nums[mid] == target:\n return mid\n if (nums[0] > nums[mid]) ^ (nums[0] > target) ^ (target > nums[mid]):\n lo = mid + 1\n else:\n hi = mid - 1\nreturn -1",
"lo, hi = (0, len(nums))\nwhile lo < hi:\n mid ... | <|body_start_0|>
lo, hi = (0, len(nums) - 1)
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if (nums[0] > nums[mid]) ^ (nums[0] > target) ^ (target > nums[mid]):
lo = mid + 1
else:
hi... | Solution | [
"MIT"
] | 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 search_pre2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def search_pre1(self, nums, target):
... | stack_v2_sparse_classes_75kplus_train_003454 | 1,817 | permissive | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search_pre2",
"signature": "def search_pre2(self, nums, target)"
},
... | 3 | stack_v2_sparse_classes_30k_train_016495 | 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 search_pre2(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- d... | 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 search_pre2(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- d... | cb70ca87aa4604d1aec83d4224b3489eacebba75 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_pre2(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def search_pre1(self, nums, target):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
lo, hi = (0, len(nums) - 1)
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if (nums[0] > nums[mid]) ^ (nums[0... | the_stack_v2_python_sparse | LeetCode/Python3/0033._Search_in_Rotated_Sorted_Array.py | icgw/practice | train | 1 | |
43bc742e88650eb5c8cbe3c29336985cf2a8c8c7 | [
"super(ChamferkNNDist, self).__init__()\nself.chamfer_dist = ChamferDist(method=chamfer_method)\nself.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)\nself.w1 = chamfer_weight\nself.w2 = knn_weight",
"chamfer_loss = self.chamfer_dist(adv_pc, ori_pc, weights=weights, batch_avg=batch_avg)\nknn_loss = self.knn_dist(adv... | <|body_start_0|>
super(ChamferkNNDist, self).__init__()
self.chamfer_dist = ChamferDist(method=chamfer_method)
self.knn_dist = KNNDist(k=knn_k, alpha=knn_alpha)
self.w1 = chamfer_weight
self.w2 = knn_weight
<|end_body_0|>
<|body_start_1|>
chamfer_loss = self.chamfer_dist... | ChamferkNNDist | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_75kplus_train_003455 | 11,583 | permissive | [
{
"docstring": "Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alpha (float, optional): alpha in kNN. Defaults to 1.1. chamfer_weight (float, optional): weight factor. Defaults to 5.. kn... | 2 | stack_v2_sparse_classes_30k_train_003426 | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | Implement the Python class `ChamferkNNDist` described below.
Class description:
Implement the ChamferkNNDist class.
Method signatures and docstrings:
- def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0): Geometry-aware distance function of AAAI'20 paper. Args: ch... | 4e2462b66fa1eac90cfbf61fa0dc635d223fdf2f | <|skeleton|>
class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChamferkNNDist:
def __init__(self, chamfer_method='adv2ori', knn_k=5, knn_alpha=1.05, chamfer_weight=5.0, knn_weight=3.0):
"""Geometry-aware distance function of AAAI'20 paper. Args: chamfer_method (str, optional): chamfer. Defaults to 'adv2ori'. knn_k (int, optional): k in kNN. Defaults to 5. knn_alp... | the_stack_v2_python_sparse | baselines/attack/util/dist_utils.py | code-roamer/IF-Defense | train | 0 | |
2a06cf1341322e2c8efa87523974debe7f763dd1 | [
"ans = 0\nn = len(s)\n\ndef count(l, r):\n cnt = 0\n while l >= 0 and r < n and (s[l] == s[r]):\n cnt += 1\n l -= 1\n r += 1\n return cnt\nfor i in range(n):\n ans += count(i, i)\n ans += count(i - 1, i)\nreturn ans",
"n, res = (len(s), 0)\ndp = [[False for _ in range(n)] for _... | <|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
for i in range(n):
ans += count(i, i)
ans... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
... | stack_v2_sparse_classes_75kplus_train_003456 | 1,573 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstringsDP",
"signature": "def countSubstringsDP(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051880 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def countSubstrings(self, s):... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
... | the_stack_v2_python_sparse | P/PalindromicSubstrings.py | bssrdf/pyleet | train | 2 | |
dea7b5885ac65ffb89d924b6b4bfd65219e40e22 | [
"super().__init__()\nself.bn1 = BatchNorm2d(num_features=n_in_channels)\nself.conv1 = Conv2d(in_channels=n_in_channels, out_channels=n_out_channels, kernel_size=(1, 1), stride=(1, 1), bias=False)\nself.bn2 = BatchNorm2d(num_features=n_out_channels)\nself.conv2 = Conv2d(in_channels=n_out_channels, out_channels=n_out... | <|body_start_0|>
super().__init__()
self.bn1 = BatchNorm2d(num_features=n_in_channels)
self.conv1 = Conv2d(in_channels=n_in_channels, out_channels=n_out_channels, kernel_size=(1, 1), stride=(1, 1), bias=False)
self.bn2 = BatchNorm2d(num_features=n_out_channels)
self.conv2 = Conv2... | Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027). | BottleneckBlockV2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BottleneckBlockV2:
"""Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in... | stack_v2_sparse_classes_75kplus_train_003457 | 18,521 | no_license | [
{
"docstring": "Init :param n_in_channels: number of channels in the inputs passed to the `forward` method :type n_in_channels: int :param n_out_channels: number of output channels (convolutional filters) to use in the convolutions applied to the inputs passed to the `forward` method :type n_out_channels: int",... | 2 | stack_v2_sparse_classes_30k_train_035627 | Implement the Python class `BottleneckBlockV2` described below.
Class description:
Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027).
Method signatures and docstrings:
- def __init__(self, n_in_channels, n_out_ch... | Implement the Python class `BottleneckBlockV2` described below.
Class description:
Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027).
Method signatures and docstrings:
- def __init__(self, n_in_channels, n_out_ch... | e05b2a15dd2925fca5206c2509e1da29c1806834 | <|skeleton|>
class BottleneckBlockV2:
"""Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BottleneckBlockV2:
"""Bottleneck Residual Block As implemented in 'Identity Mappings in Deep Residual Networks', often referred to as ResNetV2 (https://arxiv.org/abs/1603.05027)."""
def __init__(self, n_in_channels, n_out_channels):
"""Init :param n_in_channels: number of channels in the inputs p... | the_stack_v2_python_sparse | dl_playground/networks/pytorch/object_classification/resnet.py | sallamander/dl-playground | train | 5 |
1bbecd0812b097516c66d62a2f2e859eb7fd5366 | [
"auth_serializer = self.serializer_class(data=request.data)\nauth_serializer.is_valid(raise_exception=True)\nclient = request.client\nremember_me = bool(request.data.get('remember_me', False))\nid = auth_serializer.validated_data['user'].pk\nreturn self.response_login(id=id, client=client, remember_me=remember_me)"... | <|body_start_0|>
auth_serializer = self.serializer_class(data=request.data)
auth_serializer.is_valid(raise_exception=True)
client = request.client
remember_me = bool(request.data.get('remember_me', False))
id = auth_serializer.validated_data['user'].pk
return self.respons... | AuthViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthViewSet:
def create(self, request):
"""@apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: ... | stack_v2_sparse_classes_75kplus_train_003458 | 4,091 | no_license | [
{
"docstring": "@apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, tablet web, 8: Desktop web) @apiHeader ... | 2 | stack_v2_sparse_classes_30k_train_008602 | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def create(self, request): @apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device typ... | Implement the Python class `AuthViewSet` described below.
Class description:
Implement the AuthViewSet class.
Method signatures and docstrings:
- def create(self, request): @apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device typ... | b5c5bd25fb05965621615d09439bf79fa1b8d5e8 | <|skeleton|>
class AuthViewSet:
def create(self, request):
"""@apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AuthViewSet:
def create(self, request):
"""@apiVersion 1.0.0 @api {post} /auth Login @apiName Authenticate @apiGroup VMS_API Account @apiPermission none @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, ta... | the_stack_v2_python_sparse | src/kitchenrock_api/views/auth.py | thqbop/kitchenrock | train | 0 | |
6727d0823ebc4b00846bc7eb6387aac3611391a9 | [
"if name is None:\n return jsonify(responses.missing_parameters)\nsensor = Sensor.objects(name=name).first()\nif sensor is None:\n return jsonify(responses.invalid_uuid)\ntags_owned = [{'name': tag.name, 'value': tag.value} for tag in sensor.tags]\nmetadata = Sensor._get_collection().find({'name': name}, {'me... | <|body_start_0|>
if name is None:
return jsonify(responses.missing_parameters)
sensor = Sensor.objects(name=name).first()
if sensor is None:
return jsonify(responses.invalid_uuid)
tags_owned = [{'name': tag.name, 'value': tag.value} for tag in sensor.tags]
... | SensorService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier... | stack_v2_sparse_classes_75kplus_train_003459 | 3,642 | permissive | [
{
"docstring": "Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier' : str(sensor.source_identifier), 'source_name... | 2 | stack_v2_sparse_classes_30k_train_006866 | Implement the Python class `SensorService` described below.
Class description:
Implement the SensorService class.
Method signatures and docstrings:
- def get(self, name): Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sens... | Implement the Python class `SensorService` described below.
Class description:
Implement the SensorService class.
Method signatures and docstrings:
- def get(self, name): Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sens... | 53ba7519c56d46af1e32a77aab5cf1c5cd8143fc | <|skeleton|>
class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SensorService:
def get(self, name):
"""Retrieve sensor details based on uuid specified Args as data: name : <name of sensor> Returns (JSON): { 'building': <name of building in which sensor is present>, 'name' : <sensor uuid>, 'tags' : tags_owned, 'metadata' : metadata, 'source_identifier' : str(sensor... | the_stack_v2_python_sparse | BuildingDepot-v3.2.8/buildingdepot/CentralService/app/rest_api/sensors/sensor.py | Entromorgan/GIoTTo | train | 0 | |
c471ee1f458492395e2777dbb0d1b023c90e5408 | [
"cur = head\nlength = 0\nwhile cur:\n length += 1\n cur = cur.next\nreturn length",
"head_length = self.length(head)\nbreak_point = head_length // k\nif k == 0 or break_point == 0:\n return head\nb_count = 1\ncur = head\nres_node = ListNode(1)\nres_cur = res_node\nwhile cur and b_count <= break_point:\n ... | <|body_start_0|>
cur = head
length = 0
while cur:
length += 1
cur = cur.next
return length
<|end_body_0|>
<|body_start_1|>
head_length = self.length(head)
break_point = head_length // k
if k == 0 or break_point == 0:
return hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
lengt... | stack_v2_sparse_classes_75kplus_train_003460 | 1,292 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "length",
"signature": "def length(self, head)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_025119 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def length(self, head): :type head: ListNode :rtype: ListNode
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
<|skeleton|>
class Solution:... | 9bd2d706f014ce84356ba38fc7801da0285a91d3 | <|skeleton|>
class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def length(self, head):
""":type head: ListNode :rtype: ListNode"""
cur = head
length = 0
while cur:
length += 1
cur = cur.next
return length
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: Li... | the_stack_v2_python_sparse | leetcode/reverseKGroup-25.py | pittcat/Algorithm_Practice | train | 0 | |
7e211fd2c0414dcfea889002ba45d2d8c6c78b07 | [
"ret_data = []\ndb_query = DBSetting.extend()\nname = self.get_argument('name', None)\nif name is not None:\n db_query = db_query.filter(DBSetting.name == name)\ndb_type = self.get_argument('type', None)\nif db_type is not None:\n db_query = db_query.filter(DBSetting.db_type == db_type)\ndb_query = db_query.o... | <|body_start_0|>
ret_data = []
db_query = DBSetting.extend()
name = self.get_argument('name', None)
if name is not None:
db_query = db_query.filter(DBSetting.name == name)
db_type = self.get_argument('type', None)
if db_type is not None:
db_query =... | DbSettingHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbSettingHandler:
async def get(self, *args, **kwargs):
"""获取数据库配置列表数据"""
<|body_0|>
async def post(self, *args, **kwargs):
"""更新数据库配置数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret_data = []
db_query = DBSetting.extend()
name... | stack_v2_sparse_classes_75kplus_train_003461 | 17,374 | permissive | [
{
"docstring": "获取数据库配置列表数据",
"name": "get",
"signature": "async def get(self, *args, **kwargs)"
},
{
"docstring": "更新数据库配置数据",
"name": "post",
"signature": "async def post(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006996 | Implement the Python class `DbSettingHandler` described below.
Class description:
Implement the DbSettingHandler class.
Method signatures and docstrings:
- async def get(self, *args, **kwargs): 获取数据库配置列表数据
- async def post(self, *args, **kwargs): 更新数据库配置数据 | Implement the Python class `DbSettingHandler` described below.
Class description:
Implement the DbSettingHandler class.
Method signatures and docstrings:
- async def get(self, *args, **kwargs): 获取数据库配置列表数据
- async def post(self, *args, **kwargs): 更新数据库配置数据
<|skeleton|>
class DbSettingHandler:
async def get(self... | dc9b4c55f0b3ace180c30b7f080eb5d88bb38fdb | <|skeleton|>
class DbSettingHandler:
async def get(self, *args, **kwargs):
"""获取数据库配置列表数据"""
<|body_0|>
async def post(self, *args, **kwargs):
"""更新数据库配置数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DbSettingHandler:
async def get(self, *args, **kwargs):
"""获取数据库配置列表数据"""
ret_data = []
db_query = DBSetting.extend()
name = self.get_argument('name', None)
if name is not None:
db_query = db_query.filter(DBSetting.name == name)
db_type = self.get_ar... | the_stack_v2_python_sparse | apps/project/handlers.py | xiaoxiaolulu/MagicTestPlatform | train | 5 | |
844b03735cb5c0ed2fd8be1ce9bf38005bfa3f76 | [
"if answers is None:\n answers = []\nself.name = name\nself.answers = [answer for answer in answers]\nself.default = default\nself.question = question",
"name = tag.find('name').text if tag.find('name') else None\nquestion = tag.find('question').text if tag.find('question') else None\ndefault = tag.find('answe... | <|body_start_0|>
if answers is None:
answers = []
self.name = name
self.answers = [answer for answer in answers]
self.default = default
self.question = question
<|end_body_0|>
<|body_start_1|>
name = tag.find('name').text if tag.find('name') else None
... | SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotter which must specify the titles for each axis and for the plot. These special ... | SpecialCard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecialCard:
"""SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotter which must specify the titles for eac... | stack_v2_sparse_classes_75kplus_train_003462 | 1,468 | permissive | [
{
"docstring": "Initialize object.",
"name": "__init__",
"signature": "def __init__(self, name=None, question=None, default=None, answers=None)"
},
{
"docstring": "Create SpecialCard from Tag. Args: tag (Tag): The XML tag with its attributes and contents.",
"name": "from_tag",
"signature... | 2 | null | Implement the Python class `SpecialCard` described below.
Class description:
SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotte... | Implement the Python class `SpecialCard` described below.
Class description:
SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotte... | f2deb5eb340a2814722eead5f8b6278a945c730d | <|skeleton|>
class SpecialCard:
"""SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotter which must specify the titles for eac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpecialCard:
"""SpecialCard class. Once the user has defined the Parameters, Inputs, Outputs, and Derivatives, some components require addition description statements (or Cards). An example of a model that requires a special card is the TYPE 65 Online plotter which must specify the titles for each axis and fo... | the_stack_v2_python_sparse | trnsystor/specialcard.py | sturmianseq/trnsystor | train | 0 |
e7cdd08572fd6dc1751c427db4d84ef84c32a53d | [
"if not self.is_valid or self.unsubscribed_at is not None:\n return\naddr = HeaderInformationBlock(addr_to=self.notify_to_address, action=action, addr_from=None, reference_parameters=self.notify_ref_params)\nmessage = self._mk_notification_message(addr, body_node)\ntry:\n soap_client = self._get_soap_client()... | <|body_start_0|>
if not self.is_valid or self.unsubscribed_at is not None:
return
addr = HeaderInformationBlock(addr_to=self.notify_to_address, action=action, addr_from=None, reference_parameters=self.notify_ref_params)
message = self._mk_notification_message(addr, body_node)
... | Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync. | BicepsSubscriptionAsync | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BicepsSubscriptionAsync:
"""Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync."""
async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str):
"""Send notification to subscriber."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003463 | 15,551 | permissive | [
{
"docstring": "Send notification to subscriber.",
"name": "async_send_notification_report",
"signature": "async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str)"
},
{
"docstring": "Send notification end message to subscriber.",
"name": "async_send_notific... | 2 | stack_v2_sparse_classes_30k_train_029363 | Implement the Python class `BicepsSubscriptionAsync` described below.
Class description:
Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync.
Method signatures and docstrings:
- async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str): Sen... | Implement the Python class `BicepsSubscriptionAsync` described below.
Class description:
Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync.
Method signatures and docstrings:
- async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str): Sen... | dab57b38ed9a9e70e6bc6a9cf44140b96fd95851 | <|skeleton|>
class BicepsSubscriptionAsync:
"""Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync."""
async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str):
"""Send notification to subscriber."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BicepsSubscriptionAsync:
"""Async version of a single BICEPS subscription. It is used by BICEPSSubscriptionsManagerBaseAsync."""
async def async_send_notification_report(self, body_node: etree_.ElementBase, action: str):
"""Send notification to subscriber."""
if not self.is_valid or self.... | the_stack_v2_python_sparse | src/sdc11073/provider/subscriptionmgr_async.py | deichmab-draeger/sdc11073 | train | 0 |
a0bf7ae96bd3d266e5208706424ac4bc28e1e06c | [
"assert callable(item_maker), f'{repr(item_maker)} not callable.'\nself._pool_item_maker = item_maker\nself._key_to_pool: Dict[Hashable, list] = defaultdict(list)\nself._pool_item_id_to_is_acquired: Dict[int, bool] = {}\nself._thread_lock = Lock()",
"with self._thread_lock:\n pool = self._key_to_pool[key]\n ... | <|body_start_0|>
assert callable(item_maker), f'{repr(item_maker)} not callable.'
self._pool_item_maker = item_maker
self._key_to_pool: Dict[Hashable, list] = defaultdict(list)
self._pool_item_id_to_is_acquired: Dict[int, bool] = {}
self._thread_lock = Lock()
<|end_body_0|>
<|bo... | Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from module-scoped callables. Attribute... | KeyPool | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from... | stack_v2_sparse_classes_75kplus_train_003464 | 12,902 | permissive | [
{
"docstring": "Initialize this key pool with the passed factory callable. Parameters ---------- item_maker : Union[type, Callable[[Hashable,], Any]] Caller-defined factory callable internally called by the :meth:`acquire` method on attempting to acquire a non-existent object from an **empty pool** (i.e., eithe... | 3 | stack_v2_sparse_classes_30k_train_015597 | Implement the Python class `KeyPool` described below.
Class description:
Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable... | Implement the Python class `KeyPool` described below.
Class description:
Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable... | 0cfd53391eb4de2f8297a4632aa5895b8d82a5b7 | <|skeleton|>
class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeyPool:
"""Thread-safe **key pool** (i.e., object cache implemented as a dictionary of lists of arbitrary objects to be cached, where objects cached to the same list are typically of the same type). Key pools are thread-safe by design and thus safely usable as module-scoped globals accessed from module-scope... | the_stack_v2_python_sparse | beartype/_util/cache/pool/utilcachepool.py | beartype/beartype | train | 1,992 |
e6b130f24b2b3d7aedaf3964ad7f016b3111f4e4 | [
"super(NN_Attention, self).__init__()\nn_embeddings, self.embedding_size = np.shape(embeddings)\nself.embeddings = nn.Embedding(num_embeddings=n_embeddings, embedding_dim=self.embedding_size)\nself.embeddings.load_state_dict({'weight': torch.from_numpy(embeddings)})\nif not trainable_emb:\n self.embeddings.weigh... | <|body_start_0|>
super(NN_Attention, self).__init__()
n_embeddings, self.embedding_size = np.shape(embeddings)
self.embeddings = nn.Embedding(num_embeddings=n_embeddings, embedding_dim=self.embedding_size)
self.embeddings.load_state_dict({'weight': torch.from_numpy(embeddings)})
... | 1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes. | NN_Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NN_Attention:
"""1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes."""
def __init__(self, output_size, embeddings, trainable_emb=False):
"... | stack_v2_sparse_classes_75kplus_train_003465 | 2,351 | permissive | [
{
"docstring": "Args: output_size(int): the number of classes embeddings(bool): the 2D matrix with the pretrained embeddings trainable_emb(bool): train (finetune) or freeze the weights the embedding layer",
"name": "__init__",
"signature": "def __init__(self, output_size, embeddings, trainable_emb=False... | 2 | stack_v2_sparse_classes_30k_val_002286 | Implement the Python class `NN_Attention` described below.
Class description:
1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes.
Method signatures and docstrings:
- def __i... | Implement the Python class `NN_Attention` described below.
Class description:
1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes.
Method signatures and docstrings:
- def __i... | c7487c58bde54036b07df2b7ff9b4f2cd9776a15 | <|skeleton|>
class NN_Attention:
"""1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes."""
def __init__(self, output_size, embeddings, trainable_emb=False):
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NN_Attention:
"""1. We embed the words in the input texts using an embedding layer. 2. We compute the weighted sum of word embeddings. 3. We project with a linear layer the representation to the number of classes."""
def __init__(self, output_size, embeddings, trainable_emb=False):
"""Args: outpu... | the_stack_v2_python_sparse | Lab3/Lab/models/NN_Attention.py | PanosAntoniadis/slp-ntua | train | 11 |
62773eb73917c27b01cb5ee11edba17b531017cc | [
"super(littleConv, self).__init__()\nself.main = nn.Sequential(nn.Conv2d(num_channels, 64, 4, 2, 1, bias=False), nn.ReLU(True), nn.BatchNorm2d(64), nn.Conv2d(64, 128, 4, 2, 1, bias=False), nn.ReLU(True), nn.BatchNorm2d(128), nn.Conv2d(128, 256, 4, 2, 1, bias=False), nn.ReLU(True), nn.BatchNorm2d(256), nn.Conv2d(256... | <|body_start_0|>
super(littleConv, self).__init__()
self.main = nn.Sequential(nn.Conv2d(num_channels, 64, 4, 2, 1, bias=False), nn.ReLU(True), nn.BatchNorm2d(64), nn.Conv2d(64, 128, 4, 2, 1, bias=False), nn.ReLU(True), nn.BatchNorm2d(128), nn.Conv2d(128, 256, 4, 2, 1, bias=False), nn.ReLU(True), nn.Batc... | Class encoder | littleConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class littleConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
<|body_0|>
def init_weights(self):
"""Weight Initialization"""
<|body_1|>
def forward(self, input):
... | stack_v2_sparse_classes_75kplus_train_003466 | 3,780 | no_license | [
{
"docstring": "Initialization conv -> ReLU x 4 -> (mu, sigma)",
"name": "__init__",
"signature": "def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02)"
},
{
"docstring": "Weight Initialization",
"name": "init_weights",
"signature": "def init_weights(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_014027 | Implement the Python class `littleConv` described below.
Class description:
Class encoder
Method signatures and docstrings:
- def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02): Initialization conv -> ReLU x 4 -> (mu, sigma)
- def init_weights(self): Weight Initialization
- def forward(self, input): Defin... | Implement the Python class `littleConv` described below.
Class description:
Class encoder
Method signatures and docstrings:
- def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02): Initialization conv -> ReLU x 4 -> (mu, sigma)
- def init_weights(self): Weight Initialization
- def forward(self, input): Defin... | 21c0bf459388bd616a64afc1a34441123b1f41fe | <|skeleton|>
class littleConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
<|body_0|>
def init_weights(self):
"""Weight Initialization"""
<|body_1|>
def forward(self, input):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class littleConv:
"""Class encoder"""
def __init__(self, c_dim, z_dim=200, num_channels=1, std=0.02):
"""Initialization conv -> ReLU x 4 -> (mu, sigma)"""
super(littleConv, self).__init__()
self.main = nn.Sequential(nn.Conv2d(num_channels, 64, 4, 2, 1, bias=False), nn.ReLU(True), nn.Bat... | the_stack_v2_python_sparse | classification/models/littleConv.py | CHOcho-quan/CS385ML | train | 1 |
b31b2280ae652d3614e7b4cb893a4ca1b9a626f9 | [
"ElementBase.__init__(self, agent, 'T.%s' % '+'.join(map(Sense.getName, senses)))\nself._senses = senses\nself.log.debug('Created')",
"self.log.debug('Firing')\nfor sense in self._senses:\n if not sense.fire():\n self.log.debug(\"Sense '%s' failed\" % sense.getName())\n return False\nreturn True"... | <|body_start_0|>
ElementBase.__init__(self, agent, 'T.%s' % '+'.join(map(Sense.getName, senses)))
self._senses = senses
self.log.debug('Created')
<|end_body_0|>
<|body_start_1|>
self.log.debug('Firing')
for sense in self._senses:
if not sense.fire():
... | A conjunction of senses and sense-acts, acting as a trigger. | Trigger | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trigger:
"""A conjunction of senses and sense-acts, acting as a trigger."""
def __init__(self, agent, senses):
"""Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent that uses the trigger. @type agent: L{POSH.strict.Agent} @... | stack_v2_sparse_classes_75kplus_train_003467 | 4,553 | no_license | [
{
"docstring": "Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent that uses the trigger. @type agent: L{POSH.strict.Agent} @param senses: The list of senses and sense-acts for the trigger. @type senses: Sequence of L{POSH.strict.Sense}",
"name": ... | 2 | null | Implement the Python class `Trigger` described below.
Class description:
A conjunction of senses and sense-acts, acting as a trigger.
Method signatures and docstrings:
- def __init__(self, agent, senses): Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent t... | Implement the Python class `Trigger` described below.
Class description:
A conjunction of senses and sense-acts, acting as a trigger.
Method signatures and docstrings:
- def __init__(self, agent, senses): Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent t... | ed0907d5172efd5e8752fd989c78cd878e32cb49 | <|skeleton|>
class Trigger:
"""A conjunction of senses and sense-acts, acting as a trigger."""
def __init__(self, agent, senses):
"""Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent that uses the trigger. @type agent: L{POSH.strict.Agent} @... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Trigger:
"""A conjunction of senses and sense-acts, acting as a trigger."""
def __init__(self, agent, senses):
"""Initialises the trigger. The log domain is set to [Agent].T.[senseName1+senseName2+...] @param agent: The agent that uses the trigger. @type agent: L{POSH.strict.Agent} @param senses:... | the_stack_v2_python_sparse | posh/POSH/strict/sense.py | olrunsrc/fc-public | train | 0 |
dfd0cbea4374e70aedb88ee7fde2265d1cadcc0c | [
"self.logger = getMSLogger(getattr(msConfig, 'verbose', False), kwargs.get('logger'))\nself.msConfig = msConfig\nself.logger.info('Configuration including default values:\\n%s', self.msConfig)\nif not kwargs.get('skipReqMgr', False):\n self.reqmgr2 = ReqMgr(self.msConfig['reqmgr2Url'], logger=self.logger)\nif no... | <|body_start_0|>
self.logger = getMSLogger(getattr(msConfig, 'verbose', False), kwargs.get('logger'))
self.msConfig = msConfig
self.logger.info('Configuration including default values:\n%s', self.msConfig)
if not kwargs.get('skipReqMgr', False):
self.reqmgr2 = ReqMgr(self.msC... | This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes. | MSCore | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSCore:
"""This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes."""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param config: MS service configuration :param kwargs: ... | stack_v2_sparse_classes_75kplus_train_003468 | 4,792 | permissive | [
{
"docstring": "Provides a basic setup for all the microservices :param config: MS service configuration :param kwargs: can be used to skip the initialization of specific services, such as: logger: logger object skipReqMgr: boolean to skip ReqMgr initialization skipReqMgrAux: boolean to skip ReqMgrAux initializ... | 5 | null | Implement the Python class `MSCore` described below.
Class description:
This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes.
Method signatures and docstrings:
- def __init__(self, msConfig, **kwargs): Provides a basic setup for all the microservice... | Implement the Python class `MSCore` described below.
Class description:
This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes.
Method signatures and docstrings:
- def __init__(self, msConfig, **kwargs): Provides a basic setup for all the microservice... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class MSCore:
"""This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes."""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param config: MS service configuration :param kwargs: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MSCore:
"""This class provides core functionality for MSTransferor, MSMonitor, MSOutput, MSPileup, MSRuleCleaner, MSUnmerged classes."""
def __init__(self, msConfig, **kwargs):
"""Provides a basic setup for all the microservices :param config: MS service configuration :param kwargs: can be used t... | the_stack_v2_python_sparse | src/python/WMCore/MicroService/MSCore/MSCore.py | vkuznet/WMCore | train | 0 |
5c435271004db1ec8fc71bd129bfef289bca8c6a | [
"logic = CurriculumLogic(self.auth, sid, aid)\nparams = ParamsParser(request.JSON)\ncontent = params.list('content', desc='课表内容')\n_config = logic.get_association_curriculum_config()\nkeys = _config.time().keys()\ndata = {'day{}'.format(i): {k: False for k in keys} for i in range(1, 8)}\nindex = 1\nfor _time in con... | <|body_start_0|>
logic = CurriculumLogic(self.auth, sid, aid)
params = ParamsParser(request.JSON)
content = params.list('content', desc='课表内容')
_config = logic.get_association_curriculum_config()
keys = _config.time().keys()
data = {'day{}'.format(i): {k: False for k in k... | CurriculumView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurriculumView:
def post(self, request, sid, aid):
"""填写课表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def get(self, request, sid, aid):
"""汇总无课表 or 获取课表信息 :param request: :param sid: :param aid: :return: redis key scheduling:协会id:"""
<|bod... | stack_v2_sparse_classes_75kplus_train_003469 | 5,262 | no_license | [
{
"docstring": "填写课表 :param request: :param sid: :param aid: :return:",
"name": "post",
"signature": "def post(self, request, sid, aid)"
},
{
"docstring": "汇总无课表 or 获取课表信息 :param request: :param sid: :param aid: :return: redis key scheduling:协会id:",
"name": "get",
"signature": "def get(s... | 2 | stack_v2_sparse_classes_30k_train_001081 | Implement the Python class `CurriculumView` described below.
Class description:
Implement the CurriculumView class.
Method signatures and docstrings:
- def post(self, request, sid, aid): 填写课表 :param request: :param sid: :param aid: :return:
- def get(self, request, sid, aid): 汇总无课表 or 获取课表信息 :param request: :param si... | Implement the Python class `CurriculumView` described below.
Class description:
Implement the CurriculumView class.
Method signatures and docstrings:
- def post(self, request, sid, aid): 填写课表 :param request: :param sid: :param aid: :return:
- def get(self, request, sid, aid): 汇总无课表 or 获取课表信息 :param request: :param si... | a0553be3c259712de1fe5517b06317ad5756f79d | <|skeleton|>
class CurriculumView:
def post(self, request, sid, aid):
"""填写课表 :param request: :param sid: :param aid: :return:"""
<|body_0|>
def get(self, request, sid, aid):
"""汇总无课表 or 获取课表信息 :param request: :param sid: :param aid: :return: redis key scheduling:协会id:"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurriculumView:
def post(self, request, sid, aid):
"""填写课表 :param request: :param sid: :param aid: :return:"""
logic = CurriculumLogic(self.auth, sid, aid)
params = ParamsParser(request.JSON)
content = params.list('content', desc='课表内容')
_config = logic.get_association_... | the_stack_v2_python_sparse | LittlePigHoHo/server/scheduling/views/curriculum/info.py | shoogoome/hoho | train | 1 | |
ba357d3a29e3afb5ca488930687b602a45e3d5e3 | [
"super(GroupedModelMultipleChoiceField, self).__init__(queryset, *args, **kwargs)\nself.group_by_field = group_by_field\nif group_label is None:\n self.group_label = lambda group: group\nelse:\n self.group_label = group_label",
"if hasattr(self, '_choices'):\n return self._choices\nreturn GroupedModelCho... | <|body_start_0|>
super(GroupedModelMultipleChoiceField, self).__init__(queryset, *args, **kwargs)
self.group_by_field = group_by_field
if group_label is None:
self.group_label = lambda group: group
else:
self.group_label = group_label
<|end_body_0|>
<|body_start_... | A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/ | GroupedModelMultipleChoiceField | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupedModelMultipleChoiceField:
"""A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/"""
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is... | stack_v2_sparse_classes_75kplus_train_003470 | 4,687 | permissive | [
{
"docstring": "group_by_field is the name of a field on the model group_label is a function to return a label for each choice group",
"name": "__init__",
"signature": "def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs)"
},
{
"docstring": "Exactly as per ModelChoiceF... | 2 | null | Implement the Python class `GroupedModelMultipleChoiceField` described below.
Class description:
A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/
Method signatures and docstrings:
- def __init__(self, queryset, group_by_fie... | Implement the Python class `GroupedModelMultipleChoiceField` described below.
Class description:
A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/
Method signatures and docstrings:
- def __init__(self, queryset, group_by_fie... | 69aa3f5f702814969b41d62c19cd53db1f164397 | <|skeleton|>
class GroupedModelMultipleChoiceField:
"""A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/"""
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupedModelMultipleChoiceField:
"""A ModelMultipleChoiceField that groups choices by a specified field on the model. Heavily inspired by https://djangosnippets.org/snippets/2622/"""
def __init__(self, queryset, group_by_field, group_label=None, *args, **kwargs):
"""group_by_field is the name of ... | the_stack_v2_python_sparse | brambling/forms/base.py | dancerfly/django-brambling | train | 2 |
a2c1e4b1b7366c34d8b89f2e3b4dc7268c8ca066 | [
"self.Game = game\nself.dx = 1\nself.paddle = self.Game.canevas.create_rectangle(370, 500, 370 + 60, 500 + 8, fill='grey')\nself.Game.root.bind('<Motion>', self.motion)",
"if event.x - 30 <= 0:\n self.Game.canevas.coords(self.paddle, 0, 500, 60, 500 + 8)\n if self.Game.ball.static:\n self.Game.root.b... | <|body_start_0|>
self.Game = game
self.dx = 1
self.paddle = self.Game.canevas.create_rectangle(370, 500, 370 + 60, 500 + 8, fill='grey')
self.Game.root.bind('<Motion>', self.motion)
<|end_body_0|>
<|body_start_1|>
if event.x - 30 <= 0:
self.Game.canevas.coords(self.p... | Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left | Paddle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bin... | stack_v2_sparse_classes_75kplus_train_003471 | 2,368 | no_license | [
{
"docstring": "Creation of all the features of the paddle : width, height, movement speed Bind <motion> for the object paddle : it moves when the user moves the mouse PRE: Game class is running POST: - Creation of the paddle label which represents the paddle in the Graphic User Interface - Binding of the movem... | 2 | stack_v2_sparse_classes_30k_train_039995 | Implement the Python class `Paddle` described below.
Class description:
Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left
Method signatures and docstrings:
- def __init__(self, game): Creation of all the f... | Implement the Python class `Paddle` described below.
Class description:
Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left
Method signatures and docstrings:
- def __init__(self, game): Creation of all the f... | 663120fb4b69e9727b48d7f7bd96180e09be2c76 | <|skeleton|>
class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Paddle:
"""Class representing a paddle Author : Mathis Dory, Eliott Lepage Date : November 2020 This class is used to create an animate Paddle which moves from right to left"""
def __init__(self, game):
"""Creation of all the features of the paddle : width, height, movement speed Bind <motion> fo... | the_stack_v2_python_sparse | libs/paddle/classe.py | Mathis-Dory/Projet-Python-brick-breaker | train | 0 |
42c8bbb15a1f1955b74b23c755b69fabcac104cb | [
"if self.setting('USE_UNIQUE_USER_ID', False):\n if 'sub' in response:\n return response['sub']\n else:\n return response['id']\nelse:\n return details['email']",
"email = response.get('email', '')\nname, given_name, family_name = (response.get('name', ''), response.get('given_name', ''), r... | <|body_start_0|>
if self.setting('USE_UNIQUE_USER_ID', False):
if 'sub' in response:
return response['sub']
else:
return response['id']
else:
return details['email']
<|end_body_0|>
<|body_start_1|>
email = response.get('email',... | BaseGoogleAuth | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
<|body_0|>
def get_user_details(self, response):
"""Return user details from Google API account"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.set... | stack_v2_sparse_classes_75kplus_train_003472 | 6,302 | permissive | [
{
"docstring": "Use google email as unique id",
"name": "get_user_id",
"signature": "def get_user_id(self, details, response)"
},
{
"docstring": "Return user details from Google API account",
"name": "get_user_details",
"signature": "def get_user_details(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_028736 | Implement the Python class `BaseGoogleAuth` described below.
Class description:
Implement the BaseGoogleAuth class.
Method signatures and docstrings:
- def get_user_id(self, details, response): Use google email as unique id
- def get_user_details(self, response): Return user details from Google API account | Implement the Python class `BaseGoogleAuth` described below.
Class description:
Implement the BaseGoogleAuth class.
Method signatures and docstrings:
- def get_user_id(self, details, response): Use google email as unique id
- def get_user_details(self, response): Return user details from Google API account
<|skeleto... | cf95380a177e9b8d1f3b4da03543fb2f0d248bf3 | <|skeleton|>
class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
<|body_0|>
def get_user_details(self, response):
"""Return user details from Google API account"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseGoogleAuth:
def get_user_id(self, details, response):
"""Use google email as unique id"""
if self.setting('USE_UNIQUE_USER_ID', False):
if 'sub' in response:
return response['sub']
else:
return response['id']
else:
... | the_stack_v2_python_sparse | social_core/backends/google.py | python-social-auth/social-core | train | 831 | |
408e74d4c066cd0124e4d9d2affa16ef24a32999 | [
"rows, cols = (len(matrix), len(matrix[0]))\nself.prefixSumMatrix = []\nfor i in range(rows):\n l = [matrix[i][0]]\n for j in range(1, cols):\n l.append(l[-1] + matrix[i][j])\n self.prefixSumMatrix.append(l)",
"res = 0\nfor i in range(row1, row2 + 1):\n if col1 != 0:\n res += self.prefix... | <|body_start_0|>
rows, cols = (len(matrix), len(matrix[0]))
self.prefixSumMatrix = []
for i in range(rows):
l = [matrix[i][0]]
for j in range(1, cols):
l.append(l[-1] + matrix[i][j])
self.prefixSumMatrix.append(l)
<|end_body_0|>
<|body_start_1... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_75kplus_train_003473 | 1,206 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_016612 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
rows, cols = (len(matrix), len(matrix[0]))
self.prefixSumMatrix = []
for i in range(rows):
l = [matrix[i][0]]
for j in range(1, cols):
l.append(l[-1] + matrix[i][j... | the_stack_v2_python_sparse | _CodeTopics/LeetCode/201-400/000304/RE--000304.py | BIAOXYZ/variousCodes | train | 0 | |
e2e5e8c0e2d2b53ca7738abb0d5991d38c2ada5b | [
"cur_path = os.path.abspath(os.path.dirname(__file__))\nconfig_file = os.path.join(cur_path, '../conf/project_host_mapping.yaml')\nself.project_host_map = FileOperator.filereader(config_file, 'yaml')",
"if priority:\n return '[{}]\\nname={}\\nbaseurl={}\\nenabled=1\\ngpgcheck=0\\npriority={}\\n'.format(repo_id... | <|body_start_0|>
cur_path = os.path.abspath(os.path.dirname(__file__))
config_file = os.path.join(cur_path, '../conf/project_host_mapping.yaml')
self.project_host_map = FileOperator.filereader(config_file, 'yaml')
<|end_body_0|>
<|body_start_1|>
if priority:
return '[{}]\nna... | 生成obs实时仓作为rpm源的配置 | OBSRepoSource | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"MulanPSL-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OBSRepoSource:
"""生成obs实时仓作为rpm源的配置"""
def __init__(self):
""":param repo_host: obs仓库host"""
<|body_0|>
def repo_format(repo_id, repo_name, repo_baseurl, priority=None):
"""repo内容格式 :param repo_id: :param repo_name: :param repo_baseurl: :param priority: :return:"... | stack_v2_sparse_classes_75kplus_train_003474 | 3,903 | permissive | [
{
"docstring": ":param repo_host: obs仓库host",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "repo内容格式 :param repo_id: :param repo_name: :param repo_baseurl: :param priority: :return:",
"name": "repo_format",
"signature": "def repo_format(repo_id, repo_name, repo... | 4 | stack_v2_sparse_classes_30k_train_007612 | Implement the Python class `OBSRepoSource` described below.
Class description:
生成obs实时仓作为rpm源的配置
Method signatures and docstrings:
- def __init__(self): :param repo_host: obs仓库host
- def repo_format(repo_id, repo_name, repo_baseurl, priority=None): repo内容格式 :param repo_id: :param repo_name: :param repo_baseurl: :para... | Implement the Python class `OBSRepoSource` described below.
Class description:
生成obs实时仓作为rpm源的配置
Method signatures and docstrings:
- def __init__(self): :param repo_host: obs仓库host
- def repo_format(repo_id, repo_name, repo_baseurl, priority=None): repo内容格式 :param repo_id: :param repo_name: :param repo_baseurl: :para... | 6b088eb29a53510eb441338804da79ad6d0623ab | <|skeleton|>
class OBSRepoSource:
"""生成obs实时仓作为rpm源的配置"""
def __init__(self):
""":param repo_host: obs仓库host"""
<|body_0|>
def repo_format(repo_id, repo_name, repo_baseurl, priority=None):
"""repo内容格式 :param repo_id: :param repo_name: :param repo_baseurl: :param priority: :return:"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OBSRepoSource:
"""生成obs实时仓作为rpm源的配置"""
def __init__(self):
""":param repo_host: obs仓库host"""
cur_path = os.path.abspath(os.path.dirname(__file__))
config_file = os.path.join(cur_path, '../conf/project_host_mapping.yaml')
self.project_host_map = FileOperator.filereader(conf... | the_stack_v2_python_sparse | src/build/obs_repo_source.py | openeuler-mirror/openeuler-jenkins | train | 2 |
5f5b10ad4cb85707afd21c08795d542ccc0ec1a9 | [
"dtypes = data.dtypes\ndtypes = dtypes.reset_index()\ndtypes.columns = ['feature_name', 'types']\nobj_list = list(dtypes.loc[dtypes['types'] == 'object', 'feature_name'])\nobj_data = data.loc[:, obj_list]\nreturn obj_data",
"from sklearn.preprocessing import LabelEncoder\ndata = data.loc[:, var_list]\ncols = data... | <|body_start_0|>
dtypes = data.dtypes
dtypes = dtypes.reset_index()
dtypes.columns = ['feature_name', 'types']
obj_list = list(dtypes.loc[dtypes['types'] == 'object', 'feature_name'])
obj_data = data.loc[:, obj_list]
return obj_data
<|end_body_0|>
<|body_start_1|>
... | Label_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Label_Encoder:
def slice_obj_data(self, data):
"""提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集"""
<|body_0|>
def label_encoder_fit(self, data, var_list):
"""提认为模拟label_encoder的fit过程,得到fit的字典,要求data为类别型的数据 Args: data:原数据框 ... | stack_v2_sparse_classes_75kplus_train_003475 | 4,010 | no_license | [
{
"docstring": "提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集",
"name": "slice_obj_data",
"signature": "def slice_obj_data(self, data)"
},
{
"docstring": "提认为模拟label_encoder的fit过程,得到fit的字典,要求data为类别型的数据 Args: data:原数据框 var_list:数据类型为类别型的字段名列表 Returns:... | 3 | stack_v2_sparse_classes_30k_train_039769 | Implement the Python class `Label_Encoder` described below.
Class description:
Implement the Label_Encoder class.
Method signatures and docstrings:
- def slice_obj_data(self, data): 提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集
- def label_encoder_fit(self, data, var_list)... | Implement the Python class `Label_Encoder` described below.
Class description:
Implement the Label_Encoder class.
Method signatures and docstrings:
- def slice_obj_data(self, data): 提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集
- def label_encoder_fit(self, data, var_list)... | cc25cb60f1c1c89b4591bbdaec8db1eeba818377 | <|skeleton|>
class Label_Encoder:
def slice_obj_data(self, data):
"""提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集"""
<|body_0|>
def label_encoder_fit(self, data, var_list):
"""提认为模拟label_encoder的fit过程,得到fit的字典,要求data为类别型的数据 Args: data:原数据框 ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Label_Encoder:
def slice_obj_data(self, data):
"""提取数据类型为object的数据,可能需要填充缺失值,可能是类别型特征需要进行label或one-hot Args: data: Returns: 数据类型为object的数据子集"""
dtypes = data.dtypes
dtypes = dtypes.reset_index()
dtypes.columns = ['feature_name', 'types']
obj_list = list(dtypes.loc[dtype... | the_stack_v2_python_sparse | bus_drop/loans_drop/feature_engineering/label_encoder.py | xeon-ye/dgg-pro | train | 0 | |
5f3e9702e6b26299fb342726951f38aaf8969c6f | [
"logger.info('Host {}: Setting base prompt'.format(self._host))\nprompt = await self._find_prompt()\nprompt = prompt[:-1]\nif '@' in prompt:\n prompt = prompt.split('@')[1]\nself._base_prompt = prompt\ndelimiters = map(re.escape, type(self)._delimiter_list)\ndelimiters = '|'.join(delimiters)\nbase_prompt = re.es... | <|body_start_0|>
logger.info('Host {}: Setting base prompt'.format(self._host))
prompt = await self._find_prompt()
prompt = prompt[:-1]
if '@' in prompt:
prompt = prompt.split('@')[1]
self._base_prompt = prompt
delimiters = map(re.escape, type(self)._delimiter... | JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). The entire configuration is usual configured in this shell: * operation mode. This... | JunOSLikeDevice | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JunOSLikeDevice:
"""JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). The entire configuration is usual confi... | stack_v2_sparse_classes_75kplus_train_003476 | 5,855 | permissive | [
{
"docstring": "Setting two important vars base_prompt - textual prompt in CLI (usually username or hostname) base_pattern - regexp for finding the end of command. IT's platform specific parameter For JunOS devices base_pattern is \"user(@[hostname])?[>|#]",
"name": "_set_base_prompt",
"signature": "asy... | 5 | stack_v2_sparse_classes_30k_train_052033 | Implement the Python class `JunOSLikeDevice` described below.
Class description:
JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). ... | Implement the Python class `JunOSLikeDevice` described below.
Class description:
JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). ... | e2585ac24891cba172fc2056e9868e1d7c41ddc2 | <|skeleton|>
class JunOSLikeDevice:
"""JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). The entire configuration is usual confi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JunOSLikeDevice:
"""JunOSLikeDevice Class for working with Juniper JunOS like devices Juniper JunOS like devices having several concepts: * shell mode (csh). This is csh shell for FreeBSD. This mode is not covered by this Class. * cli mode (specific shell). The entire configuration is usual configured in this... | the_stack_v2_python_sparse | netdev/vendors/junos_like.py | maliciousgroup/netdev | train | 1 |
f6d09ba5285026059a92d7c290ee8e0645324433 | [
"self.canary = api\nupdate_interval = timedelta(seconds=30)\nsuper().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)",
"locations_by_id: dict[str, Location] = {}\nreadings_by_device_id: dict[str, ValuesView[Reading]] = {}\nfor location in self.canary.get_locations():\n location_id = locat... | <|body_start_0|>
self.canary = api
update_interval = timedelta(seconds=30)
super().__init__(hass, _LOGGER, name=DOMAIN, update_interval=update_interval)
<|end_body_0|>
<|body_start_1|>
locations_by_id: dict[str, Location] = {}
readings_by_device_id: dict[str, ValuesView[Reading]... | Class to manage fetching Canary data. | CanaryDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanaryDataUpdateCoordinator:
"""Class to manage fetching Canary data."""
def __init__(self, hass: HomeAssistant, *, api: Api) -> None:
"""Initialize global Canary data updater."""
<|body_0|>
def _update_data(self) -> CanaryData:
"""Fetch data from Canary via sync... | stack_v2_sparse_classes_75kplus_train_003477 | 2,098 | permissive | [
{
"docstring": "Initialize global Canary data updater.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, *, api: Api) -> None"
},
{
"docstring": "Fetch data from Canary via sync functions.",
"name": "_update_data",
"signature": "def _update_data(self) -> CanaryD... | 3 | stack_v2_sparse_classes_30k_train_019574 | Implement the Python class `CanaryDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Canary data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, api: Api) -> None: Initialize global Canary data updater.
- def _update_data(self) -> CanaryData: Fetch data... | Implement the Python class `CanaryDataUpdateCoordinator` described below.
Class description:
Class to manage fetching Canary data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, *, api: Api) -> None: Initialize global Canary data updater.
- def _update_data(self) -> CanaryData: Fetch data... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class CanaryDataUpdateCoordinator:
"""Class to manage fetching Canary data."""
def __init__(self, hass: HomeAssistant, *, api: Api) -> None:
"""Initialize global Canary data updater."""
<|body_0|>
def _update_data(self) -> CanaryData:
"""Fetch data from Canary via sync... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CanaryDataUpdateCoordinator:
"""Class to manage fetching Canary data."""
def __init__(self, hass: HomeAssistant, *, api: Api) -> None:
"""Initialize global Canary data updater."""
self.canary = api
update_interval = timedelta(seconds=30)
super().__init__(hass, _LOGGER, nam... | the_stack_v2_python_sparse | homeassistant/components/canary/coordinator.py | home-assistant/core | train | 35,501 |
e46aeeac4139f18a4b92ab9a9a4fc2fa46c01745 | [
"self.dic = {}\nfor i, w in enumerate(words):\n self.dic[w] = self.dic.get(w, []) + [i]\nself.max_len = len(words)",
"i1 = i2 = 0\ndistance = self.max_len\nwhile i1 < len(self.dic[word1]) and i2 < len(self.dic[word2]):\n distance = min(distance, abs(self.dic[word1][i1] - self.dic[word2][i2]))\n if self.d... | <|body_start_0|>
self.dic = {}
for i, w in enumerate(words):
self.dic[w] = self.dic.get(w, []) + [i]
self.max_len = len(words)
<|end_body_0|>
<|body_start_1|>
i1 = i2 = 0
distance = self.max_len
while i1 < len(self.dic[word1]) and i2 < len(self.dic[word2]):
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_003478 | 1,779 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | stack_v2_sparse_classes_30k_train_012361 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 80a604cc09d5d2d62dd05157d8b829de675e4404 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.dic = {}
for i, w in enumerate(words):
self.dic[w] = self.dic.get(w, []) + [i]
self.max_len = len(words)
def shortest(self, word1, word2):
""... | the_stack_v2_python_sparse | Algorithm/244_ShortestWordDistanceII.py | lingtianwan/Leetcode2 | train | 0 | |
1e0cb55544bf5d06761e6d89e3766d8483ad0580 | [
"question = Question.objects.all()\nserializer = QuestionSerializer(question, many=True)\nreturn Response(serializer.data, status=200)",
"serializer = QuestionSerializer(data=self.request.data)\nif serializer.is_valid():\n serializer.save(self.request.user)\n return Response(status=201)\nreturn Response(ser... | <|body_start_0|>
question = Question.objects.all()
serializer = QuestionSerializer(question, many=True)
return Response(serializer.data, status=200)
<|end_body_0|>
<|body_start_1|>
serializer = QuestionSerializer(data=self.request.data)
if serializer.is_valid():
seri... | Questions API | QuestionAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
<|body_0|>
def create(self, *args, **kwargs):
"""creates a question"""
<|body_1|>
def details(self, *args, **kwargs):
"""view details of a question"""... | stack_v2_sparse_classes_75kplus_train_003479 | 1,648 | no_license | [
{
"docstring": "lists all questions",
"name": "list",
"signature": "def list(self, *args, **kwargs)"
},
{
"docstring": "creates a question",
"name": "create",
"signature": "def create(self, *args, **kwargs)"
},
{
"docstring": "view details of a question",
"name": "details",
... | 4 | stack_v2_sparse_classes_30k_train_042314 | Implement the Python class `QuestionAPI` described below.
Class description:
Questions API
Method signatures and docstrings:
- def list(self, *args, **kwargs): lists all questions
- def create(self, *args, **kwargs): creates a question
- def details(self, *args, **kwargs): view details of a question
- def edit(self, ... | Implement the Python class `QuestionAPI` described below.
Class description:
Questions API
Method signatures and docstrings:
- def list(self, *args, **kwargs): lists all questions
- def create(self, *args, **kwargs): creates a question
- def details(self, *args, **kwargs): view details of a question
- def edit(self, ... | 4795bbc9ea90badc5e2a6804110b3a21f4cab9ce | <|skeleton|>
class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
<|body_0|>
def create(self, *args, **kwargs):
"""creates a question"""
<|body_1|>
def details(self, *args, **kwargs):
"""view details of a question"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionAPI:
"""Questions API"""
def list(self, *args, **kwargs):
"""lists all questions"""
question = Question.objects.all()
serializer = QuestionSerializer(question, many=True)
return Response(serializer.data, status=200)
def create(self, *args, **kwargs):
"... | the_stack_v2_python_sparse | questions/views.py | Swiftkind/qna | train | 0 |
8a685681bfe46a305a053b9d858f3667a50f2d14 | [
"super().__init__()\nself.fc = nn.Linear(768, num_labels)\nself.loss_fn = FocalLoss()",
"x = data['x']\ny = data['y']\nlogits = self.fc(x)\nif y is not None:\n loss = self.loss_fn.forward(torch.reshape(logits, [-1, logits.shape[-1]]), y.view(-1))\nelse:\n loss = None\nreturn {'loss': loss, 'logits': logits,... | <|body_start_0|>
super().__init__()
self.fc = nn.Linear(768, num_labels)
self.loss_fn = FocalLoss()
<|end_body_0|>
<|body_start_1|>
x = data['x']
y = data['y']
logits = self.fc(x)
if y is not None:
loss = self.loss_fn.forward(torch.reshape(logits, [-1... | TaskModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskModel:
def __init__(self, num_labels, dropout_prob, bret_pretrainded_path):
""":param num_labels: :param dropout_prob: :param bret_pretrainded_path:"""
<|body_0|>
def forward(self, data):
""":param data: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_75kplus_train_003480 | 5,862 | permissive | [
{
"docstring": ":param num_labels: :param dropout_prob: :param bret_pretrainded_path:",
"name": "__init__",
"signature": "def __init__(self, num_labels, dropout_prob, bret_pretrainded_path)"
},
{
"docstring": ":param data: :return:",
"name": "forward",
"signature": "def forward(self, dat... | 2 | stack_v2_sparse_classes_30k_train_033052 | Implement the Python class `TaskModel` described below.
Class description:
Implement the TaskModel class.
Method signatures and docstrings:
- def __init__(self, num_labels, dropout_prob, bret_pretrainded_path): :param num_labels: :param dropout_prob: :param bret_pretrainded_path:
- def forward(self, data): :param dat... | Implement the Python class `TaskModel` described below.
Class description:
Implement the TaskModel class.
Method signatures and docstrings:
- def __init__(self, num_labels, dropout_prob, bret_pretrainded_path): :param num_labels: :param dropout_prob: :param bret_pretrainded_path:
- def forward(self, data): :param dat... | 9aa9d7a50ada1deb653d295dd8a7fe46321b9094 | <|skeleton|>
class TaskModel:
def __init__(self, num_labels, dropout_prob, bret_pretrainded_path):
""":param num_labels: :param dropout_prob: :param bret_pretrainded_path:"""
<|body_0|>
def forward(self, data):
""":param data: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskModel:
def __init__(self, num_labels, dropout_prob, bret_pretrainded_path):
""":param num_labels: :param dropout_prob: :param bret_pretrainded_path:"""
super().__init__()
self.fc = nn.Linear(768, num_labels)
self.loss_fn = FocalLoss()
def forward(self, data):
"... | the_stack_v2_python_sparse | src/nlp/classification/tf1/traditional_cls/_run_bert.py | wu-uw/OpenCompetition | train | 0 | |
0981f7037fda1f107f407df3c68ffd7d8b6fa4a8 | [
"self.cacheMap = {}\nself.keyList = []\nself.maxLen = capacity",
"value = self.cacheMap.get(key)\nif value != None and self.keyList[0] != key:\n index = self.keyList.index(key)\n self.keyList.pop(index)\n self.keyList.insert(0, key)\nvalue = value if value != None else -1\nreturn value",
"if self.cache... | <|body_start_0|>
self.cacheMap = {}
self.keyList = []
self.maxLen = capacity
<|end_body_0|>
<|body_start_1|>
value = self.cacheMap.get(key)
if value != None and self.keyList[0] != key:
index = self.keyList.index(key)
self.keyList.pop(index)
se... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus_train_003481 | 1,193 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_041819 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | b03528bfc954e8c402d66e84b397ec3b065ddb84 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cacheMap = {}
self.keyList = []
self.maxLen = capacity
def get(self, key):
""":type key: int :rtype: int"""
value = self.cacheMap.get(key)
if value != None and self.keyList[0] !=... | the_stack_v2_python_sparse | bytedance/LRU缓存机制/Solution.py | wudc5/LeetCode | train | 0 | |
972a8971c70b19e856bc81b7b24a0d70a6743b6b | [
"super(TemporalConvNet, self).__init__()\nself.C = C\nself.mask_nonlinear = mask_nonlinear\nlayer_norm = ChannelwiseLayerNorm(N)\nbottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False)\nrepeats = []\nfor r in range(R):\n blocks = []\n for x in range(X):\n dilation = 2 ** x\n padding = (P - 1) * dil... | <|body_start_0|>
super(TemporalConvNet, self).__init__()
self.C = C
self.mask_nonlinear = mask_nonlinear
layer_norm = ChannelwiseLayerNorm(N)
bottleneck_conv1x1 = nn.Conv1d(N, B, 1, bias=False)
repeats = []
for r in range(R):
blocks = []
fo... | TemporalConvNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional ... | stack_v2_sparse_classes_75kplus_train_003482 | 15,161 | no_license | [
{
"docstring": "Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Number of convolutional blocks in each repeat R: Number of repeats C: Number of speakers norm_type: BN, gLN, cLN ... | 2 | stack_v2_sparse_classes_30k_train_002261 | Implement the Python class `TemporalConvNet` described below.
Class description:
Implement the TemporalConvNet class.
Method signatures and docstrings:
- def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): Args: N: Number of filters in autoencoder B: Number of channels in bo... | Implement the Python class `TemporalConvNet` described below.
Class description:
Implement the TemporalConvNet class.
Method signatures and docstrings:
- def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'): Args: N: Number of filters in autoencoder B: Number of channels in bo... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemporalConvNet:
def __init__(self, N, B, H, P, X, R, C, norm_type='gLN', causal=False, mask_nonlinear='relu'):
"""Args: N: Number of filters in autoencoder B: Number of channels in bottleneck 1 × 1-conv block H: Number of channels in convolutional blocks P: Kernel size in convolutional blocks X: Numb... | the_stack_v2_python_sparse | generated/test_kaituoxu_Conv_TasNet.py | jansel/pytorch-jit-paritybench | train | 35 | |
eb421963a3fa52ab88a96bef236872e18ace6930 | [
"if not re.match('.+/v[0-1](\\\\.[0-9]+)*/?$', v):\n raise ValueError(f'url MUST be a versioned base URL. It is: {v}')\nreturn v",
"url_version = values['url'].split('/')[-2 if values['url'].endswith('/') else -1].replace('v', '')\nurl_version = tuple((int(val) for val in url_version.split('-')[0].split('+')[0... | <|body_start_0|>
if not re.match('.+/v[0-1](\\.[0-9]+)*/?$', v):
raise ValueError(f'url MUST be a versioned base URL. It is: {v}')
return v
<|end_body_0|>
<|body_start_1|>
url_version = values['url'].split('/')[-2 if values['url'].endswith('/') else -1].replace('v', '')
url_... | A JSON object containing information about an available API version | AvailableApiVersion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvailableApiVersion:
"""A JSON object containing information about an available API version"""
def url_must_be_versioned_base_url(cls, v):
"""The URL must be a valid versioned Base URL"""
<|body_0|>
def crosscheck_url_and_version(cls, values):
"""Check that URL v... | stack_v2_sparse_classes_75kplus_train_003483 | 4,217 | permissive | [
{
"docstring": "The URL must be a valid versioned Base URL",
"name": "url_must_be_versioned_base_url",
"signature": "def url_must_be_versioned_base_url(cls, v)"
},
{
"docstring": "Check that URL version and API version are compatible.",
"name": "crosscheck_url_and_version",
"signature": ... | 2 | null | Implement the Python class `AvailableApiVersion` described below.
Class description:
A JSON object containing information about an available API version
Method signatures and docstrings:
- def url_must_be_versioned_base_url(cls, v): The URL must be a valid versioned Base URL
- def crosscheck_url_and_version(cls, valu... | Implement the Python class `AvailableApiVersion` described below.
Class description:
A JSON object containing information about an available API version
Method signatures and docstrings:
- def url_must_be_versioned_base_url(cls, v): The URL must be a valid versioned Base URL
- def crosscheck_url_and_version(cls, valu... | a9840269d11ca3f32e5b7d1547e5a49647656264 | <|skeleton|>
class AvailableApiVersion:
"""A JSON object containing information about an available API version"""
def url_must_be_versioned_base_url(cls, v):
"""The URL must be a valid versioned Base URL"""
<|body_0|>
def crosscheck_url_and_version(cls, values):
"""Check that URL v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AvailableApiVersion:
"""A JSON object containing information about an available API version"""
def url_must_be_versioned_base_url(cls, v):
"""The URL must be a valid versioned Base URL"""
if not re.match('.+/v[0-1](\\.[0-9]+)*/?$', v):
raise ValueError(f'url MUST be a versione... | the_stack_v2_python_sparse | optimade/models/baseinfo.py | Materials-Consortia/optimade-python-tools | train | 54 |
79eaabcc76d1ada302cc2292c9b87bab87c8b10f | [
"self.numberOfSimulations = numberOfSimulations\nself.maturity = maturity\nself.numberOfIntervals = numberOfIntervals\nself.localFloor = localFloor\nself.localCap = localCap\nself.globalFloor = globalFloor\nself.globalCap = globalCap\nself.sigma = sigma\nself.r = r",
"initialValue = 1\nmaturityOfTheCallOptions = ... | <|body_start_0|>
self.numberOfSimulations = numberOfSimulations
self.maturity = maturity
self.numberOfIntervals = numberOfIntervals
self.localFloor = localFloor
self.localCap = localCap
self.globalFloor = globalFloor
self.globalCap = globalCap
self.sigma =... | This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_t, 0 \\le t \\le T, where T is the maturity of the option. The payoff of the Cliquet option with ... | FasterControlVariatesCliquetBS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FasterControlVariatesCliquetBS:
"""This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_t, 0 \\le t \\le T, where T is the matu... | stack_v2_sparse_classes_75kplus_train_003484 | 8,732 | no_license | [
{
"docstring": "Parameters ---------- numberOfSimulations : int the number of simulated trajectories of the returns maturity : float the maturity of the option. It is also the final time of the global time interval, i.e., the last time of the partition numberOfIntervals : int the number of time intervals in the... | 3 | stack_v2_sparse_classes_30k_train_031610 | Implement the Python class `FasterControlVariatesCliquetBS` described below.
Class description:
This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_... | Implement the Python class `FasterControlVariatesCliquetBS` described below.
Class description:
This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_... | 4314e47509b05523ee547be9ba6970870f9bcde0 | <|skeleton|>
class FasterControlVariatesCliquetBS:
"""This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_t, 0 \\le t \\le T, where T is the matu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FasterControlVariatesCliquetBS:
"""This class is designed to compute the payoff of a Cliquet option written on a Black-Scholes model, with control variates. In particular, the underlying of the option is the log-normal process dX_t = r X_t dt + sigma X_t dW_t, 0 \\le t \\le T, where T is the maturity of the o... | the_stack_v2_python_sparse | Computational-finance-python/montecarlovariancereduction/controlvariates/fasterControlVariatesCliquetBS.py | AndreaMaz/Computational-finance-python | train | 1 |
f54c70bccf53b3a61009efc4e4c59dec03e03fc0 | [
"kwds['channels'] = channels\nsuper().__init__(**kwds)\nfor channel in self.channels:\n channel[2].setValue(1.05)\n channel[2].setMaximum(9.9)",
"active = []\nincrement = []\nfor i, channel in enumerate(self.channels):\n if self.which_checked[i] and frame_number % channel[3].value() == 0:\n active... | <|body_start_0|>
kwds['channels'] = channels
super().__init__(**kwds)
for channel in self.channels:
channel[2].setValue(1.05)
channel[2].setMaximum(9.9)
<|end_body_0|>
<|body_start_1|>
active = []
increment = []
for i, channel in enumerate(self.ch... | Channels class for exponential progression. | ExponentialChannels | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExponentialChannels:
"""Channels class for exponential progression."""
def __init__(self, channels=None, **kwds):
"""This is basically the same as for MathChannels. It also specifies the current and maximum value of the increment spin box."""
<|body_0|>
def handleNewFram... | stack_v2_sparse_classes_75kplus_train_003485 | 25,535 | permissive | [
{
"docstring": "This is basically the same as for MathChannels. It also specifies the current and maximum value of the increment spin box.",
"name": "__init__",
"signature": "def __init__(self, channels=None, **kwds)"
},
{
"docstring": "Called when we get a new frame from the camera. Returns the... | 2 | stack_v2_sparse_classes_30k_train_028206 | Implement the Python class `ExponentialChannels` described below.
Class description:
Channels class for exponential progression.
Method signatures and docstrings:
- def __init__(self, channels=None, **kwds): This is basically the same as for MathChannels. It also specifies the current and maximum value of the increme... | Implement the Python class `ExponentialChannels` described below.
Class description:
Channels class for exponential progression.
Method signatures and docstrings:
- def __init__(self, channels=None, **kwds): This is basically the same as for MathChannels. It also specifies the current and maximum value of the increme... | f185df3d23b231a26c46f33b0b91fffa86356dc4 | <|skeleton|>
class ExponentialChannels:
"""Channels class for exponential progression."""
def __init__(self, channels=None, **kwds):
"""This is basically the same as for MathChannels. It also specifies the current and maximum value of the increment spin box."""
<|body_0|>
def handleNewFram... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExponentialChannels:
"""Channels class for exponential progression."""
def __init__(self, channels=None, **kwds):
"""This is basically the same as for MathChannels. It also specifies the current and maximum value of the increment spin box."""
kwds['channels'] = channels
super().__... | the_stack_v2_python_sparse | storm_control/hal4000/progressions/progressions.py | ZhuangLab/storm-control | train | 54 |
2454c516e0403bbb8b9583b6fc8dd32c3b7c4e34 | [
"super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))\nself.game_icons: dict[int, str] = {}\nself.player_interface: INTMethod = None\nself.user_interface: INTMethod = None\nsteam.api.key.set(self.config_entry.data[CONF_API_KEY])",
"accounts = self.config_entry.options[CON... | <|body_start_0|>
super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))
self.game_icons: dict[int, str] = {}
self.player_interface: INTMethod = None
self.user_interface: INTMethod = None
steam.api.key.set(self.config_entry.data[CONF_API_KEY... | Data update coordinator for the Steam integration. | SteamDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
<|body_0|>
def _update(self) -> dict[str, dict[str, str | int]]:
"""Fetch data from API endpoin... | stack_v2_sparse_classes_75kplus_train_003486 | 2,808 | permissive | [
{
"docstring": "Initialize the coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Fetch data from API endpoint.",
"name": "_update",
"signature": "def _update(self) -> dict[str, dict[str, str | int]]"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_048786 | Implement the Python class `SteamDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the Steam integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize the coordinator.
- def _update(self) -> dict[str, dict[str, str | int]]: Fetch ... | Implement the Python class `SteamDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the Steam integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize the coordinator.
- def _update(self) -> dict[str, dict[str, str | int]]: Fetch ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
<|body_0|>
def _update(self) -> dict[str, dict[str, str | int]]:
"""Fetch data from API endpoin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SteamDataUpdateCoordinator:
"""Data update coordinator for the Steam integration."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the coordinator."""
super().__init__(hass=hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=30))
self.game_icons: d... | the_stack_v2_python_sparse | homeassistant/components/steam_online/coordinator.py | home-assistant/core | train | 35,501 |
2404ebd5c6f9e9c2780e5053e2d0f2b257bd066f | [
"if not root:\n return []\nres = []\nq = deque()\nq.append(root)\nwhile q:\n node = q.popleft()\n if node is None:\n res.append('null')\n else:\n res.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\nreturn res",
"if not data or len(data) == 0:\n return... | <|body_start_0|>
if not root:
return []
res = []
q = deque()
q.append(root)
while q:
node = q.popleft()
if node is None:
res.append('null')
else:
res.append(str(node.val))
q.append(nod... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_003487 | 1,324 | 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_023636 | 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:... | 0d5dd2913931ca655c54f15f4857c27cd5124c2c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return []
res = []
q = deque()
q.append(root)
while q:
node = q.popleft()
if node is None:
... | the_stack_v2_python_sparse | LeetCode/python/297_二叉树的序列化与反序列化.py | geroge-gao/Algorithm | train | 28 | |
8e4a01dee87eba5e3bc2f6cc2e4ec5eec5e4511e | [
"t = _TimeEvent()\nt.type = 'once'\nt.next = datetime.datetime.now() + delay\nt.action = action\nself.time_events.append(t)",
"t = _TimeEvent()\nt.type = 'periodic'\nif delay:\n t.next = datetime.datetime.now() + delay\nelse:\n t.next = datetime.datetime.now() + interval\nt.interval = interval\nt.action = a... | <|body_start_0|>
t = _TimeEvent()
t.type = 'once'
t.next = datetime.datetime.now() + delay
t.action = action
self.time_events.append(t)
<|end_body_0|>
<|body_start_1|>
t = _TimeEvent()
t.type = 'periodic'
if delay:
t.next = datetime.datetime.n... | Class to manage timed events | TimeManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeManager:
"""Class to manage timed events"""
def register_once(self, action, delay):
""":param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register an event to be executed once"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_003488 | 2,705 | no_license | [
{
"docstring": ":param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register an event to be executed once",
"name": "register_once",
"signature": "def register_once(self, action, delay)"
},
{
"docstring": ":param action: ... | 4 | stack_v2_sparse_classes_30k_train_005624 | Implement the Python class `TimeManager` described below.
Class description:
Class to manage timed events
Method signatures and docstrings:
- def register_once(self, action, delay): :param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register ... | Implement the Python class `TimeManager` described below.
Class description:
Class to manage timed events
Method signatures and docstrings:
- def register_once(self, action, delay): :param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register ... | 3e65f20adbc29d38529f41a4e839c554be3c7691 | <|skeleton|>
class TimeManager:
"""Class to manage timed events"""
def register_once(self, action, delay):
""":param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register an event to be executed once"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TimeManager:
"""Class to manage timed events"""
def register_once(self, action, delay):
""":param action: function to be executed :type action: function :param delay: Delay until action :type delay: datetime.timedelta Register an event to be executed once"""
t = _TimeEvent()
t.typ... | the_stack_v2_python_sparse | src/timemanager.py | varesa/mustikkaBot | train | 0 |
a94a00fd74ec130e764470ccaaf949890bd88055 | [
"test = '2\\naa'\nd = Good(test)\nself.assertEqual(d.n, 2)\nself.assertEqual(d.s, ['a', 'a'])\nself.assertEqual(Good(test).calculate(), '1')\ntest = '4\\nkoko'\nself.assertEqual(Good(test).calculate(), '2')\ntest = '5\\nmurat'\nself.assertEqual(Good(test).calculate(), '0')\ntest = '30\\ndasdsadasdasdasdsadasdsadasd... | <|body_start_0|>
test = '2\naa'
d = Good(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.s, ['a', 'a'])
self.assertEqual(Good(test).calculate(), '1')
test = '4\nkoko'
self.assertEqual(Good(test).calculate(), '2')
test = '5\nmurat'
self.assertEqua... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Good class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = '2\naa'
d = Good(test)
self.assertEqual(d.n, 2)
... | stack_v2_sparse_classes_75kplus_train_003489 | 3,030 | permissive | [
{
"docstring": "Good class testing",
"name": "test_single_test",
"signature": "def test_single_test(self)"
},
{
"docstring": "Timelimit testing",
"name": "time_limit_test",
"signature": "def time_limit_test(self, nmax)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012454 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Good class testing
- def time_limit_test(self, nmax): Timelimit testing | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Good class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""G... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Good class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class unitTests:
def test_single_test(self):
"""Good class testing"""
test = '2\naa'
d = Good(test)
self.assertEqual(d.n, 2)
self.assertEqual(d.s, ['a', 'a'])
self.assertEqual(Good(test).calculate(), '1')
test = '4\nkoko'
self.assertEqual(Good(test).ca... | the_stack_v2_python_sparse | codeforces/672B_good.py | snsokolov/contests | train | 1 | |
4bb4ae370500f23661d775f26b317f948d101dba | [
"Halo().info(Style.BRIGHT + Fore.GREEN + 'Displaying wordcloud.')\nprint()\nplt.show()",
"filename = GetPath.name_file(analytics_dir, scrape_file[0])\nsplit_path = list(Path(filename).parts)\nsplit_filename = split_path[-1].split('.')\nsplit_filename[-1] = scrape_file[-1]\nsplit_path[-1] = '.'.join(split_filename... | <|body_start_0|>
Halo().info(Style.BRIGHT + Fore.GREEN + 'Displaying wordcloud.')
print()
plt.show()
<|end_body_0|>
<|body_start_1|>
filename = GetPath.name_file(analytics_dir, scrape_file[0])
split_path = list(Path(filename).parts)
split_filename = split_path[-1].split(... | Methods for either saving or displaying the wordcloud. | FinalizeWordcloud | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinalizeWordcloud:
"""Methods for either saving or displaying the wordcloud."""
def show_wordcloud(self, plt):
"""Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None"""
<|body_0|>
def save_wordcloud(self, analyt... | stack_v2_sparse_classes_75kplus_train_003490 | 5,148 | permissive | [
{
"docstring": "Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None",
"name": "show_wordcloud",
"signature": "def show_wordcloud(self, plt)"
},
{
"docstring": "Save wordcloud to file. Calls a public method from an external module: GetPa... | 2 | stack_v2_sparse_classes_30k_train_033515 | Implement the Python class `FinalizeWordcloud` described below.
Class description:
Methods for either saving or displaying the wordcloud.
Method signatures and docstrings:
- def show_wordcloud(self, plt): Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None
-... | Implement the Python class `FinalizeWordcloud` described below.
Class description:
Methods for either saving or displaying the wordcloud.
Method signatures and docstrings:
- def show_wordcloud(self, plt): Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None
-... | 9f8cf3a3adb9aa5079dfc7bfd7832b53358ee40f | <|skeleton|>
class FinalizeWordcloud:
"""Methods for either saving or displaying the wordcloud."""
def show_wordcloud(self, plt):
"""Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None"""
<|body_0|>
def save_wordcloud(self, analyt... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FinalizeWordcloud:
"""Methods for either saving or displaying the wordcloud."""
def show_wordcloud(self, plt):
"""Display wordcloud. Parameters ---------- plt: matplotlib.pyplot matplotlib.pyplot instance Returns ------- None"""
Halo().info(Style.BRIGHT + Fore.GREEN + 'Displaying wordclou... | the_stack_v2_python_sparse | urs/analytics/Wordcloud.py | shilezi/URS | train | 0 |
4edcb2410cb51abcc3350056649d5119ba099873 | [
"with FileAccess._game_lock:\n with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'r') as file:\n return function(file)",
"with FileAccess._game_lock:\n with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'w') as file:\n return function(... | <|body_start_0|>
with FileAccess._game_lock:
with open(os.path.join(os.path.dirname(__file__), '..', 'test_data', filename), 'r') as file:
return function(file)
<|end_body_0|>
<|body_start_1|>
with FileAccess._game_lock:
with open(os.path.join(os.path.dirname(__f... | Handles access of the data to prevent files from being accessed while already in use | FileAccess | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the ga... | stack_v2_sparse_classes_75kplus_train_003491 | 4,980 | no_license | [
{
"docstring": "Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the game table @precondition none @return the return value of the passed in function @param function The service attempting to read from the game table @param filena... | 6 | stack_v2_sparse_classes_30k_train_043736 | Implement the Python class `FileAccess` described below.
Class description:
Handles access of the data to prevent files from being accessed while already in use
Method signatures and docstrings:
- def read_game_table(function, filename): Executes the passed in function after thread obtains the lock and prevents other... | Implement the Python class `FileAccess` described below.
Class description:
Handles access of the data to prevent files from being accessed while already in use
Method signatures and docstrings:
- def read_game_table(function, filename): Executes the passed in function after thread obtains the lock and prevents other... | 7f3a4377ff2d3d81835aafad06c654a95f059353 | <|skeleton|>
class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the ga... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FileAccess:
"""Handles access of the data to prevent files from being accessed while already in use"""
def read_game_table(function, filename):
"""Executes the passed in function after thread obtains the lock and prevents other threads from reading or writing simultaneously to the game table @pre... | the_stack_v2_python_sparse | code/SteamScoutServer/src/dataupdates/fileaccess.py | TheMichaelJiles/SteamScout | train | 0 |
e81c250c6ea0a989d20010fbb48a4148de8f7cf2 | [
"for index, item in enumerate(nums):\n if item >= target:\n return index\nreturn index + 1",
"nums.append(target)\nnums.sort()\nreturn nums.index(target)",
"if not nums or len(nums) == 0:\n return 0\n\ndef binarySearch(a, b, nums, target):\n if a >= b:\n return a\n mid = a + (b - a) //... | <|body_start_0|>
for index, item in enumerate(nums):
if item >= target:
return index
return index + 1
<|end_body_0|>
<|body_start_1|>
nums.append(target)
nums.sort()
return nums.index(target)
<|end_body_1|>
<|body_start_2|>
if not nums or len... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchInsertFastInPython(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsertNaive(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def searchIns... | stack_v2_sparse_classes_75kplus_train_003492 | 1,607 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "searchInsertFastInPython",
"signature": "def searchInsertFastInPython(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "searchInsertNaive",
"signature": "de... | 4 | stack_v2_sparse_classes_30k_train_012876 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsertFastInPython(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def searchInsertNaive(self, nums, target): :type nums: List[int] :type tar... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchInsertFastInPython(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def searchInsertNaive(self, nums, target): :type nums: List[int] :type tar... | 9bf06e095b5eefe388d33afe0ac4bb702b6a96b4 | <|skeleton|>
class Solution:
def searchInsertFastInPython(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def searchInsertNaive(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
def searchIns... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def searchInsertFastInPython(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
for index, item in enumerate(nums):
if item >= target:
return index
return index + 1
def searchInsertNaive(self, nums, target):
... | the_stack_v2_python_sparse | Easy/SearchInsertPosition.py | JayWelborn/LeetCode | train | 0 | |
57012939da8c4e4fb58b3898592464800bdaab91 | [
"if type(data) is not np.ndarray or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nmean = np.mean(data, axis=1).reshape((data.shape[0], 1))\nself.mean = mean\nself.cov = np.matmul(data - self.mean,... | <|body_start_0|>
if type(data) is not np.ndarray or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
mean = np.mean(data, axis=1).reshape((data.shape[0], 1))
s... | Multinormal Class | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Multinormal Class"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message dat... | stack_v2_sparse_classes_75kplus_train_003493 | 1,942 | no_license | [
{
"docstring": "data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2D numpy.ndarray If n is less than 2, raise a ValueError with the ... | 2 | stack_v2_sparse_classes_30k_train_008531 | Implement the Python class `MultiNormal` described below.
Class description:
Multinormal Class
Method signatures and docstrings:
- def __init__(self, data): data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a... | Implement the Python class `MultiNormal` described below.
Class description:
Multinormal Class
Method signatures and docstrings:
- def __init__(self, data): data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class MultiNormal:
"""Multinormal Class"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message dat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""Multinormal Class"""
def __init__(self, data):
"""data is a numpy.ndarray of shape (d, n) containing the data set: n is the number of data points d is the number of dimensions in each data point If data is not a 2D numpy.ndarray, raise a TypeError with the message data must be a 2... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | Gaspela/holbertonschool-machine_learning | train | 0 |
2a3b979de8702bf98b57657893bd26e989f2df59 | [
"super(N3AggregationBase, self).__init__()\nself.k = k\nself.nnn = NeuralNearestNeighbors(k, temp_opt=temp_opt)",
"b, n, f = x.shape\nm, e = ye.shape[1:]\no = I.shape[2]\nk = self.k\nassert (b, n, e) == xe.shape\nassert (b, m, e) == ye.shape\nassert (b, m, o) == I.shape\nD = compute_distances(xe, ye, I, train=sel... | <|body_start_0|>
super(N3AggregationBase, self).__init__()
self.k = k
self.nnn = NeuralNearestNeighbors(k, temp_opt=temp_opt)
<|end_body_0|>
<|body_start_1|>
b, n, f = x.shape
m, e = ye.shape[1:]
o = I.shape[2]
k = self.k
assert (b, n, e) == xe.shape
... | Domain agnostic base class for computing neural nearest neighbors | N3AggregationBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class N3AggregationBase:
"""Domain agnostic base class for computing neural nearest neighbors"""
def __init__(self, k, temp_opt={}):
""":param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperatures, see `NeuralNearestNeighbors`"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_003494 | 12,937 | permissive | [
{
"docstring": ":param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperatures, see `NeuralNearestNeighbors`",
"name": "__init__",
"signature": "def __init__(self, k, temp_opt={})"
},
{
"docstring": ":param x: database items, shape BxNxF :param xe: embedding o... | 2 | stack_v2_sparse_classes_30k_train_012413 | Implement the Python class `N3AggregationBase` described below.
Class description:
Domain agnostic base class for computing neural nearest neighbors
Method signatures and docstrings:
- def __init__(self, k, temp_opt={}): :param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperature... | Implement the Python class `N3AggregationBase` described below.
Class description:
Domain agnostic base class for computing neural nearest neighbors
Method signatures and docstrings:
- def __init__(self, k, temp_opt={}): :param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperature... | 067bfb007930ad4fb9012b7c50f2fdbdaa6d1980 | <|skeleton|>
class N3AggregationBase:
"""Domain agnostic base class for computing neural nearest neighbors"""
def __init__(self, k, temp_opt={}):
""":param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperatures, see `NeuralNearestNeighbors`"""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class N3AggregationBase:
"""Domain agnostic base class for computing neural nearest neighbors"""
def __init__(self, k, temp_opt={}):
""":param k: Number of neighbor volumes to compute :param temp_opt: options for handling temperatures, see `NeuralNearestNeighbors`"""
super(N3AggregationBase, se... | the_stack_v2_python_sparse | model/n3net/non_local.py | IDKiro/denoisers | train | 5 |
9fbecb529d70108d30831ec25cef202c9c063aaa | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn IdentityUserFlowAttributeAssignment()",
"from .entity import Entity\nfrom .identity_user_flow_attribute import IdentityUserFlowAttribute\nfrom .identity_user_flow_attribute_input_type import IdentityUserFlowAttributeInputType\nfrom .us... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return IdentityUserFlowAttributeAssignment()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .identity_user_flow_attribute import IdentityUserFlowAttribute
from .identit... | IdentityUserFlowAttributeAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_75kplus_train_003495 | 4,693 | 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: IdentityUserFlowAttributeAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_fr... | 3 | stack_v2_sparse_classes_30k_train_002281 | Implement the Python class `IdentityUserFlowAttributeAssignment` described below.
Class description:
Implement the IdentityUserFlowAttributeAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment: Creates a ... | Implement the Python class `IdentityUserFlowAttributeAssignment` described below.
Class description:
Implement the IdentityUserFlowAttributeAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment: Creates a ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IdentityUserFlowAttributeAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> IdentityUserFlowAttributeAssignment:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/identity_user_flow_attribute_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
44883de0f086ca3e35d0cd22fe3d79680a811be3 | [
"super().__init__(parent, **options)\nself.imgdir = imgdir\nself.bgcolor = options.get('bg', self['bg'])\nself.var = tk.StringVar()\nself.values = [('jednoruční znak', 'single hand'), ('obě ruce stejný tvar', 'both the same'), ('tvar pasivní ruky', 'passive hand')]\nself.pady = 6\nself.makeWidgets()",
"self.colum... | <|body_start_0|>
super().__init__(parent, **options)
self.imgdir = imgdir
self.bgcolor = options.get('bg', self['bg'])
self.var = tk.StringVar()
self.values = [('jednoruční znak', 'single hand'), ('obě ruce stejný tvar', 'both the same'), ('tvar pasivní ruky', 'passive hand')]
... | A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific radiobutton is selected. | RadioFrm | [
"CC-BY-4.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadioFrm:
"""A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific radiobutton is selected."""
def __in... | stack_v2_sparse_classes_75kplus_train_003496 | 2,725 | permissive | [
{
"docstring": "Initialize a RadioFrm object. Arguments: parent: a parent tkinter widget imgdir (str): a path to the directory with images",
"name": "__init__",
"signature": "def __init__(self, parent, imgdir, **options)"
},
{
"docstring": "Create radiobuttons and a frame for selecting passive h... | 3 | null | Implement the Python class `RadioFrm` described below.
Class description:
A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific ra... | Implement the Python class `RadioFrm` described below.
Class description:
A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific ra... | af73e9d18c5ffd928bd0140e2fa2c51ae58940ae | <|skeleton|>
class RadioFrm:
"""A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific radiobutton is selected."""
def __in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RadioFrm:
"""A frame with three radiobuttons for selecting the type of the sign. Apart from the radiobuttons, there is also a frame for selecting a handshape of a passive hand. This frame is 'active' (enabled to be used by the user) only when one specific radiobutton is selected."""
def __init__(self, pa... | the_stack_v2_python_sparse | dictionary/radio_buttons.py | katerinazuzana/sign-language-dictionary | train | 0 |
ba3a5f1c9813e9546e496c36725bcad3ed6aa44c | [
"self.cycletime = datetime(2017, 1, 10, 6)\ncube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=datetime(2017, 1, 10, 3))\ntime_points = [1484038800, 1484046000, 1484053200]\ncube_uk_det = add_coordinate(cube_uk_det, time_points, 'time', dtype=np.int64, coord_units... | <|body_start_0|>
self.cycletime = datetime(2017, 1, 10, 6)
cube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=datetime(2017, 1, 10, 3))
time_points = [1484038800, 1484046000, 1484053200]
cube_uk_det = add_coordinate(cube_uk_det, time_po... | Test the unify_cycletime function. | Test_unify_cycletime | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_unify_cycletime:
"""Test the unify_cycletime function."""
def setUp(self):
"""Set up a UK deterministic cube for testing."""
<|body_0|>
def test_cubelist_input(self):
"""Test when supplying a cubelist as input containing cubes representing UK deterministic a... | stack_v2_sparse_classes_75kplus_train_003497 | 20,564 | permissive | [
{
"docstring": "Set up a UK deterministic cube for testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test when supplying a cubelist as input containing cubes representing UK deterministic and UK ensemble model configuration and unifying the forecast_reference_time, so... | 4 | stack_v2_sparse_classes_30k_train_021392 | Implement the Python class `Test_unify_cycletime` described below.
Class description:
Test the unify_cycletime function.
Method signatures and docstrings:
- def setUp(self): Set up a UK deterministic cube for testing.
- def test_cubelist_input(self): Test when supplying a cubelist as input containing cubes representi... | Implement the Python class `Test_unify_cycletime` described below.
Class description:
Test the unify_cycletime function.
Method signatures and docstrings:
- def setUp(self): Set up a UK deterministic cube for testing.
- def test_cubelist_input(self): Test when supplying a cubelist as input containing cubes representi... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_unify_cycletime:
"""Test the unify_cycletime function."""
def setUp(self):
"""Set up a UK deterministic cube for testing."""
<|body_0|>
def test_cubelist_input(self):
"""Test when supplying a cubelist as input containing cubes representing UK deterministic a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_unify_cycletime:
"""Test the unify_cycletime function."""
def setUp(self):
"""Set up a UK deterministic cube for testing."""
self.cycletime = datetime(2017, 1, 10, 6)
cube_uk_det = set_up_variable_cube(np.full((4, 4), 273.15, dtype=np.float32), time=self.cycletime, frt=dateti... | the_stack_v2_python_sparse | improver_tests/metadata/test_forecast_times.py | metoppv/improver | train | 101 |
f956ab56d187f07cb3bc4e117798eb0ef42dc2ef | [
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nif n == 2 or n == 3:\n return max(nums)\nreturn max(self.rob1(nums[:n - 1]), self.rob1(nums[1:]))",
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nif n == 2:\n return max(nums)\nelse:\n dp = [0] * n\n ... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
if n == 2 or n == 3:
return max(nums)
return max(self.rob1(nums[:n - 1]), self.rob1(nums[1:]))
<|end_body_0|>
<|body_start_1|>
n = len(nums)
if n == 0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if n == 0:
return 0
... | stack_v2_sparse_classes_75kplus_train_003498 | 837 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob1",
"signature": "def rob1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026557 | 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 rob1(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 rob1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
"... | 15f012927dc34b5d751af6633caa5e8882d26ff7 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
if n == 2 or n == 3:
return max(nums)
return max(self.rob1(nums[:n - 1]), self.rob1(nums[1:]))
... | the_stack_v2_python_sparse | python/213.HouseRobberII.py | MaxPoon/Leetcode | train | 15 | |
0717caac7c5339ec504a6557b87e848edc7b8832 | [
"self.pre = pre\nself._n = n\nself.top = Toplevel()\nself.top.focus_set()\nself.top.grab_set()\nself._make_widgets()",
"self._entries = []\nfor i in range(self._n):\n _frame = Frame(self.top)\n _frame.pack(side=TOP, fill=X)\n Label(_frame, text='a[{}]: '.format(i), font=('arial', '16', 'bold')).pack(side... | <|body_start_0|>
self.pre = pre
self._n = n
self.top = Toplevel()
self.top.focus_set()
self.top.grab_set()
self._make_widgets()
<|end_body_0|>
<|body_start_1|>
self._entries = []
for i in range(self._n):
_frame = Frame(self.top)
_f... | Діалогове вікно. Містить n полів для введення компонент вектора. | Dialog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
<|body_0|>
def _make_widgets(self):
"""Сворення віджетів"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_003499 | 5,953 | no_license | [
{
"docstring": "Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало",
"name": "__init__",
"signature": "def __init__(self, n, pre)"
},
{
"docstring": "Сворення віджетів",
"name": "_make_widgets",
"signature": "def _make_widgets(self)"
},
{
"docstring": "Обробка ... | 3 | stack_v2_sparse_classes_30k_train_023308 | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно. Містить n полів для введення компонент вектора.
Method signatures and docstrings:
- def __init__(self, n, pre): Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало
- def _make_widgets(self): Сворення віджетів
- ... | Implement the Python class `Dialog` described below.
Class description:
Діалогове вікно. Містить n полів для введення компонент вектора.
Method signatures and docstrings:
- def __init__(self, n, pre): Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало
- def _make_widgets(self): Сворення віджетів
- ... | e44bf2b535b34bc31fb323c20901a77b0b3072f2 | <|skeleton|>
class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
<|body_0|>
def _make_widgets(self):
"""Сворення віджетів"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dialog:
"""Діалогове вікно. Містить n полів для введення компонент вектора."""
def __init__(self, n, pre):
"""Ініціалізація :param n: к-ть компонент :param pre: вікно, яке визвало"""
self.pre = pre
self._n = n
self.top = Toplevel()
self.top.focus_set()
self... | the_stack_v2_python_sparse | dz_others/subject24_gui/t24_7.py | davendiy/ads_course2 | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.