blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2e62641b35c9ec779526a68adaa0907b9614eb65 | [
"count = 0\nfor i, v in enumerate(nums):\n if v == 0:\n count += 1\n elif count:\n nums[i - count] = v\nif count:\n nums[-count:] = [0] * count\nprint(nums)",
"j = 0\nfor i in range(len(nums)):\n if nums[i]:\n nums[j] = nums[i]\n j += 1"
] | <|body_start_0|>
count = 0
for i, v in enumerate(nums):
if v == 0:
count += 1
elif count:
nums[i - count] = v
if count:
nums[-count:] = [0] * count
print(nums)
<|end_body_0|>
<|body_start_1|>
j = 0
for i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""better way :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_016200 | 1,067 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self, nums: List[int]) -> None"
},
{
"docstring": "better way :param nums: :return:",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self, nums: List[int]) -> ... | 2 | stack_v2_sparse_classes_30k_train_000606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: better way :param nums: :re... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes2(self, nums: List[int]) -> None: better way :param nums: :re... | 0abc04bc44e6fedf6ce59e83dd37be5787b88a25 | <|skeleton|>
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes2(self, nums: List[int]) -> None:
"""better way :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
count = 0
for i, v in enumerate(nums):
if v == 0:
count += 1
elif count:
nums[i - count] = v
if count:
... | the_stack_v2_python_sparse | MoveZeroes.py | oratun/Py-LeetCode | train | 0 | |
19a783a67decbe5521a90b06ffcf91226b3b88d2 | [
"if not cls._instance:\n cls._instance = RedisAppStatus()\nreturn cls._instance",
"options = _load_redis_options()\nout = ''\nerr = ''\ntry:\n if 'requirepass' in options:\n LOG.info(_('Password is set running ping with password'))\n out, err = utils.execute_with_timeout(system.REDIS_CLI, '-a'... | <|body_start_0|>
if not cls._instance:
cls._instance = RedisAppStatus()
return cls._instance
<|end_body_0|>
<|body_start_1|>
options = _load_redis_options()
out = ''
err = ''
try:
if 'requirepass' in options:
LOG.info(_('Password i... | Handles all of the status updating for the redis guest agent. | RedisAppStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
<|body_0|>
def _get_actual_db_status(self):
"""Gets the actual status of the Redis instance First it attempts to ... | stack_v2_sparse_classes_36k_train_016201 | 10,076 | permissive | [
{
"docstring": "Gets an instance of the RedisAppStatus class.",
"name": "get",
"signature": "def get(cls)"
},
{
"docstring": "Gets the actual status of the Redis instance First it attempts to make a connection to the redis instance by making a PING request. If PING does not return PONG we do a p... | 2 | stack_v2_sparse_classes_30k_train_019667 | Implement the Python class `RedisAppStatus` described below.
Class description:
Handles all of the status updating for the redis guest agent.
Method signatures and docstrings:
- def get(cls): Gets an instance of the RedisAppStatus class.
- def _get_actual_db_status(self): Gets the actual status of the Redis instance ... | Implement the Python class `RedisAppStatus` described below.
Class description:
Handles all of the status updating for the redis guest agent.
Method signatures and docstrings:
- def get(cls): Gets an instance of the RedisAppStatus class.
- def _get_actual_db_status(self): Gets the actual status of the Redis instance ... | 8f200b73719b36a7ab2f8d651e46a8b6b55c9a77 | <|skeleton|>
class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
<|body_0|>
def _get_actual_db_status(self):
"""Gets the actual status of the Redis instance First it attempts to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedisAppStatus:
"""Handles all of the status updating for the redis guest agent."""
def get(cls):
"""Gets an instance of the RedisAppStatus class."""
if not cls._instance:
cls._instance = RedisAppStatus()
return cls._instance
def _get_actual_db_status(self):
... | the_stack_v2_python_sparse | trove/guestagent/datastore/redis/service.py | NeCTAR-RC/trove | train | 1 |
cdbe83e607f21f38169fd93b25afcb114be881d4 | [
"sorted(nums)\na = len(nums)\nfor i in range(a):\n if nums[i] == 0:\n i += 1\n else:\n break\na = []\na.append(nums[i])\na.extend(nums[:i])\na.extend(nums[i + 1:])\nstr1 = ''.join((str(k) for k in a))\nreturn str1",
"one_p = []\nwhile nums:\n nums.sort(key=lambda x: int(str(x)[0]))",
"def... | <|body_start_0|>
sorted(nums)
a = len(nums)
for i in range(a):
if nums[i] == 0:
i += 1
else:
break
a = []
a.append(nums[i])
a.extend(nums[:i])
a.extend(nums[i + 1:])
str1 = ''.join((str(k) for k in a)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minNumber(self, nums):
"""先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串"""
<|body_0|>
def minNumber1(self, nums):
"""要找到最高位最小的 :param nums: :return:"""
<|body_1|>
def minNumber2(self, nums):
""":param nums: :return:"""
... | stack_v2_sparse_classes_36k_train_016202 | 1,841 | no_license | [
{
"docstring": "先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串",
"name": "minNumber",
"signature": "def minNumber(self, nums)"
},
{
"docstring": "要找到最高位最小的 :param nums: :return:",
"name": "minNumber1",
"signature": "def minNumber1(self, nums)"
},
{
"docstring": ":param... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minNumber(self, nums): 先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串
- def minNumber1(self, nums): 要找到最高位最小的 :param nums: :return:
- def minNumber2(self, nums): :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minNumber(self, nums): 先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串
- def minNumber1(self, nums): 要找到最高位最小的 :param nums: :return:
- def minNumber2(self, nums): :... | 4a27fdd976268bf4daf8eee447efd754f1e0bb02 | <|skeleton|>
class Solution:
def minNumber(self, nums):
"""先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串"""
<|body_0|>
def minNumber1(self, nums):
"""要找到最高位最小的 :param nums: :return:"""
<|body_1|>
def minNumber2(self, nums):
""":param nums: :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minNumber(self, nums):
"""先对数组进行排序,如果最小的是0,那么把第二位放到最左边 :param nums: :return:返回一个字符串"""
sorted(nums)
a = len(nums)
for i in range(a):
if nums[i] == 0:
i += 1
else:
break
a = []
a.append(nums[i]... | the_stack_v2_python_sparse | ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof.py | Angel888/suanfa | train | 0 | |
7637e4526334d5934221f71e921d322cb609f4e4 | [
"rst = 0\nlen_all = len(guess) + len(answer)\nlist_all = guess + answer\nprint(len_all)\nfor i in range(len(guess)):\n if list_all[i] == list_all[i + len_all // 2]:\n rst += 1\nreturn rst",
"rst = 0\nfor i in range(len(guess)):\n if guess[i] == answer[i]:\n rst += 1\nreturn rst"
] | <|body_start_0|>
rst = 0
len_all = len(guess) + len(answer)
list_all = guess + answer
print(len_all)
for i in range(len(guess)):
if list_all[i] == list_all[i + len_all // 2]:
rst += 1
return rst
<|end_body_0|>
<|body_start_1|>
rst = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def game(self, guess, answer):
""":type guess: List[int] :type answer: List[int] :rtype: int"""
<|body_0|>
def game_2(self, guess, answer):
""":type guess: List[int] :type answer: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_016203 | 909 | no_license | [
{
"docstring": ":type guess: List[int] :type answer: List[int] :rtype: int",
"name": "game",
"signature": "def game(self, guess, answer)"
},
{
"docstring": ":type guess: List[int] :type answer: List[int] :rtype: int",
"name": "game_2",
"signature": "def game_2(self, guess, answer)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def game(self, guess, answer): :type guess: List[int] :type answer: List[int] :rtype: int
- def game_2(self, guess, answer): :type guess: List[int] :type answer: List[int] :rtype... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def game(self, guess, answer): :type guess: List[int] :type answer: List[int] :rtype: int
- def game_2(self, guess, answer): :type guess: List[int] :type answer: List[int] :rtype... | 4f92911896c8b92c51650413b998e0bb1edfa4c0 | <|skeleton|>
class Solution:
def game(self, guess, answer):
""":type guess: List[int] :type answer: List[int] :rtype: int"""
<|body_0|>
def game_2(self, guess, answer):
""":type guess: List[int] :type answer: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def game(self, guess, answer):
""":type guess: List[int] :type answer: List[int] :rtype: int"""
rst = 0
len_all = len(guess) + len(answer)
list_all = guess + answer
print(len_all)
for i in range(len(guess)):
if list_all[i] == list_all[i + l... | the_stack_v2_python_sparse | guess_num.py | chenpengcode/Leetcode | train | 1 | |
b0bd7aad16b7a9b26ce3b416c4be70f49146e319 | [
"super(ExampleQueueTest, self).__init__(*args, **kwargs)\nself._input_text_file = tempfile.NamedTemporaryFile(mode='w+b')\nwith open(self._input_text_file.name, 'wt') as f:\n f.write('my name is chanwoo kim\\n')\n f.write('another name is chanwcom kim\\n')\n f.write('everyone has a name\\n')\n f.write('... | <|body_start_0|>
super(ExampleQueueTest, self).__init__(*args, **kwargs)
self._input_text_file = tempfile.NamedTemporaryFile(mode='w+b')
with open(self._input_text_file.name, 'wt') as f:
f.write('my name is chanwoo kim\n')
f.write('another name is chanwcom kim\n')
... | A class for testing classes and methods in word_id_example_queue.py. | ExampleQueueTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExampleQueueTest:
"""A class for testing classes and methods in word_id_example_queue.py."""
def __init__(self, *args, **kwargs):
"""Creates the input text file. The following is the contents of the input text file. * my name is chanwoo kim * another name is chanwcom kim * everyone h... | stack_v2_sparse_classes_36k_train_016204 | 4,876 | no_license | [
{
"docstring": "Creates the input text file. The following is the contents of the input text file. * my name is chanwoo kim * another name is chanwcom kim * everyone has a name * everyone has a car * my car has a name",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_017873 | Implement the Python class `ExampleQueueTest` described below.
Class description:
A class for testing classes and methods in word_id_example_queue.py.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Creates the input text file. The following is the contents of the input text file. * my name i... | Implement the Python class `ExampleQueueTest` described below.
Class description:
A class for testing classes and methods in word_id_example_queue.py.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Creates the input text file. The following is the contents of the input text file. * my name i... | cc1a193779a5e6ba42ecc8f223138519e431d014 | <|skeleton|>
class ExampleQueueTest:
"""A class for testing classes and methods in word_id_example_queue.py."""
def __init__(self, *args, **kwargs):
"""Creates the input text file. The following is the contents of the input text file. * my name is chanwoo kim * another name is chanwcom kim * everyone h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExampleQueueTest:
"""A class for testing classes and methods in word_id_example_queue.py."""
def __init__(self, *args, **kwargs):
"""Creates the input text file. The following is the contents of the input text file. * my name is chanwoo kim * another name is chanwcom kim * everyone has a name * e... | the_stack_v2_python_sparse | data_queue/word_id_example_queue_test.py | chanwcom/tensorflow_examples | train | 0 |
8f78fd953ecd7f0f38448561fcc508ec3b003699 | [
"LOG.debug('Config conversion started')\nself.aviobj = AviConverter()\nself.parsed = parsed_output\nself.common_utils = MigrationUtil()\nself.version = version\nself.enable_vs = enable_vs\nself.input_file_loc = input_folder_loc\nself.tenant = tenant\nself.cloud = cloud\nself.vrf = vrf\nself.vrf_ref = None\nself.seg... | <|body_start_0|>
LOG.debug('Config conversion started')
self.aviobj = AviConverter()
self.parsed = parsed_output
self.common_utils = MigrationUtil()
self.version = version
self.enable_vs = enable_vs
self.input_file_loc = input_folder_loc
self.tenant = tena... | Configuration conversion happens here | ConfigConverter | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigConverter:
"""Configuration conversion happens here"""
def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None):
"""Create Some common Objects over here"""
<|body_0|>
def conversion... | stack_v2_sparse_classes_36k_train_016205 | 6,022 | permissive | [
{
"docstring": "Create Some common Objects over here",
"name": "__init__",
"signature": "def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None)"
},
{
"docstring": "All conversion controller over here",
"nam... | 2 | stack_v2_sparse_classes_30k_train_016212 | Implement the Python class `ConfigConverter` described below.
Class description:
Configuration conversion happens here
Method signatures and docstrings:
- def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None): Create Some common Ob... | Implement the Python class `ConfigConverter` described below.
Class description:
Configuration conversion happens here
Method signatures and docstrings:
- def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None): Create Some common Ob... | f2386af42908d3c503ec0ec6f1b00f2095b0b004 | <|skeleton|>
class ConfigConverter:
"""Configuration conversion happens here"""
def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None):
"""Create Some common Objects over here"""
<|body_0|>
def conversion... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigConverter:
"""Configuration conversion happens here"""
def __init__(self, parsed_output, enable_vs=False, version='18.2.6', input_folder_loc=None, tenant=None, cloud=None, vrf=None, segroup=None):
"""Create Some common Objects over here"""
LOG.debug('Config conversion started')
... | the_stack_v2_python_sparse | python/avi/migrationtools/ace_converter/ace_config_converter.py | vmware/alb-sdk | train | 30 |
eeb4c56bcccdc2601c29e1a4e22008a0350c0952 | [
"if cls is cxx:\n if sys.platform == 'win32':\n from .msvc import msvc\n msvc.instances(fs)\nreturn super(cxx, cls).instances(fs)",
"fs = set.instantiate(fs)\nif cls is cxx and (not cxx.instantiated(fs)):\n logger.info('trying to instantiate a default C++ compiler')\n if sys.platform == 'wi... | <|body_start_0|>
if cls is cxx:
if sys.platform == 'win32':
from .msvc import msvc
msvc.instances(fs)
return super(cxx, cls).instances(fs)
<|end_body_0|>
<|body_start_1|>
fs = set.instantiate(fs)
if cls is cxx and (not cxx.instantiated(fs)):
... | C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to build). | cxx | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to buil... | stack_v2_sparse_classes_36k_train_016206 | 2,259 | permissive | [
{
"docstring": "Return all known C++ compiler instances for the current platform.",
"name": "instances",
"signature": "def instances(cls, fs=None)"
},
{
"docstring": "Try to find a compiler instance for the current platform.",
"name": "instance",
"signature": "def instance(cls, fs=None)"... | 2 | stack_v2_sparse_classes_30k_train_003243 | Implement the Python class `cxx` described below.
Class description:
C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler ... | Implement the Python class `cxx` described below.
Class description:
C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler ... | 0f369a8a9e4de305e5379d9662b2e79bffd43910 | <|skeleton|>
class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to buil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to build)."""
d... | the_stack_v2_python_sparse | src/faber/tools/cxx.py | stefanseefeld/faber | train | 15 |
1aa222737757444b8fa8b24b45371f2d528b162b | [
"self.parent_model = parent_model\nself.nms_thresh = nms_thresh\nself.n_train_pre_nms = n_train_pre_nms\nself.n_train_post_nms = n_train_post_nms\nself.n_test_pre_nms = n_test_pre_nms\nself.n_test_post_nms = n_test_post_nms\nself.min_size = min_size",
"if self.parent_model.training:\n n_pre_nms = self.n_train_... | <|body_start_0|>
self.parent_model = parent_model
self.nms_thresh = nms_thresh
self.n_train_pre_nms = n_train_pre_nms
self.n_train_post_nms = n_train_post_nms
self.n_test_pre_nms = n_test_pre_nms
self.n_test_post_nms = n_test_post_nms
self.min_size = min_size
<|en... | ProposalCreator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProposalCreator:
def __init__(self, parent_model, nms_thresh=0.7, n_train_pre_nms=12000, n_train_post_nms=2000, n_test_pre_nms=6000, n_test_post_nms=300, min_size=16):
""":param parent_model: 区分是training_model还是testing_model :param nms_thresh: 非极大值抑制的阈值 :param n_train_pre_nms: 训练时NMS之前的b... | stack_v2_sparse_classes_36k_train_016207 | 3,449 | no_license | [
{
"docstring": ":param parent_model: 区分是training_model还是testing_model :param nms_thresh: 非极大值抑制的阈值 :param n_train_pre_nms: 训练时NMS之前的boxes的数量 :param n_train_post_nms: 训练时NMS之后的boxes的数量 :param n_test_pre_nms: 测试时NMS之前的数量 :param n_test_post_nms: 测试时NMS之后的数量 :param min_size: 生成一个roi所需的目标的最小高度, 防止Roi pooling层切割后维度降为... | 2 | stack_v2_sparse_classes_30k_train_004074 | Implement the Python class `ProposalCreator` described below.
Class description:
Implement the ProposalCreator class.
Method signatures and docstrings:
- def __init__(self, parent_model, nms_thresh=0.7, n_train_pre_nms=12000, n_train_post_nms=2000, n_test_pre_nms=6000, n_test_post_nms=300, min_size=16): :param parent... | Implement the Python class `ProposalCreator` described below.
Class description:
Implement the ProposalCreator class.
Method signatures and docstrings:
- def __init__(self, parent_model, nms_thresh=0.7, n_train_pre_nms=12000, n_train_post_nms=2000, n_test_pre_nms=6000, n_test_post_nms=300, min_size=16): :param parent... | b4fb6ff7af6c9f906eabd836c6727ab7d9f18576 | <|skeleton|>
class ProposalCreator:
def __init__(self, parent_model, nms_thresh=0.7, n_train_pre_nms=12000, n_train_post_nms=2000, n_test_pre_nms=6000, n_test_post_nms=300, min_size=16):
""":param parent_model: 区分是training_model还是testing_model :param nms_thresh: 非极大值抑制的阈值 :param n_train_pre_nms: 训练时NMS之前的b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProposalCreator:
def __init__(self, parent_model, nms_thresh=0.7, n_train_pre_nms=12000, n_train_post_nms=2000, n_test_pre_nms=6000, n_test_post_nms=300, min_size=16):
""":param parent_model: 区分是training_model还是testing_model :param nms_thresh: 非极大值抑制的阈值 :param n_train_pre_nms: 训练时NMS之前的boxes的数量 :param... | the_stack_v2_python_sparse | nets/proposal_creator.py | xiguanlezz/Faster-RCNN | train | 13 | |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super().__init__()\nself.beta = beta\nself.inplace = inplace",
"if inplace:\n return torch.log(F.relu_(x).mul_(self.beta).add_(1), out=x)\nelse:\n return torch.log(1 + self.beta * F.relu(x))"
] | <|body_start_0|>
super().__init__()
self.beta = beta
self.inplace = inplace
<|end_body_0|>
<|body_start_1|>
if inplace:
return torch.log(F.relu_(x).mul_(self.beta).add_(1), out=x)
else:
return torch.log(1 + self.beta * F.relu(x))
<|end_body_1|>
| NLReLU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.beta = beta
self.in... | stack_v2_sparse_classes_36k_train_016208 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, beta=1.0, inplace=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015276 | Implement the Python class `NLReLU` described below.
Class description:
Implement the NLReLU class.
Method signatures and docstrings:
- def __init__(self, beta=1.0, inplace=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `NLReLU` described below.
Class description:
Implement the NLReLU class.
Method signatures and docstrings:
- def __init__(self, beta=1.0, inplace=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inpl... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NLReLU:
def __init__(self, beta=1.0, inplace=False):
"""Init method."""
super().__init__()
self.beta = beta
self.inplace = inplace
def forward(self, input):
"""Forward pass of the function."""
if inplace:
return torch.log(F.relu_(x).mul_(self.be... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
02b7572458a23a3ce384e19c4594cf02f7429179 | [
"self.batchsize = batchsize\nself.half_window = half_window\nself.n_negative = n_negative\nself.dataset = dataset\nself.counter = 0\nself.datasize = len(dataset)\nself.sampler = CategoricalSampler(dataset)\nself.indices = np.random.permutation(self.datasize - 2 * self.half_window) + self.half_window\nself.n_batch =... | <|body_start_0|>
self.batchsize = batchsize
self.half_window = half_window
self.n_negative = n_negative
self.dataset = dataset
self.counter = 0
self.datasize = len(dataset)
self.sampler = CategoricalSampler(dataset)
self.indices = np.random.permutation(sel... | DataIteratorForEmbeddingLearning | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataIteratorForEmbeddingLearning:
def __init__(self, batchsize, half_window, n_negative, dataset):
"""Initialization Args: batchsize: batchsize half_window: half window length n_negative: number of negative samples dataset: corpus replaced with word ids"""
<|body_0|>
def nex... | stack_v2_sparse_classes_36k_train_016209 | 11,796 | permissive | [
{
"docstring": "Initialization Args: batchsize: batchsize half_window: half window length n_negative: number of negative samples dataset: corpus replaced with word ids",
"name": "__init__",
"signature": "def __init__(self, batchsize, half_window, n_negative, dataset)"
},
{
"docstring": "Creating... | 2 | stack_v2_sparse_classes_30k_train_007170 | Implement the Python class `DataIteratorForEmbeddingLearning` described below.
Class description:
Implement the DataIteratorForEmbeddingLearning class.
Method signatures and docstrings:
- def __init__(self, batchsize, half_window, n_negative, dataset): Initialization Args: batchsize: batchsize half_window: half windo... | Implement the Python class `DataIteratorForEmbeddingLearning` described below.
Class description:
Implement the DataIteratorForEmbeddingLearning class.
Method signatures and docstrings:
- def __init__(self, batchsize, half_window, n_negative, dataset): Initialization Args: batchsize: batchsize half_window: half windo... | 41f71faa6efff7774a76bbd5af3198322a90a6ab | <|skeleton|>
class DataIteratorForEmbeddingLearning:
def __init__(self, batchsize, half_window, n_negative, dataset):
"""Initialization Args: batchsize: batchsize half_window: half window length n_negative: number of negative samples dataset: corpus replaced with word ids"""
<|body_0|>
def nex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataIteratorForEmbeddingLearning:
def __init__(self, batchsize, half_window, n_negative, dataset):
"""Initialization Args: batchsize: batchsize half_window: half window length n_negative: number of negative samples dataset: corpus replaced with word ids"""
self.batchsize = batchsize
se... | the_stack_v2_python_sparse | language-modeling/word2vec/word_embedding.py | sony/nnabla-examples | train | 308 | |
facb3d50632b96f6953546c096536844133ca17e | [
"u = usermanage(self.driver)\nu.open_usermanage()\nself.assertEqual(u.verify(), True)\nu.modify_obj()\nself.assertEqual(u.sub_tagname(), '用户管理-修改')\nu.name_clear()\nu.modify_save()\nself.assertEqual(u.error_name(), '不能为空哦')\nfunction.screenshot(self.driver, 'modify_user_blank.jpg')",
"u = usermanage(self.driver)\... | <|body_start_0|>
u = usermanage(self.driver)
u.open_usermanage()
self.assertEqual(u.verify(), True)
u.modify_obj()
self.assertEqual(u.sub_tagname(), '用户管理-修改')
u.name_clear()
u.modify_save()
self.assertEqual(u.error_name(), '不能为空哦')
function.screen... | Test014_User_Modify_Error | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test014_User_Modify_Error:
def test_user_modify_error1(self):
"""输入为空"""
<|body_0|>
def test_user_modify_error2(self):
"""没有专业"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
u = usermanage(self.driver)
u.open_usermanage()
self.asser... | stack_v2_sparse_classes_36k_train_016210 | 1,157 | no_license | [
{
"docstring": "输入为空",
"name": "test_user_modify_error1",
"signature": "def test_user_modify_error1(self)"
},
{
"docstring": "没有专业",
"name": "test_user_modify_error2",
"signature": "def test_user_modify_error2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012451 | Implement the Python class `Test014_User_Modify_Error` described below.
Class description:
Implement the Test014_User_Modify_Error class.
Method signatures and docstrings:
- def test_user_modify_error1(self): 输入为空
- def test_user_modify_error2(self): 没有专业 | Implement the Python class `Test014_User_Modify_Error` described below.
Class description:
Implement the Test014_User_Modify_Error class.
Method signatures and docstrings:
- def test_user_modify_error1(self): 输入为空
- def test_user_modify_error2(self): 没有专业
<|skeleton|>
class Test014_User_Modify_Error:
def test_u... | 6f42c25249fc642cecc270578a180820988d45b5 | <|skeleton|>
class Test014_User_Modify_Error:
def test_user_modify_error1(self):
"""输入为空"""
<|body_0|>
def test_user_modify_error2(self):
"""没有专业"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test014_User_Modify_Error:
def test_user_modify_error1(self):
"""输入为空"""
u = usermanage(self.driver)
u.open_usermanage()
self.assertEqual(u.verify(), True)
u.modify_obj()
self.assertEqual(u.sub_tagname(), '用户管理-修改')
u.name_clear()
u.modify_save()... | the_stack_v2_python_sparse | GlxssLive_web/TestCase/Manage_User/Test014_user_modify_error.py | rrmiracle/GlxssLive | train | 0 | |
477e8a03cb0a1e0cca9841347a9726f74ba73b9f | [
"queryset = super(CreateAndEmbedLinkView, self).get_queryset()\nif 'external_url' in self.request.POST:\n queryset = queryset.filter(link_type=Link.LINK_TYPE_EXTERNAL)\nif 'email' in self.request.POST:\n queryset = queryset.filter(link_type=Link.LINK_TYPE_EMAIL)\nreturn queryset",
"if 'external_url' in self... | <|body_start_0|>
queryset = super(CreateAndEmbedLinkView, self).get_queryset()
if 'external_url' in self.request.POST:
queryset = queryset.filter(link_type=Link.LINK_TYPE_EXTERNAL)
if 'email' in self.request.POST:
queryset = queryset.filter(link_type=Link.LINK_TYPE_EMAIL)... | View that allows a link to be created and immediately embedded in a rich-text field. | CreateAndEmbedLinkView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
<|body_0|>
def form_invalid(self, form):
... | stack_v2_sparse_classes_36k_train_016211 | 4,768 | permissive | [
{
"docstring": "Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "Processes unsuccessful form submittal. :param form: the form instance. :rtype: django.http.HttpResponse.",
"na... | 3 | stack_v2_sparse_classes_30k_train_008669 | Implement the Python class `CreateAndEmbedLinkView` described below.
Class description:
View that allows a link to be created and immediately embedded in a rich-text field.
Method signatures and docstrings:
- def get_queryset(self): Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.
- ... | Implement the Python class `CreateAndEmbedLinkView` described below.
Class description:
View that allows a link to be created and immediately embedded in a rich-text field.
Method signatures and docstrings:
- def get_queryset(self): Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet.
- ... | 096143fc2f4659f4ee9d63126fe30882950a6f59 | <|skeleton|>
class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
<|body_0|>
def form_invalid(self, form):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateAndEmbedLinkView:
"""View that allows a link to be created and immediately embedded in a rich-text field."""
def get_queryset(self):
"""Returns queryset based on POST variables. :rtype: django.db.models.query.QuerySet."""
queryset = super(CreateAndEmbedLinkView, self).get_queryset()... | the_stack_v2_python_sparse | wagtailplus/wagtaillinks/views/choosers.py | MechanisM/wagtailplus | train | 10 |
7b0847d9aad677cc871f5d2b890469a2f52ae1c8 | [
"logger.debug('cleaned_data %s' % self.cleaned_data)\nif self.files:\n self.key = Keypair(string=self.files['key_file'].read())\n self.cert = GID(string=self.files['cert_file'].read())\n cert_pubkey = self.cert.get_pubkey().get_pubkey_string()\n if cert_pubkey != self.key.get_pubkey_string():\n r... | <|body_start_0|>
logger.debug('cleaned_data %s' % self.cleaned_data)
if self.files:
self.key = Keypair(string=self.files['key_file'].read())
self.cert = GID(string=self.files['cert_file'].read())
cert_pubkey = self.cert.get_pubkey().get_pubkey_string()
if ... | Form to upload a certificate and its corresponding key. | UploadCertForm | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadCertForm:
"""Form to upload a certificate and its corresponding key."""
def clean(self):
"""Check that the cert file is signed by the key file and is trusted."""
<|body_0|>
def save(self, user):
"""Write the key and cert into files. @param user: the user to... | stack_v2_sparse_classes_36k_train_016212 | 6,630 | permissive | [
{
"docstring": "Check that the cert file is signed by the key file and is trusted.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Write the key and cert into files. @param user: the user to save the cert and key for. @type user: C{django.contrib.auth.models.User}",
"nam... | 2 | null | Implement the Python class `UploadCertForm` described below.
Class description:
Form to upload a certificate and its corresponding key.
Method signatures and docstrings:
- def clean(self): Check that the cert file is signed by the key file and is trusted.
- def save(self, user): Write the key and cert into files. @pa... | Implement the Python class `UploadCertForm` described below.
Class description:
Form to upload a certificate and its corresponding key.
Method signatures and docstrings:
- def clean(self): Check that the cert file is signed by the key file and is trusted.
- def save(self, user): Write the key and cert into files. @pa... | 059ed2b3308bda2af5e1942dc9967e6573dd6a53 | <|skeleton|>
class UploadCertForm:
"""Form to upload a certificate and its corresponding key."""
def clean(self):
"""Check that the cert file is signed by the key file and is trusted."""
<|body_0|>
def save(self, user):
"""Write the key and cert into files. @param user: the user to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadCertForm:
"""Form to upload a certificate and its corresponding key."""
def clean(self):
"""Check that the cert file is signed by the key file and is trusted."""
logger.debug('cleaned_data %s' % self.cleaned_data)
if self.files:
self.key = Keypair(string=self.fil... | the_stack_v2_python_sparse | expedient/src/python/expedient/clearinghouse/geni/forms.py | dana-i2cat/felix | train | 4 |
eaf295d4ae67329376c82f8fc095b4ad682bfa2e | [
"test = \"5\\nIAO'15\\nIAO'2015\\nIAO'1\\nIAO'9\\nIAO'0\"\nd = Olymp(test)\nself.assertEqual(d.n, 5)\nself.assertEqual(d.nums[0:2], ['15', '2015'])\nself.assertEqual(Olymp(test).calculate(), '2015\\n12015\\n1991\\n1989\\n1990')\ntest = \"4\\nIAO'9\\nIAO'99\\nIAO'999\\nIAO'9999\"\nself.assertEqual(Olymp(test).calcul... | <|body_start_0|>
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.nums[0:2], ['15', '2015'])
self.assertEqual(Olymp(test).calculate(), '2015\n12015\n1991\n1989\n1990')
test = "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999... | unitTests | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Olymp class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(tes... | stack_v2_sparse_classes_36k_train_016213 | 3,747 | permissive | [
{
"docstring": "Olymp 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_012166 | Implement the Python class `unitTests` described below.
Class description:
Implement the unitTests class.
Method signatures and docstrings:
- def test_single_test(self): Olymp 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): Olymp class testing
- def time_limit_test(self, nmax): Timelimit testing
<|skeleton|>
class unitTests:
def test_single_test(self):
"""... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class unitTests:
def test_single_test(self):
"""Olymp class testing"""
<|body_0|>
def time_limit_test(self, nmax):
"""Timelimit testing"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class unitTests:
def test_single_test(self):
"""Olymp class testing"""
test = "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0"
d = Olymp(test)
self.assertEqual(d.n, 5)
self.assertEqual(d.nums[0:2], ['15', '2015'])
self.assertEqual(Olymp(test).calculate(), '2015\n12015\n1991... | the_stack_v2_python_sparse | codeforces/664C_olymp.py | snsokolov/contests | train | 1 | |
384377947f9bd60eb493bd720aaff81db2a70238 | [
"ObjectManager.__init__(self)\nself.getters.update({'active': 'get_general', 'audience': 'get_general', 'session_template_resource_type_requirements': 'get_many_to_one', 'session_template_user_role_requirements': 'get_many_to_one', 'description': 'get_general', 'duration': 'get_general', 'event_template': 'get_fore... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'active': 'get_general', 'audience': 'get_general', 'session_template_resource_type_requirements': 'get_many_to_one', 'session_template_user_role_requirements': 'get_many_to_one', 'description': 'get_general', 'duration': 'get_general', ... | Manage SessionTemplates in the Power Reg system | SessionTemplateManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionTemplateManager:
"""Manage SessionTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, shortname, fullname, version, description, price, lead_time, active, modality='Generic', optional_attributes=None):... | stack_v2_sparse_classes_36k_train_016214 | 5,621 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a SessionTemplate @param shortname A short name, which must be unique @param fullname Full name @param version Version @param description description of the SessionTemplate @param price ... | 4 | stack_v2_sparse_classes_30k_train_010841 | Implement the Python class `SessionTemplateManager` described below.
Class description:
Manage SessionTemplates in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, shortname, fullname, version, description, price, lead_time, active, modality='Gene... | Implement the Python class `SessionTemplateManager` described below.
Class description:
Manage SessionTemplates in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, shortname, fullname, version, description, price, lead_time, active, modality='Gene... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class SessionTemplateManager:
"""Manage SessionTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, shortname, fullname, version, description, price, lead_time, active, modality='Generic', optional_attributes=None):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionTemplateManager:
"""Manage SessionTemplates in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'active': 'get_general', 'audience': 'get_general', 'session_template_resource_type_requirements': 'get_many_to_one... | the_stack_v2_python_sparse | pr_services/event_system/session_template_manager.py | ninemoreminutes/openassign-server | train | 0 |
df467ccace044f0fe02745123c01943c866a3afc | [
"try:\n len(regions)\nexcept:\n msg = 'Polygon_function takes a list of pairs (polygon, value).Got %s' % str(regions)\n raise Exception(msg)\nfirst_region = regions[0]\nif isinstance(first_region, str):\n msg = 'You passed in a list of text values into polygon_function instead of a list of pairs (polygo... | <|body_start_0|>
try:
len(regions)
except:
msg = 'Polygon_function takes a list of pairs (polygon, value).Got %s' % str(regions)
raise Exception(msg)
first_region = regions[0]
if isinstance(first_region, str):
msg = 'You passed in a list of... | Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of the form [ (P0, v0), (P1, v1), ...] with Pi being lists of vertices defining polyg... | Polygon_function | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Polygon_function:
"""Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of the form [ (P0, v0), (P1, v1), ...] wi... | stack_v2_sparse_classes_36k_train_016215 | 4,727 | permissive | [
{
"docstring": "Create instance of a polygon function. regions A list of (x,y) tuples defining a polygon. default Value or function returning value for points outside poly. geo_reference ??",
"name": "__init__",
"signature": "def __init__(self, regions, default=0.0, geo_reference=None)"
},
{
"do... | 2 | null | Implement the Python class `Polygon_function` described below.
Class description:
Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of... | Implement the Python class `Polygon_function` described below.
Class description:
Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of... | 6d6d8e22b7e15b601f960c198b521bc20682477c | <|skeleton|>
class Polygon_function:
"""Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of the form [ (P0, v0), (P1, v1), ...] wi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Polygon_function:
"""Create callable object f: x,y -> z, where a,y,z are vectors and where f will return different values depending on whether x,y belongs to specified polygons. To instantiate: Polygon_function(polygons) where polygons is a list of tuples of the form [ (P0, v0), (P1, v1), ...] with Pi being l... | the_stack_v2_python_sparse | anuga/geometry/polygon_function.py | stoiver/anuga_core | train | 4 |
724cc60afa14facdb58eaa7d5902ec051d54066e | [
"str_dict = {}\nfor ele in strs:\n sorted_str = self.get_sort_str(ele)\n if sorted_str not in str_dict:\n str_dict[sorted_str] = []\n str_dict[sorted_str].append(ele)\nreturn list(str_dict.values())",
"if not s or len(s) < 1:\n return None\ns = sorted(list(s))\nreturn ''.join(s)",
"words_dict... | <|body_start_0|>
str_dict = {}
for ele in strs:
sorted_str = self.get_sort_str(ele)
if sorted_str not in str_dict:
str_dict[sorted_str] = []
str_dict[sorted_str].append(ele)
return list(str_dict.values())
<|end_body_0|>
<|body_start_1|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def group_anagrams1(self, strs: List[str]) -> List[str]:
"""字符串 Args: strs: 字符串数组 Returns: 链表"""
<|body_0|>
def get_sort_str(self, s: str) -> str:
"""对字符串进行排序 Args: s: 字符串 Returns: 排序后字符串"""
<|body_1|>
def group_anagrams2(self, strs: List[str])... | stack_v2_sparse_classes_36k_train_016216 | 3,035 | permissive | [
{
"docstring": "字符串 Args: strs: 字符串数组 Returns: 链表",
"name": "group_anagrams1",
"signature": "def group_anagrams1(self, strs: List[str]) -> List[str]"
},
{
"docstring": "对字符串进行排序 Args: s: 字符串 Returns: 排序后字符串",
"name": "get_sort_str",
"signature": "def get_sort_str(self, s: str) -> str"
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def group_anagrams1(self, strs: List[str]) -> List[str]: 字符串 Args: strs: 字符串数组 Returns: 链表
- def get_sort_str(self, s: str) -> str: 对字符串进行排序 Args: s: 字符串 Returns: 排序后字符串
- def gr... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def group_anagrams1(self, strs: List[str]) -> List[str]: 字符串 Args: strs: 字符串数组 Returns: 链表
- def get_sort_str(self, s: str) -> str: 对字符串进行排序 Args: s: 字符串 Returns: 排序后字符串
- def gr... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def group_anagrams1(self, strs: List[str]) -> List[str]:
"""字符串 Args: strs: 字符串数组 Returns: 链表"""
<|body_0|>
def get_sort_str(self, s: str) -> str:
"""对字符串进行排序 Args: s: 字符串 Returns: 排序后字符串"""
<|body_1|>
def group_anagrams2(self, strs: List[str])... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def group_anagrams1(self, strs: List[str]) -> List[str]:
"""字符串 Args: strs: 字符串数组 Returns: 链表"""
str_dict = {}
for ele in strs:
sorted_str = self.get_sort_str(ele)
if sorted_str not in str_dict:
str_dict[sorted_str] = []
str... | the_stack_v2_python_sparse | src/leetcodepython/string/group_anagrams_49.py | zhangyu345293721/leetcode | train | 101 | |
7e79f5812ca6606edd1a4e942e4b9e69005e4daa | [
"self.mapi = defaultdict(list)\nfor idx, word in enumerate(words):\n self.mapi[word].append(idx)",
"dist, li1, li2, i1, i2 = (2 ** 31, self.mapi[word1], self.mapi[word2], 0, 0)\nwhile i1 < len(li1) and i2 < len(li2):\n dist = min(dist, abs(li1[i1] - li2[i2]))\n if li1[i1] > li2[i2]:\n i2 += 1\n ... | <|body_start_0|>
self.mapi = defaultdict(list)
for idx, word in enumerate(words):
self.mapi[word].append(idx)
<|end_body_0|>
<|body_start_1|>
dist, li1, li2, i1, i2 = (2 ** 31, self.mapi[word1], self.mapi[word2], 0, 0)
while i1 < len(li1) and i2 < len(li2):
dist ... | 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_36k_train_016217 | 967 | 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_018832 | 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... | 3129438b032d3aeb87c6ac5c4733df0ebc1272ba | <|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_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.mapi = defaultdict(list)
for idx, word in enumerate(words):
self.mapi[word].append(idx)
def shortest(self, word1, word2):
"""Adds a word into the dat... | the_stack_v2_python_sparse | solu/244. Shortest Word Distance II.py | coolmich/py-leetcode | train | 3 | |
07141169a51e489446a36cf91cb14b0602974f13 | [
"super(TopDownNet, self).__init__()\nself.aggregate = nn.Parameter(torch.zeros(1, n_hidden))\nself.M = nn.Sequential(nn.Linear(n_in + n_hidden, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_hidden), nn.ReLU())\nself.O = nn.Sequential(nn.Linear(n_in + n_hidden, n_hidden), nn.R... | <|body_start_0|>
super(TopDownNet, self).__init__()
self.aggregate = nn.Parameter(torch.zeros(1, n_hidden))
self.M = nn.Sequential(nn.Linear(n_in + n_hidden, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_hidden), nn.ReLU(), nn.Linear(n_hidden, n_hidden), nn.ReLU())
self.O = nn.Sequential(n... | TopDownNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopDownNet:
def __init__(self, n_in, n_hidden):
"""This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n_hidden: Number of hidden units unsed throughout the network."""
<|body_0|>
def forwar... | stack_v2_sparse_classes_36k_train_016218 | 1,869 | no_license | [
{
"docstring": "This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n_hidden: Number of hidden units unsed throughout the network.",
"name": "__init__",
"signature": "def __init__(self, n_in, n_hidden)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_007315 | Implement the Python class `TopDownNet` described below.
Class description:
Implement the TopDownNet class.
Method signatures and docstrings:
- def __init__(self, n_in, n_hidden): This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n... | Implement the Python class `TopDownNet` described below.
Class description:
Implement the TopDownNet class.
Method signatures and docstrings:
- def __init__(self, n_in, n_hidden): This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n... | 114f41207d28f1c3d16f9c3d8cdb2bbced60c423 | <|skeleton|>
class TopDownNet:
def __init__(self, n_in, n_hidden):
"""This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n_hidden: Number of hidden units unsed throughout the network."""
<|body_0|>
def forwar... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopDownNet:
def __init__(self, n_in, n_hidden):
"""This network is given input of size (N, K, n_in) where N, K can vary per batch. :param n_in: Number of block-specific parameters. :param n_hidden: Number of hidden units unsed throughout the network."""
super(TopDownNet, self).__init__()
... | the_stack_v2_python_sparse | learning/models/topdown_net.py | Learning-and-Intelligent-Systems/stacking | train | 13 | |
f143e35ae8dbb0de06d81d8da2c70e07af16072a | [
"if not exactly_one(table, sql):\n raise ETLInputError('Only one of table, sql needed')\nsuper(ExtractPostgresStep, self).__init__(**kwargs)\nif table:\n sql = 'SELECT * FROM %s;' % table\nelif sql:\n table = SelectStatement(sql).dependencies[0]\nelse:\n raise ETLInputError('Provide a sql statement or a... | <|body_start_0|>
if not exactly_one(table, sql):
raise ETLInputError('Only one of table, sql needed')
super(ExtractPostgresStep, self).__init__(**kwargs)
if table:
sql = 'SELECT * FROM %s;' % table
elif sql:
table = SelectStatement(sql).dependencies[0]... | Extract Postgres Step class that helps get data out of postgres | ExtractPostgresStep | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractPostgresStep:
"""Extract Postgres Step class that helps get data out of postgres"""
def __init__(self, table=None, sql=None, host_db_key=None, output_path=None, intermediate_path=None, splits=4, **kwargs):
"""Constructor for the ExtractPostgresStep class Args: schema(str): sch... | stack_v2_sparse_classes_36k_train_016219 | 5,365 | permissive | [
{
"docstring": "Constructor for the ExtractPostgresStep class Args: schema(str): schema from which table should be extracted table(path): table name for extract sql(str): sql query to be executed output_path(str): s3 path where sql output should be saved **kwargs(optional): Keyword arguments directly passed to ... | 2 | null | Implement the Python class `ExtractPostgresStep` described below.
Class description:
Extract Postgres Step class that helps get data out of postgres
Method signatures and docstrings:
- def __init__(self, table=None, sql=None, host_db_key=None, output_path=None, intermediate_path=None, splits=4, **kwargs): Constructor... | Implement the Python class `ExtractPostgresStep` described below.
Class description:
Extract Postgres Step class that helps get data out of postgres
Method signatures and docstrings:
- def __init__(self, table=None, sql=None, host_db_key=None, output_path=None, intermediate_path=None, splits=4, **kwargs): Constructor... | 797cb719e6c2abeda0751ada3339c72bfb19c8f2 | <|skeleton|>
class ExtractPostgresStep:
"""Extract Postgres Step class that helps get data out of postgres"""
def __init__(self, table=None, sql=None, host_db_key=None, output_path=None, intermediate_path=None, splits=4, **kwargs):
"""Constructor for the ExtractPostgresStep class Args: schema(str): sch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractPostgresStep:
"""Extract Postgres Step class that helps get data out of postgres"""
def __init__(self, table=None, sql=None, host_db_key=None, output_path=None, intermediate_path=None, splits=4, **kwargs):
"""Constructor for the ExtractPostgresStep class Args: schema(str): schema from whic... | the_stack_v2_python_sparse | dataduct/steps/extract_postgres.py | EverFi/dataduct | train | 3 |
e065d7840e44b074a43c915ba937fbeaa782b816 | [
"nums = sorted(nums)\n\ndef findNSum(l, r, target, N, result, rst):\n if N > r - l + 1 or N < 2 or target < nums[l] * N or (target > nums[r] * N):\n return\n if N == 2:\n while l < r:\n s = nums[l] + nums[r]\n if s == target:\n rst.append(result + [nums[l], n... | <|body_start_0|>
nums = sorted(nums)
def findNSum(l, r, target, N, result, rst):
if N > r - l + 1 or N < 2 or target < nums[l] * N or (target > nums[r] * N):
return
if N == 2:
while l < r:
s = nums[l] + nums[r]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def fourSum_myfirst(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_016220 | 2,798 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum_myfirst",
"signature": "def fourSum_my... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def fourSum_myfirst(self, nums, target): :type nums: List[int] :type target: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def fourSum_myfirst(self, nums, target): :type nums: List[int] :type target: in... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def fourSum_myfirst(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
nums = sorted(nums)
def findNSum(l, r, target, N, result, rst):
if N > r - l + 1 or N < 2 or target < nums[l] * N or (target > nums[r] * N):
ret... | the_stack_v2_python_sparse | 18.4Sum.py | JerryRoc/leetcode | train | 0 | |
0f9d3537c98abd7f653df332e74165224d9eaaf3 | [
"self.lock = asyncio.Lock()\nsession = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)\nself.requester = AiohttpSessionRequester(session, with_sleep=True)\nself.upnp_factory = UpnpFactory(self.requester, non_strict=True)\nself.event_notifiers = {}\nself.event_notifier_refs = defaultdict(int)",
"LOG... | <|body_start_0|>
self.lock = asyncio.Lock()
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionRequester(session, with_sleep=True)
self.upnp_factory = UpnpFactory(self.requester, non_strict=True)
self.event_notifiers = {}
... | Storage class for domain global data. | DlnaDmrData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_cleanup_event_notifiers(self, event: Event) -> None:
"""Clean up resources when Home Assistant is st... | stack_v2_sparse_classes_36k_train_016221 | 5,016 | permissive | [
{
"docstring": "Initialize global data.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant) -> None"
},
{
"docstring": "Clean up resources when Home Assistant is stopped.",
"name": "async_cleanup_event_notifiers",
"signature": "async def async_cleanup_event_notifi... | 4 | stack_v2_sparse_classes_30k_train_010117 | Implement the Python class `DlnaDmrData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_cleanup_event_notifiers(self, event: Event) -> None: Clean up resources when... | Implement the Python class `DlnaDmrData` described below.
Class description:
Storage class for domain global data.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant) -> None: Initialize global data.
- async def async_cleanup_event_notifiers(self, event: Event) -> None: Clean up resources when... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
<|body_0|>
async def async_cleanup_event_notifiers(self, event: Event) -> None:
"""Clean up resources when Home Assistant is st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DlnaDmrData:
"""Storage class for domain global data."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize global data."""
self.lock = asyncio.Lock()
session = aiohttp_client.async_get_clientsession(hass, verify_ssl=False)
self.requester = AiohttpSessionReques... | the_stack_v2_python_sparse | homeassistant/components/dlna_dmr/data.py | home-assistant/core | train | 35,501 |
8f8a9a7472430a1edbb7b5b3bf4effe794a2eeb2 | [
"datas = []\nfin = open(w_file, 'r')\nfor line in fin.readlines():\n f = float(line.split('\\n')[0])\n datas.append(f)\nfin.close()\nreturn datas",
"datas = self.data_collect(w_file)\ntot = 0\nfor data in datas:\n tot = tot + data\naverage = tot / len(datas)\ntot = 0\nfor data in datas:\n tot = tot + ... | <|body_start_0|>
datas = []
fin = open(w_file, 'r')
for line in fin.readlines():
f = float(line.split('\n')[0])
datas.append(f)
fin.close()
return datas
<|end_body_0|>
<|body_start_1|>
datas = self.data_collect(w_file)
tot = 0
for ... | ParaMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
<|body_0|>
def get_para(self, w_file):
"""get parameter :param w_file: filename :return: average u and sigma's square"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_016222 | 975 | no_license | [
{
"docstring": "open fine and handle data form :param w_file: filename :return: data (list)",
"name": "data_collect",
"signature": "def data_collect(self, w_file)"
},
{
"docstring": "get parameter :param w_file: filename :return: average u and sigma's square",
"name": "get_para",
"signat... | 2 | stack_v2_sparse_classes_30k_train_001981 | Implement the Python class `ParaMaker` described below.
Class description:
Implement the ParaMaker class.
Method signatures and docstrings:
- def data_collect(self, w_file): open fine and handle data form :param w_file: filename :return: data (list)
- def get_para(self, w_file): get parameter :param w_file: filename ... | Implement the Python class `ParaMaker` described below.
Class description:
Implement the ParaMaker class.
Method signatures and docstrings:
- def data_collect(self, w_file): open fine and handle data form :param w_file: filename :return: data (list)
- def get_para(self, w_file): get parameter :param w_file: filename ... | b0820b8d8924a9b22c820e3dce4778f4f9a0a96f | <|skeleton|>
class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
<|body_0|>
def get_para(self, w_file):
"""get parameter :param w_file: filename :return: average u and sigma's square"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParaMaker:
def data_collect(self, w_file):
"""open fine and handle data form :param w_file: filename :return: data (list)"""
datas = []
fin = open(w_file, 'r')
for line in fin.readlines():
f = float(line.split('\n')[0])
datas.append(f)
fin.close(... | the_stack_v2_python_sparse | NaiveBayesian/para_make.py | P-a-z/learn-python-slowly | train | 0 | |
11eac46a5163108d34fa502e4f08e3fcf2d6550c | [
"self._sa_id_card = SAIDCard()\nself._sa_id_book = SAIDBook()\nself._sa_id_book_old = SAIDBookOld()\nself._up_card = UPStudentCard()",
"if id_type == 'idcard':\n return self._sa_id_card\nelif id_type == 'idbook':\n return self._sa_id_book\nelif id_type == 'idbookold':\n return self._sa_id_book_old\nelif ... | <|body_start_0|>
self._sa_id_card = SAIDCard()
self._sa_id_book = SAIDBook()
self._sa_id_book_old = SAIDBookOld()
self._up_card = UPStudentCard()
<|end_body_0|>
<|body_start_1|>
if id_type == 'idcard':
return self._sa_id_card
elif id_type == 'idbook':
... | A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South African ID book context. :_up_card (UPStudentCard): A University of Pretoria staff/st... | ContextManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextManager:
"""A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South African ID book context. :_up_card (UPStude... | stack_v2_sparse_classes_36k_train_016223 | 2,120 | permissive | [
{
"docstring": "Responsible for initialising the ContextManager object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Returns an ID context based on the ID type that is passed in as an arg. :param id_type (str): A string indicating a type of ID. Returns: - (IDContext... | 2 | stack_v2_sparse_classes_30k_train_000685 | Implement the Python class `ContextManager` described below.
Class description:
A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South Afri... | Implement the Python class `ContextManager` described below.
Class description:
A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South Afri... | d62917262080f09d7c9e7262f507e2c1482d7c56 | <|skeleton|>
class ContextManager:
"""A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South African ID book context. :_up_card (UPStude... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContextManager:
"""A class responsible for managing and maintaining the various ID contexts. :_sa_id_card (SAIDCard): A South African ID card context. :_sa_id_book (SAIDBook): A South African ID book context. :_sa_id_book_old (SAIDBookOld): An old South African ID book context. :_up_card (UPStudentCard): A Un... | the_stack_v2_python_sparse | src/main/python/hutts_verification/image_processing/context_manager.py | javaTheHutts/Java-the-Hutts | train | 2 |
a2f7482fb19af0064e301bf6263ce26267abdd38 | [
"pairs = []\nfor i, num1 in enumerate(nums1):\n for j, num2 in enumerate(nums2):\n if i + j >= k:\n break\n pairs.append((num1 + num2, num1, num2))\nreturn map(lambda x: [x[1], x[2]], heapq.nsmallest(k, pairs))",
"if not nums1 or not nums2:\n return []\nlength1, length2 = (len(nums1... | <|body_start_0|>
pairs = []
for i, num1 in enumerate(nums1):
for j, num2 in enumerate(nums2):
if i + j >= k:
break
pairs.append((num1 + num2, num1, num2))
return map(lambda x: [x[1], x[2]], heapq.nsmallest(k, pairs))
<|end_body_0|>
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs2(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_36k_train_016224 | 1,286 | permissive | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairs",
"signature": "def kSmallestPairs(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"nam... | 2 | stack_v2_sparse_classes_30k_train_002960 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs2(self, nums1, nums2, k): :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairs2(self, nums1, nums2, k): :type ... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairs2(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
pairs = []
for i, num1 in enumerate(nums1):
for j, num2 in enumerate(nums2):
if i + j >= k:
brea... | the_stack_v2_python_sparse | 301-400/371-380/373-findKPairsWithSmallestSums/findKPairsWithSmallestSums.py | xuychen/Leetcode | train | 0 | |
555c572b289633145f5c1f2068058b7f1cb4896c | [
"self.file_name = file_name\nself.append_file = append_file\nself.result_keys = None\nif self.append_file:\n if not os.path.isfile(file_name):\n msg = 'File not found at path: {}. When using append=True in CSVWriter, the file must exist at the prescribed path before data is written to it.'.format(file_nam... | <|body_start_0|>
self.file_name = file_name
self.append_file = append_file
self.result_keys = None
if self.append_file:
if not os.path.isfile(file_name):
msg = 'File not found at path: {}. When using append=True in CSVWriter, the file must exist at the prescri... | Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come. | CSVWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVWriter:
"""Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come."""
def __init__(self, file_name: str='output.csv', append_file: bool=False):
"""Initialize ... | stack_v2_sparse_classes_36k_train_016225 | 26,819 | no_license | [
{
"docstring": "Initialize the basics of the output file Parameters ---------- file_name : str, default 'output.csv' Name of the output CSV file append_file : bool, default False Add more rows to an existing CSV file",
"name": "__init__",
"signature": "def __init__(self, file_name: str='output.csv', app... | 3 | stack_v2_sparse_classes_30k_train_016726 | Implement the Python class `CSVWriter` described below.
Class description:
Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come.
Method signatures and docstrings:
- def __init__(self, file_name... | Implement the Python class `CSVWriter` described below.
Class description:
Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come.
Method signatures and docstrings:
- def __init__(self, file_name... | 560e840f87a6a8f86929cd3b37a799504e46e53b | <|skeleton|>
class CSVWriter:
"""Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come."""
def __init__(self, file_name: str='output.csv', append_file: bool=False):
"""Initialize ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSVWriter:
"""Class which builds a CSV file to store the output of analysis tools. It can only be used to store relatively basic quantities (scalars, strings, etc.) More documentation to come."""
def __init__(self, file_name: str='output.csv', append_file: bool=False):
"""Initialize the basics of... | the_stack_v2_python_sparse | mlreco/iotools/writers.py | DeepLearnPhysics/lartpc_mlreco3d | train | 9 |
c72a5600552958dbc55f3db8cb20060c991f6e7a | [
"self.probability_distribution = []\ntot = 0\nfor i in range(len(w)):\n tot += w[i]\n self.probability_distribution.append(tot)\nself.tot = tot",
"x = random.randint(0, self.tot - 1)\nlo = 0\nhi = len(self.probability_distribution) - 1\nwhile lo + 1 < hi:\n mid = (lo + hi) // 2\n if x >= self.probabil... | <|body_start_0|>
self.probability_distribution = []
tot = 0
for i in range(len(w)):
tot += w[i]
self.probability_distribution.append(tot)
self.tot = tot
<|end_body_0|>
<|body_start_1|>
x = random.randint(0, self.tot - 1)
lo = 0
hi = len(se... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.probability_distribution = []
tot = 0
for i in range(len(w)):
t... | stack_v2_sparse_classes_36k_train_016226 | 1,644 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021265 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | aac41ddd2ec5f6e5c0f46659696ed5b67769bde2 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.probability_distribution = []
tot = 0
for i in range(len(w)):
tot += w[i]
self.probability_distribution.append(tot)
self.tot = tot
def pickIndex(self):
""":rtype: int"""
... | the_stack_v2_python_sparse | random_pick_with_weight.py | aroraakshit/coding_prep | train | 8 | |
044a3470f76db302683901cc6dae4b460ee42c52 | [
"instance_id = getattr(self.instance, 'id', None)\nfor user in attendee_ids:\n if user.meeting_set.exclude(id=instance_id).exists():\n raise serializers.ValidationError(f'{user} is already in a meeting.')\nreturn attendee_ids",
"if queue.status == 'closed' and self.context['action'] == 'WRITE' and (self... | <|body_start_0|>
instance_id = getattr(self.instance, 'id', None)
for user in attendee_ids:
if user.meeting_set.exclude(id=instance_id).exists():
raise serializers.ValidationError(f'{user} is already in a meeting.')
return attendee_ids
<|end_body_0|>
<|body_start_1|>... | MeetingSerializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeetingSerializer:
def validate_attendee_ids(self, attendee_ids):
"""Attendees may only be in one meeting at a time."""
<|body_0|>
def validate_queue(self, queue):
"""Prevent new meeting from being added to a closed queue, unless it's added by a host."""
<|bo... | stack_v2_sparse_classes_36k_train_016227 | 10,335 | permissive | [
{
"docstring": "Attendees may only be in one meeting at a time.",
"name": "validate_attendee_ids",
"signature": "def validate_attendee_ids(self, attendee_ids)"
},
{
"docstring": "Prevent new meeting from being added to a closed queue, unless it's added by a host.",
"name": "validate_queue",
... | 3 | stack_v2_sparse_classes_30k_test_000080 | Implement the Python class `MeetingSerializer` described below.
Class description:
Implement the MeetingSerializer class.
Method signatures and docstrings:
- def validate_attendee_ids(self, attendee_ids): Attendees may only be in one meeting at a time.
- def validate_queue(self, queue): Prevent new meeting from being... | Implement the Python class `MeetingSerializer` described below.
Class description:
Implement the MeetingSerializer class.
Method signatures and docstrings:
- def validate_attendee_ids(self, attendee_ids): Attendees may only be in one meeting at a time.
- def validate_queue(self, queue): Prevent new meeting from being... | 12e2185faf35307564bea910ff1baad7bef1ff76 | <|skeleton|>
class MeetingSerializer:
def validate_attendee_ids(self, attendee_ids):
"""Attendees may only be in one meeting at a time."""
<|body_0|>
def validate_queue(self, queue):
"""Prevent new meeting from being added to a closed queue, unless it's added by a host."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeetingSerializer:
def validate_attendee_ids(self, attendee_ids):
"""Attendees may only be in one meeting at a time."""
instance_id = getattr(self.instance, 'id', None)
for user in attendee_ids:
if user.meeting_set.exclude(id=instance_id).exists():
raise ser... | the_stack_v2_python_sparse | src/officehours_api/serializers.py | tl-its-umich-edu/remote-office-hours-queue | train | 12 | |
6eeb2d6be78771a9465d6d2e7b9be50ccaa4674f | [
"super().__init__(num_locations, coverages_per_location)\nself.num_layers = num_layers\nself.dtypes = OrderedDict([('layer_id', 'i'), ('level_id', 'i'), ('agg_id', 'i'), ('policytc_id', 'i')])\nself.data_length = num_locations * coverages_per_location + num_layers\nself.file_name = os.path.join(directory, 'fm_polic... | <|body_start_0|>
super().__init__(num_locations, coverages_per_location)
self.num_layers = num_layers
self.dtypes = OrderedDict([('layer_id', 'i'), ('level_id', 'i'), ('agg_id', 'i'), ('policytc_id', 'i')])
self.data_length = num_locations * coverages_per_location + num_layers
se... | Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: Generate Financial Model Policy dummy model Oasis file data. | FMPolicyTCFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FMPolicyTCFile:
"""Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: Generate Financial Model Policy dummy mo... | stack_v2_sparse_classes_36k_train_016228 | 39,722 | permissive | [
{
"docstring": "Initialise Financial Model Policy file class. Args: num_locations (int): number of locations. coverages_per_location (int): number of coverage types per location. num_layers (int): number of layers. directory (str): dummy model file destination.",
"name": "__init__",
"signature": "def __... | 2 | null | Implement the Python class `FMPolicyTCFile` described below.
Class description:
Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: G... | Implement the Python class `FMPolicyTCFile` described below.
Class description:
Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: G... | 23e704c335629ccd010969b1090446cfa3f384d5 | <|skeleton|>
class FMPolicyTCFile:
"""Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: Generate Financial Model Policy dummy mo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FMPolicyTCFile:
"""Generate data for Financial Model Policy dummy model Oasis file. This file shows the calculation rule (from the Financial Model Policy file) that should be applied to aggregations of loss at a particular level. Attributes: generate_data: Generate Financial Model Policy dummy model Oasis fil... | the_stack_v2_python_sparse | oasislmf/computation/data/dummy_model/generate.py | OasisLMF/OasisLMF | train | 122 |
dec6e9db4e2397f2609fdaeb439b80d1615cf48b | [
"charms: List[Dict[str, Any]] = []\ncharms = Charms.IDs(self, charms)\ncharms = Charms.Table(self, charms)\nUtility.WriteFile(self, f'{self.eXAssets}/charms.json', charms)\nlog.info(f'Compiled {len(charms):,} Charms')",
"ids: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAssets}/loot/weapon_charm_ids.csv... | <|body_start_0|>
charms: List[Dict[str, Any]] = []
charms = Charms.IDs(self, charms)
charms = Charms.Table(self, charms)
Utility.WriteFile(self, f'{self.eXAssets}/charms.json', charms)
log.info(f'Compiled {len(charms):,} Charms')
<|end_body_0|>
<|body_start_1|>
ids: List... | Charm XAssets. | Charms | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Charms:
"""Charm XAssets."""
def Compile(self: Any) -> None:
"""Compile the Charm XAssets."""
<|body_0|>
def IDs(self: Any, charms: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/weapon_charm_ids.csv XAsset."""
<|body_1|>
def Tabl... | stack_v2_sparse_classes_36k_train_016229 | 2,781 | permissive | [
{
"docstring": "Compile the Charm XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the loot/weapon_charm_ids.csv XAsset.",
"name": "IDs",
"signature": "def IDs(self: Any, charms: List[Dict[str, Any]]) -> List[Dict[str, Any]]"
},
{... | 3 | stack_v2_sparse_classes_30k_train_006268 | Implement the Python class `Charms` described below.
Class description:
Charm XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Charm XAssets.
- def IDs(self: Any, charms: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/weapon_charm_ids.csv XAsset.
- def Table(se... | Implement the Python class `Charms` described below.
Class description:
Charm XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Charm XAssets.
- def IDs(self: Any, charms: List[Dict[str, Any]]) -> List[Dict[str, Any]]: Compile the loot/weapon_charm_ids.csv XAsset.
- def Table(se... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class Charms:
"""Charm XAssets."""
def Compile(self: Any) -> None:
"""Compile the Charm XAssets."""
<|body_0|>
def IDs(self: Any, charms: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the loot/weapon_charm_ids.csv XAsset."""
<|body_1|>
def Tabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Charms:
"""Charm XAssets."""
def Compile(self: Any) -> None:
"""Compile the Charm XAssets."""
charms: List[Dict[str, Any]] = []
charms = Charms.IDs(self, charms)
charms = Charms.Table(self, charms)
Utility.WriteFile(self, f'{self.eXAssets}/charms.json', charms)
... | the_stack_v2_python_sparse | ModernWarfare/XAssets/charms.py | dbuentello/Hyde | train | 0 |
f6d16ecbe6366172cbb7008490318418219e59cd | [
"super(LinearModel, self).__init__()\nself.features = feature_extractor\nself.fc = nn.Linear(num_features, output_dim)",
"features = self.features(x)\nout = self.fc(features)\nreturn out"
] | <|body_start_0|>
super(LinearModel, self).__init__()
self.features = feature_extractor
self.fc = nn.Linear(num_features, output_dim)
<|end_body_0|>
<|body_start_1|>
features = self.features(x)
out = self.fc(features)
return out
<|end_body_1|>
| Add a linear layer after the backbone. | LinearModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearModel:
"""Add a linear layer after the backbone."""
def __init__(self, feature_extractor, num_features, output_dim=2):
"""Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_features (int): The number of features from the backbone. o... | stack_v2_sparse_classes_36k_train_016230 | 17,515 | permissive | [
{
"docstring": "Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_features (int): The number of features from the backbone. output_dim (int): The output dimension of the new model.",
"name": "__init__",
"signature": "def __init__(self, feature_extractor, nu... | 2 | stack_v2_sparse_classes_30k_train_001846 | Implement the Python class `LinearModel` described below.
Class description:
Add a linear layer after the backbone.
Method signatures and docstrings:
- def __init__(self, feature_extractor, num_features, output_dim=2): Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_fe... | Implement the Python class `LinearModel` described below.
Class description:
Add a linear layer after the backbone.
Method signatures and docstrings:
- def __init__(self, feature_extractor, num_features, output_dim=2): Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_fe... | 008ba81a14c333f5027126000555baefdf5fc049 | <|skeleton|>
class LinearModel:
"""Add a linear layer after the backbone."""
def __init__(self, feature_extractor, num_features, output_dim=2):
"""Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_features (int): The number of features from the backbone. o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearModel:
"""Add a linear layer after the backbone."""
def __init__(self, feature_extractor, num_features, output_dim=2):
"""Args: feature_extractor (nn.Module): The backbone of the model, used as a feature extractor. num_features (int): The number of features from the backbone. output_dim (in... | the_stack_v2_python_sparse | model_utils.py | ZhiliangWu/mDKL | train | 4 |
770c3e0c20234fad7c9c757e094da8e742e41e2a | [
"marker_type = MarkerType.Unlabeled if unlabeled else MarkerType.Labeled\nsuper(MarkerSet, self).__init__(nb_channels, name, rate, system_rate)\nif isinstance(marker_names, str):\n marker_names = [marker_names]\nif marker_names:\n if nb_channels != len(marker_names):\n raise ValueError('The number of c... | <|body_start_0|>
marker_type = MarkerType.Unlabeled if unlabeled else MarkerType.Labeled
super(MarkerSet, self).__init__(nb_channels, name, rate, system_rate)
if isinstance(marker_names, str):
marker_names = [marker_names]
if marker_names:
if nb_channels != len(ma... | This class is used to store the available markers. | MarkerSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarkerSet:
"""This class is used to store the available markers."""
def __init__(self, nb_channels: int=1, name: str=None, marker_names: Union[str, list]=None, rate: float=None, unlabeled: bool=False, system_rate: float=100, unit: str='m'):
"""Initialize a marker set. Parameters ----... | stack_v2_sparse_classes_36k_train_016231 | 14,244 | permissive | [
{
"docstring": "Initialize a marker set. Parameters ---------- nb_channels: int Number of channels of the marker set (number of markers). name: str Name of the marker set. marker_names: str or list Name of the markers. rate: float Rate of the marker set. unlabeled: bool True if the marker set is unlabeled, Fals... | 2 | stack_v2_sparse_classes_30k_train_001899 | Implement the Python class `MarkerSet` described below.
Class description:
This class is used to store the available markers.
Method signatures and docstrings:
- def __init__(self, nb_channels: int=1, name: str=None, marker_names: Union[str, list]=None, rate: float=None, unlabeled: bool=False, system_rate: float=100,... | Implement the Python class `MarkerSet` described below.
Class description:
This class is used to store the available markers.
Method signatures and docstrings:
- def __init__(self, nb_channels: int=1, name: str=None, marker_names: Union[str, list]=None, rate: float=None, unlabeled: bool=False, system_rate: float=100,... | 1f09785605ed5e4eaa78bd203ec118c3b2794732 | <|skeleton|>
class MarkerSet:
"""This class is used to store the available markers."""
def __init__(self, nb_channels: int=1, name: str=None, marker_names: Union[str, list]=None, rate: float=None, unlabeled: bool=False, system_rate: float=100, unit: str='m'):
"""Initialize a marker set. Parameters ----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarkerSet:
"""This class is used to store the available markers."""
def __init__(self, nb_channels: int=1, name: str=None, marker_names: Union[str, list]=None, rate: float=None, unlabeled: bool=False, system_rate: float=100, unit: str='m'):
"""Initialize a marker set. Parameters ---------- nb_cha... | the_stack_v2_python_sparse | biosiglive/interfaces/param.py | aceglia/biosiglive | train | 6 |
3850c0b40115edd2a99b20cc72cda902cdab49b7 | [
"DBFormatter.__init__(self, logger, dbi)\nself.logger = logger\nself.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''\nself.sql = 'UPDATE %sBLOCKS SET OPEN_FOR_WRITING = :open_for_writing , LAST_MODIFIED_BY=:myuser,\\nLAST_MODIFICATION_DATE = :ltime where BLOCK_NAME = :block_name' % self.owner",
"i... | <|body_start_0|>
DBFormatter.__init__(self, logger, dbi)
self.logger = logger
self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''
self.sql = 'UPDATE %sBLOCKS SET OPEN_FOR_WRITING = :open_for_writing , LAST_MODIFIED_BY=:myuser,\nLAST_MODIFICATION_DATE = :ltime where BLOCK... | Block Update Status DAO class. | UpdateStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateStatus:
"""Block Update Status DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
<|body_0|>
def execute(self, conn, block_name, open_for_writing, ltime, transaction=False):
"""for a given file"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_016232 | 1,356 | permissive | [
{
"docstring": "Add schema owner and sql.",
"name": "__init__",
"signature": "def __init__(self, logger, dbi, owner)"
},
{
"docstring": "for a given file",
"name": "execute",
"signature": "def execute(self, conn, block_name, open_for_writing, ltime, transaction=False)"
}
] | 2 | null | Implement the Python class `UpdateStatus` described below.
Class description:
Block Update Status DAO class.
Method signatures and docstrings:
- def __init__(self, logger, dbi, owner): Add schema owner and sql.
- def execute(self, conn, block_name, open_for_writing, ltime, transaction=False): for a given file | Implement the Python class `UpdateStatus` described below.
Class description:
Block Update Status DAO class.
Method signatures and docstrings:
- def __init__(self, logger, dbi, owner): Add schema owner and sql.
- def execute(self, conn, block_name, open_for_writing, ltime, transaction=False): for a given file
<|skel... | 14df8bbe8ee8f874fe423399b18afef911fe78c7 | <|skeleton|>
class UpdateStatus:
"""Block Update Status DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
<|body_0|>
def execute(self, conn, block_name, open_for_writing, ltime, transaction=False):
"""for a given file"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateStatus:
"""Block Update Status DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
DBFormatter.__init__(self, logger, dbi)
self.logger = logger
self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''
self.sql = '... | the_stack_v2_python_sparse | Server/Python/src/dbs/dao/Oracle/Block/UpdateStatus.py | vkuznet/DBS | train | 0 |
00f5220631f275b3e3dd0d3a1fd27482110ddf65 | [
"if '_xml_ns' in kwargs:\n self._xml_ns = kwargs['_xml_ns']\nif '_xml_ns_key' in kwargs:\n self._xml_ns_key = kwargs['_xml_ns_key']\nself.AzSF = AzSF\nself.KazPoly = KazPoly\nsuper(RgAzCompType, self).__init__(**kwargs)",
"look = SCPCOA.look\naz_sf = -look * numpy.sin(numpy.deg2rad(SCPCOA.DopplerConeAng)) /... | <|body_start_0|>
if '_xml_ns' in kwargs:
self._xml_ns = kwargs['_xml_ns']
if '_xml_ns_key' in kwargs:
self._xml_ns_key = kwargs['_xml_ns_key']
self.AzSF = AzSF
self.KazPoly = KazPoly
super(RgAzCompType, self).__init__(**kwargs)
<|end_body_0|>
<|body_start... | Parameters included for a Range, Doppler image. | RgAzCompType | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
<|bod... | stack_v2_sparse_classes_36k_train_016233 | 3,652 | permissive | [
{
"docstring": "Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs",
"name": "__init__",
"signature": "def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs)"
},
{
"docstring": "Expected to be called by the... | 2 | stack_v2_sparse_classes_30k_train_011033 | Implement the Python class `RgAzCompType` described below.
Class description:
Parameters included for a Range, Doppler image.
Method signatures and docstrings:
- def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs): Parameters ---------- AzSF : float KazPoly : Po... | Implement the Python class `RgAzCompType` described below.
Class description:
Parameters included for a Range, Doppler image.
Method signatures and docstrings:
- def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs): Parameters ---------- AzSF : float KazPoly : Po... | de1b1886f161a83b6c89aadc7a2c7cfc4892ef81 | <|skeleton|>
class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RgAzCompType:
"""Parameters included for a Range, Doppler image."""
def __init__(self, AzSF: float=None, KazPoly: Union[Poly1DType, numpy.ndarray, list, tuple]=None, **kwargs):
"""Parameters ---------- AzSF : float KazPoly : Poly1DType|numpy.ndarray|list|tuple kwargs"""
if '_xml_ns' in kw... | the_stack_v2_python_sparse | sarpy/io/complex/sicd_elements/RgAzComp.py | ngageoint/sarpy | train | 192 |
fe314ea5e607af2f7197b9d9588601c795cde4a6 | [
"self.certificate = certificate\nself.last_update_time_msecs = last_update_time_msecs\nself.private_key = private_key",
"if dictionary is None:\n return None\ncertificate = dictionary.get('certificate')\nlast_update_time_msecs = dictionary.get('lastUpdateTimeMsecs')\nprivate_key = dictionary.get('privateKey')\... | <|body_start_0|>
self.certificate = certificate
self.last_update_time_msecs = last_update_time_msecs
self.private_key = private_key
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
certificate = dictionary.get('certificate')
last_update_time... | Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last_update_time_msecs (long|int): LastUpdateTimeMsecs is a time in milliseconds at which c... | SslCertificateConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SslCertificateConfig:
"""Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last_update_time_msecs (long|int): LastUpda... | stack_v2_sparse_classes_36k_train_016234 | 2,140 | permissive | [
{
"docstring": "Constructor for the SslCertificateConfig class",
"name": "__init__",
"signature": "def __init__(self, certificate=None, last_update_time_msecs=None, private_key=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictiona... | 2 | null | Implement the Python class `SslCertificateConfig` described below.
Class description:
Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last... | Implement the Python class `SslCertificateConfig` described below.
Class description:
Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SslCertificateConfig:
"""Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last_update_time_msecs (long|int): LastUpda... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SslCertificateConfig:
"""Implementation of the 'SslCertificateConfig' model. SslCertificateConfig represents the SSL certificate object exposed to the user. Attributes: certificate (string): Certificate is a SSL certificate used by Iris HTTPS webserver. last_update_time_msecs (long|int): LastUpdateTimeMsecs i... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ssl_certificate_config.py | cohesity/management-sdk-python | train | 24 |
be38b6a161f0284d10e148c65b77da3e99bc3089 | [
"if support_regional_security_policy or support_net_lb:\n cls.NAME_ARG = flags.PriorityArgument('delete', is_plural=True)\n cls.NAME_ARG.AddArgument(parser, operation_type='delete', cust_metavar='PRIORITY')\n flags.AddRegionFlag(parser, 'delete')\n cls.SECURITY_POLICY_ARG = security_policies_flags.Secur... | <|body_start_0|>
if support_regional_security_policy or support_net_lb:
cls.NAME_ARG = flags.PriorityArgument('delete', is_plural=True)
cls.NAME_ARG.AddArgument(parser, operation_type='delete', cust_metavar='PRIORITY')
flags.AddRegionFlag(parser, 'delete')
cls.SEC... | Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy | DeleteHelper | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteHelper:
"""Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy"""
def Args(cls, parser, support_regional_security_policy, support_net_lb):... | stack_v2_sparse_classes_36k_train_016235 | 7,810 | permissive | [
{
"docstring": "Generates the flagset for a Delete command.",
"name": "Args",
"signature": "def Args(cls, parser, support_regional_security_policy, support_net_lb)"
},
{
"docstring": "Validates arguments and deletes security policy rule(s).",
"name": "Run",
"signature": "def Run(cls, rel... | 2 | stack_v2_sparse_classes_30k_train_012638 | Implement the Python class `DeleteHelper` described below.
Class description:
Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy
Method signatures and docstrings:
- def ... | Implement the Python class `DeleteHelper` described below.
Class description:
Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy
Method signatures and docstrings:
- def ... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class DeleteHelper:
"""Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy"""
def Args(cls, parser, support_regional_security_policy, support_net_lb):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteHelper:
"""Delete Compute Engine security policy rules. *{command}* is used to delete security policy rules. ## EXAMPLES To delete the rule at priority 1000, run: $ {command} 1000 \\ --security-policy=my-policy"""
def Args(cls, parser, support_regional_security_policy, support_net_lb):
"""G... | the_stack_v2_python_sparse | lib/surface/compute/security_policies/rules/delete.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
316cf0f9a0f5244c77ae5c4478424145a7421a84 | [
"self.dt = collections.defaultdict(list)\nfor i in range(len(arr)):\n self.dt[arr[i]].append(i)",
"if value not in self.dt:\n return 0\na = self.dt[value]\nreturn bisect.bisect_right(a, right) - bisect.bisect_left(a, left)"
] | <|body_start_0|>
self.dt = collections.defaultdict(list)
for i in range(len(arr)):
self.dt[arr[i]].append(i)
<|end_body_0|>
<|body_start_1|>
if value not in self.dt:
return 0
a = self.dt[value]
return bisect.bisect_right(a, right) - bisect.bisect_left(a, ... | RangeFreqQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(... | stack_v2_sparse_classes_36k_train_016236 | 2,667 | no_license | [
{
"docstring": ":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(a,8) 2 , lower range should bisect_left bisect.bisec... | 2 | stack_v2_sparse_classes_30k_train_020592 | Implement the Python class `RangeFreqQuery` described below.
Class description:
Implement the RangeFreqQuery class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a... | Implement the Python class `RangeFreqQuery` described below.
Class description:
Implement the RangeFreqQuery class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RangeFreqQuery:
def __init__(self, arr):
""":type arr: List[int] thought: a hashmap to store a value's (index), use a binary search for the ranged count a = [2,5,8] bisect.bisect_left(a,1) 0 bisect.bisect_left(a,3) 1 bisect.bisect_left(a,5) 1 bisect.bisect_left(a,6) 2 bisect.bisect_left(a,8) 2 , lower... | the_stack_v2_python_sparse | design/N2080_RangeFrequencyQueries.py | zerghua/leetcode-python | train | 2 | |
84303400bafb7e79bfa0ee10cf5e4e8d3d916c23 | [
"if back:\n self.image = Image.open('./テストコード/Visualization/image/background.jpg')\nelse:\n self.image = Image.new('RGBA', self.__size, (255, 255, 255, 255))",
"draw = ImageDraw.Draw(self.image)\nfor pos in pos_list:\n self.draw_circle(draw, 3, float(pos[0]), float(pos[1]), (0, 255, 0))\nimage_list = np.... | <|body_start_0|>
if back:
self.image = Image.open('./テストコード/Visualization/image/background.jpg')
else:
self.image = Image.new('RGBA', self.__size, (255, 255, 255, 255))
<|end_body_0|>
<|body_start_1|>
draw = ImageDraw.Draw(self.image)
for pos in pos_list:
... | PlacePlotter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlacePlotter:
def __init__(self, back: bool):
"""Parameter back : bool 背景に衛星画像を表示するかどうか"""
<|body_0|>
def plot_places(self, pos_list, caption_list=None, color_list=None):
"""リスト型の複数の位置情報を描画する Parameter pos_list : list (lat, lon) の2要素の2次元 caption_list : list 画像に表示するラベ... | stack_v2_sparse_classes_36k_train_016237 | 2,137 | no_license | [
{
"docstring": "Parameter back : bool 背景に衛星画像を表示するかどうか",
"name": "__init__",
"signature": "def __init__(self, back: bool)"
},
{
"docstring": "リスト型の複数の位置情報を描画する Parameter pos_list : list (lat, lon) の2要素の2次元 caption_list : list 画像に表示するラベル (牛の個体番号など) color_list : list 塗りつぶしの色のリスト",
"name": "plo... | 3 | stack_v2_sparse_classes_30k_train_016261 | Implement the Python class `PlacePlotter` described below.
Class description:
Implement the PlacePlotter class.
Method signatures and docstrings:
- def __init__(self, back: bool): Parameter back : bool 背景に衛星画像を表示するかどうか
- def plot_places(self, pos_list, caption_list=None, color_list=None): リスト型の複数の位置情報を描画する Parameter ... | Implement the Python class `PlacePlotter` described below.
Class description:
Implement the PlacePlotter class.
Method signatures and docstrings:
- def __init__(self, back: bool): Parameter back : bool 背景に衛星画像を表示するかどうか
- def plot_places(self, pos_list, caption_list=None, color_list=None): リスト型の複数の位置情報を描画する Parameter ... | 9046329d57ef10b6643c9c6e7dcc3ea9b6294dee | <|skeleton|>
class PlacePlotter:
def __init__(self, back: bool):
"""Parameter back : bool 背景に衛星画像を表示するかどうか"""
<|body_0|>
def plot_places(self, pos_list, caption_list=None, color_list=None):
"""リスト型の複数の位置情報を描画する Parameter pos_list : list (lat, lon) の2要素の2次元 caption_list : list 画像に表示するラベ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlacePlotter:
def __init__(self, back: bool):
"""Parameter back : bool 背景に衛星画像を表示するかどうか"""
if back:
self.image = Image.open('./テストコード/Visualization/image/background.jpg')
else:
self.image = Image.new('RGBA', self.__size, (255, 255, 255, 255))
def plot_place... | the_stack_v2_python_sparse | COW_PROJECT/テストコード/Visualization/image/place_plot.py | FUKUSHUN/cow_python | train | 1 | |
b4754f2145aac4e720beebc0be5a5b35cbb76467 | [
"super().__init__(base_url='https://panacea.threatgrid.com/api/v3/feeds/', verify=verify)\nself.first_fetch = first_fetch\nself.feed_name = feed_name\nself.feed_tags = feed_tags\nself.tlp_color = tlp_color\nself.create_relationships = create_relationships\nself._api_key = api_key\nself._proxies = handle_proxy()",
... | <|body_start_0|>
super().__init__(base_url='https://panacea.threatgrid.com/api/v3/feeds/', verify=verify)
self.first_fetch = first_fetch
self.feed_name = feed_name
self.feed_tags = feed_tags
self.tlp_color = tlp_color
self.create_relationships = create_relationships
... | Client | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from wh... | stack_v2_sparse_classes_36k_train_016238 | 12,402 | permissive | [
{
"docstring": "Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from which to start fetching feeds feed_name: The feed names to fetch feed_tags: feed tags. tlp_color: Traffic Light Protocol color... | 2 | null | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships): Implements class for the feed. Args: api_key: API Key. verify: boolean, if *f... | Implement the Python class `Client` described below.
Class description:
Implement the Client class.
Method signatures and docstrings:
- def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships): Implements class for the feed. Args: api_key: API Key. verify: boolean, if *f... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from wh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Client:
def __init__(self, api_key, verify, first_fetch, feed_name, feed_tags, tlp_color, create_relationships):
"""Implements class for the feed. Args: api_key: API Key. verify: boolean, if *false* feed HTTPS server certificate is verified. Default: *false* first_fetch: The date from which to start f... | the_stack_v2_python_sparse | Packs/ThreatGrid/Integrations/FeedCiscoSecureMalwareAnalytics/FeedCiscoSecureMalwareAnalytics.py | demisto/content | train | 1,023 | |
446f93db141f6f425732417fb84e211bbd69465d | [
"super().__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.ffn = point_wise_feed_forward_network(dm, hidden)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm3 = tf.ke... | <|body_start_0|>
super().__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.ffn = point_wise_feed_forward_network(dm, hidden)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
self.layernorm2 = tf.keras.layers.Lay... | class DecoderBlock | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""class DecoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public ins... | stack_v2_sparse_classes_36k_train_016239 | 18,002 | no_license | [
{
"docstring": "* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attributes: * mha1 - the first MultiHeadAttention layer * mha2 - the second MultiHeadAttention lay... | 2 | stack_v2_sparse_classes_30k_train_002287 | Implement the Python class `DecoderBlock` described below.
Class description:
class DecoderBlock
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * d... | Implement the Python class `DecoderBlock` described below.
Class description:
class DecoderBlock
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): * dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * d... | 8ad4c2594ff78b345dbd92e9d54d2a143ac4071a | <|skeleton|>
class DecoderBlock:
"""class DecoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public ins... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""class DecoderBlock"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""* dm - the dimensionality of the model * h - the number of heads * hidden - the number of hidden units in the fully connected layer * drop_rate - the dropout rate Sets the following public instance attribu... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | jorgezafra94/holbertonschool-machine_learning | train | 1 |
1eb3c8de73a609a35018d22ee0c5e748e56a1127 | [
"self._log_dir = log_dir\nself._testbed_name = testbed_name\nself.results = records.TestResult()\nself._test_run_infos = []\nself._test_run_metadata = TestRunner._TestRunMetaData(log_dir, testbed_name)",
"root_output_path = self._test_run_metadata.generate_test_run_log_path()\nlogger.setup_test_logger(root_output... | <|body_start_0|>
self._log_dir = log_dir
self._testbed_name = testbed_name
self.results = records.TestResult()
self._test_run_infos = []
self._test_run_metadata = TestRunner._TestRunMetaData(log_dir, testbed_name)
<|end_body_0|>
<|body_start_1|>
root_output_path = self._... | The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all tests that have been added to this runner. Attributes: results: records.TestRes... | TestRunner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRunner:
"""The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all tests that have been added to this runner... | stack_v2_sparse_classes_36k_train_016240 | 16,191 | permissive | [
{
"docstring": "Constructor for TestRunner. Args: log_dir: string, root folder where to write logs testbed_name: string, name of the testbed to run tests on",
"name": "__init__",
"signature": "def __init__(self, log_dir, testbed_name)"
},
{
"docstring": "Starts and stops a logging context for a ... | 5 | null | Implement the Python class `TestRunner` described below.
Class description:
The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all te... | Implement the Python class `TestRunner` described below.
Class description:
The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all te... | 6392f83acf512fb9e3a9229858bf9fd26e9d7278 | <|skeleton|>
class TestRunner:
"""The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all tests that have been added to this runner... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRunner:
"""The class that instantiates test classes, executes tests, and report results. One TestRunner instance is associated with one specific output folder and testbed. TestRunner.run() will generate a single set of output files and results for all tests that have been added to this runner. Attributes:... | the_stack_v2_python_sparse | mobly/test_runner.py | google/mobly | train | 624 |
1f5dd48e3a1863222ab6ce02b6c97ed368020faa | [
"self.layers = ModuleList([DetrTransformerEncoderLayer(**self.layer_cfg) for _ in range(self.num_layers)])\nembed_dims = self.layers[0].embed_dims\nself.embed_dims = embed_dims\nself.query_scale = MLP(embed_dims, embed_dims, embed_dims, 2)",
"for layer in self.layers:\n pos_scales = self.query_scale(query)\n ... | <|body_start_0|>
self.layers = ModuleList([DetrTransformerEncoderLayer(**self.layer_cfg) for _ in range(self.num_layers)])
embed_dims = self.layers[0].embed_dims
self.embed_dims = embed_dims
self.query_scale = MLP(embed_dims, embed_dims, embed_dims, 2)
<|end_body_0|>
<|body_start_1|>
... | Encoder of DAB-DETR. | DABDetrTransformerEncoder | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DABDetrTransformerEncoder:
"""Encoder of DAB-DETR."""
def _init_layers(self):
"""Initialize encoder layers."""
<|body_0|>
def forward(self, query: Tensor, query_pos: Tensor, key_padding_mask: Tensor, **kwargs):
"""Forward function of encoder. Args: query (Tensor)... | stack_v2_sparse_classes_36k_train_016241 | 11,683 | permissive | [
{
"docstring": "Initialize encoder layers.",
"name": "_init_layers",
"signature": "def _init_layers(self)"
},
{
"docstring": "Forward function of encoder. Args: query (Tensor): Input queries of encoder, has shape (bs, num_queries, dim). query_pos (Tensor): The positional embeddings of the querie... | 2 | null | Implement the Python class `DABDetrTransformerEncoder` described below.
Class description:
Encoder of DAB-DETR.
Method signatures and docstrings:
- def _init_layers(self): Initialize encoder layers.
- def forward(self, query: Tensor, query_pos: Tensor, key_padding_mask: Tensor, **kwargs): Forward function of encoder.... | Implement the Python class `DABDetrTransformerEncoder` described below.
Class description:
Encoder of DAB-DETR.
Method signatures and docstrings:
- def _init_layers(self): Initialize encoder layers.
- def forward(self, query: Tensor, query_pos: Tensor, key_padding_mask: Tensor, **kwargs): Forward function of encoder.... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class DABDetrTransformerEncoder:
"""Encoder of DAB-DETR."""
def _init_layers(self):
"""Initialize encoder layers."""
<|body_0|>
def forward(self, query: Tensor, query_pos: Tensor, key_padding_mask: Tensor, **kwargs):
"""Forward function of encoder. Args: query (Tensor)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DABDetrTransformerEncoder:
"""Encoder of DAB-DETR."""
def _init_layers(self):
"""Initialize encoder layers."""
self.layers = ModuleList([DetrTransformerEncoderLayer(**self.layer_cfg) for _ in range(self.num_layers)])
embed_dims = self.layers[0].embed_dims
self.embed_dims =... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/layers/transformer/dab_detr_layers.py | alldatacenter/alldata | train | 774 |
a96019a7ab745e4adaddd29519ebac4605054970 | [
"self.parent = parent\ncontent = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)\nPageTemplate.__init__(self, 'MyTemplate', [content])\nself.logo = self.getImageFromZODB('logo')",
"try:\n logo = getattr(self.parent.context, name)\nexcept Attri... | <|body_start_0|>
self.parent = parent
content = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)
PageTemplate.__init__(self, 'MyTemplate', [content])
self.logo = self.getImageFromZODB('logo')
<|end_body_0|>
<|body_start_... | Our own page template. | MyPageTemplate | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
<|body_0|>
def getImageFromZODB(self, name):
"""Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_016242 | 6,791 | permissive | [
{
"docstring": "Initialise our page template.",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.",
"name": "getImageFromZODB",
"signature": "def getImageFromZODB(self, name)... | 3 | stack_v2_sparse_classes_30k_train_007644 | Implement the Python class `MyPageTemplate` described below.
Class description:
Our own page template.
Method signatures and docstrings:
- def __init__(self, parent): Initialise our page template.
- def getImageFromZODB(self, name): Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.
- ... | Implement the Python class `MyPageTemplate` described below.
Class description:
Our own page template.
Method signatures and docstrings:
- def __init__(self, parent): Initialise our page template.
- def getImageFromZODB(self, name): Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high.
- ... | c28aa50e2d6d3451b47e114094a86c03c87d4c50 | <|skeleton|>
class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
<|body_0|>
def getImageFromZODB(self, name):
"""Retrieves an Image from the ZODB, converts it to PIL, and makes it 0.75 inch high."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyPageTemplate:
"""Our own page template."""
def __init__(self, parent):
"""Initialise our page template."""
self.parent = parent
content = Frame(0.75 * inch, 0.5 * inch, parent.document.pagesize[0] - 1.25 * inch, parent.document.pagesize[1] - 1.5 * inch)
PageTemplate.__in... | the_stack_v2_python_sparse | demos/rlzope/rlzope.py | MrBitBucket/reportlab-mirror | train | 64 |
b70af2b025fe6194791d7bc5e9f2f772921e4b76 | [
"environment_builds = models.EnvironmentBuild.query.all()\nif not environment_builds:\n environment_builds = []\nreturn ({'environment_builds': [envb.as_dict() for envb in environment_builds]}, 200)",
"post_data = request.get_json()\nbuilds_requests = post_data['environment_build_requests']\nbuilds_requests = ... | <|body_start_0|>
environment_builds = models.EnvironmentBuild.query.all()
if not environment_builds:
environment_builds = []
return ({'environment_builds': [envb.as_dict() for envb in environment_builds]}, 200)
<|end_body_0|>
<|body_start_1|>
post_data = request.get_json()
... | EnvironmentBuildList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvironmentBuildList:
def get(self):
"""Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED"""
<|body_0|>
def post(self):
"""Queues a list of environment builds. Only unique requests are con... | stack_v2_sparse_classes_36k_train_016243 | 12,436 | permissive | [
{
"docstring": "Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Queues a list of environment builds. Only unique requests are considered, meaning that... | 2 | null | Implement the Python class `EnvironmentBuildList` described below.
Class description:
Implement the EnvironmentBuildList class.
Method signatures and docstrings:
- def get(self): Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED
- def post... | Implement the Python class `EnvironmentBuildList` described below.
Class description:
Implement the EnvironmentBuildList class.
Method signatures and docstrings:
- def get(self): Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED
- def post... | 0d78bf21e6da84754bd8ba8ebe4ff0d6631a92f9 | <|skeleton|>
class EnvironmentBuildList:
def get(self):
"""Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED"""
<|body_0|>
def post(self):
"""Queues a list of environment builds. Only unique requests are con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnvironmentBuildList:
def get(self):
"""Fetches all environment builds (past and present). The environment builds are either PENDING, STARTED, SUCCESS, FAILURE, ABORTED"""
environment_builds = models.EnvironmentBuild.query.all()
if not environment_builds:
environment_builds... | the_stack_v2_python_sparse | data/codefile/orchest@orchest__6b629d0__services$orchest-api$app$app$apis$namespace_environment_builds.py.target.py | ualberta-smr/PyMigBench | train | 1 | |
c88c742464ce8c083e3b76c7492893a16761d16f | [
"new_class = super().__new__(mcs, str(metaname), bases, dict_)\nif metaname != 'VersionedBase':\n register_plugin_table(new_class.__tablename__, new_class._plugin, new_class._version)\nreturn new_class",
"if isinstance(table, str):\n register_plugin_table(table, cls._plugin, cls._version)\nelse:\n regist... | <|body_start_0|>
new_class = super().__new__(mcs, str(metaname), bases, dict_)
if metaname != 'VersionedBase':
register_plugin_table(new_class.__tablename__, new_class._plugin, new_class._version)
return new_class
<|end_body_0|>
<|body_start_1|>
if isinstance(table, str):
... | Metaclass for objects returned by versioned_base factory | VersionedBaseMeta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionedBaseMeta:
"""Metaclass for objects returned by versioned_base factory"""
def __new__(mcs, metaname, bases, dict_):
"""This gets called when a class that subclasses VersionedBase is defined."""
<|body_0|>
def register_table(cls, table: Union[str, Table]) -> None:... | stack_v2_sparse_classes_36k_train_016244 | 10,294 | permissive | [
{
"docstring": "This gets called when a class that subclasses VersionedBase is defined.",
"name": "__new__",
"signature": "def __new__(mcs, metaname, bases, dict_)"
},
{
"docstring": "This can be used if a plugin is declaring non-declarative sqlalchemy tables. :param table: Can either be the nam... | 2 | null | Implement the Python class `VersionedBaseMeta` described below.
Class description:
Metaclass for objects returned by versioned_base factory
Method signatures and docstrings:
- def __new__(mcs, metaname, bases, dict_): This gets called when a class that subclasses VersionedBase is defined.
- def register_table(cls, ta... | Implement the Python class `VersionedBaseMeta` described below.
Class description:
Metaclass for objects returned by versioned_base factory
Method signatures and docstrings:
- def __new__(mcs, metaname, bases, dict_): This gets called when a class that subclasses VersionedBase is defined.
- def register_table(cls, ta... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class VersionedBaseMeta:
"""Metaclass for objects returned by versioned_base factory"""
def __new__(mcs, metaname, bases, dict_):
"""This gets called when a class that subclasses VersionedBase is defined."""
<|body_0|>
def register_table(cls, table: Union[str, Table]) -> None:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VersionedBaseMeta:
"""Metaclass for objects returned by versioned_base factory"""
def __new__(mcs, metaname, bases, dict_):
"""This gets called when a class that subclasses VersionedBase is defined."""
new_class = super().__new__(mcs, str(metaname), bases, dict_)
if metaname != 'V... | the_stack_v2_python_sparse | flexget/db_schema.py | BrutuZ/Flexget | train | 1 |
6025e5db41aa0cfaddb439bb0ff37a6db9fe24ce | [
"def preorder(root):\n if not root:\n return '#,'\n return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)\nreturn preorder(root)",
"if not data or data == '#':\n return\nnodes = data.split(',')\n\ndef preorder(i):\n if i >= len(nodes) or nodes[i] == '#':\n r... | <|body_start_0|>
def preorder(root):
if not root:
return '#,'
return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)
return preorder(root)
<|end_body_0|>
<|body_start_1|>
if not data or data == '#':
return
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def preorder(r... | stack_v2_sparse_classes_36k_train_016245 | 1,243 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_015730 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 3a5649357e0f21cbbc5e238351300cd706d533b3 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def preorder(root):
if not root:
return '#,'
return str(root.val) + ',' + self.serialize(root.left) + self.serialize(root.right)
return preorder(root)
... | the_stack_v2_python_sparse | leetcode-py/leetcode449.py | cicihou/LearningProject | train | 0 | |
f2c3778d249adad9cddc13fe93486d978467205a | [
"self.capacity = capacity\nself.data = {}\nself.head = DLL(0)\nself.tail = DLL(0)\nself.head.next = self.tail\nself.tail.prev = self.head",
"if key in self.data:\n cur = self.data[key][1]\n if cur.next:\n cur.next.prev = cur.prev\n if cur.prev:\n cur.prev.next = cur.next\n cur.next, cur.... | <|body_start_0|>
self.capacity = capacity
self.data = {}
self.head = DLL(0)
self.tail = DLL(0)
self.head.next = self.tail
self.tail.prev = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.data:
cur = self.data[key][1]
if cur.next:
... | 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: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_016246 | 1,528 | 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: void",
"name": "pu... | 3 | null | 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: void | 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: void
<|sk... | 763372587b9ca3f8be4c843427e4760c3e472d6b | <|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: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.data = {}
self.head = DLL(0)
self.tail = DLL(0)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
""":type key: int :rtyp... | the_stack_v2_python_sparse | 146.LRUCache/solution.py | ynXiang/LeetCode | train | 0 | |
4a9c3d47c77c3afe195a78d36f406d1ead16b517 | [
"self.sign_in(self.peter)\nself.assertContains(self.app_client.put('/docs/mydoc/tagblob?tags=0,1%2C2,3-4'), '\"statusText\": \"Saved\"')\nself.assertContains(self.app_client.put('/docs/mydoc/tagblob2?tags=0,1%2C2'), '\"statusText\": \"Saved\"')\ntags = Blob.get_by_key_name('myapp/mydoc/tagblob/').tags\nself.assertT... | <|body_start_0|>
self.sign_in(self.peter)
self.assertContains(self.app_client.put('/docs/mydoc/tagblob?tags=0,1%2C2,3-4'), '"statusText": "Saved"')
self.assertContains(self.app_client.put('/docs/mydoc/tagblob2?tags=0,1%2C2'), '"statusText": "Saved"')
tags = Blob.get_by_key_name('myapp/my... | TaggableTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaggableTest:
def test_tags(self):
"""Query string options should set and filter tags on blobs."""
<|body_0|>
def test_max(self):
"""The maximum number of tags should be enforced in the back-end."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.... | stack_v2_sparse_classes_36k_train_016247 | 28,221 | no_license | [
{
"docstring": "Query string options should set and filter tags on blobs.",
"name": "test_tags",
"signature": "def test_tags(self)"
},
{
"docstring": "The maximum number of tags should be enforced in the back-end.",
"name": "test_max",
"signature": "def test_max(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015138 | Implement the Python class `TaggableTest` described below.
Class description:
Implement the TaggableTest class.
Method signatures and docstrings:
- def test_tags(self): Query string options should set and filter tags on blobs.
- def test_max(self): The maximum number of tags should be enforced in the back-end. | Implement the Python class `TaggableTest` described below.
Class description:
Implement the TaggableTest class.
Method signatures and docstrings:
- def test_tags(self): Query string options should set and filter tags on blobs.
- def test_max(self): The maximum number of tags should be enforced in the back-end.
<|ske... | fb15f64b16d5cda6370ee185d047072de82f8d09 | <|skeleton|>
class TaggableTest:
def test_tags(self):
"""Query string options should set and filter tags on blobs."""
<|body_0|>
def test_max(self):
"""The maximum number of tags should be enforced in the back-end."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaggableTest:
def test_tags(self):
"""Query string options should set and filter tags on blobs."""
self.sign_in(self.peter)
self.assertContains(self.app_client.put('/docs/mydoc/tagblob?tags=0,1%2C2,3-4'), '"statusText": "Saved"')
self.assertContains(self.app_client.put('/docs/m... | the_stack_v2_python_sparse | appengine/blobs/tests.py | mckoss/pageforest | train | 0 | |
e0c9f7d012343611c3c322118427951536e8a57a | [
"super().__init__(model=pref_model)\nself.add_module('outcome_model', outcome_model)\nself.register_buffer('previous_winner', previous_winner)\ntkwargs = {'dtype': pref_model.datapoints.dtype, 'device': pref_model.datapoints.device}\nstd_norm = torch.distributions.normal.Normal(torch.zeros(1, **tkwargs), torch.ones... | <|body_start_0|>
super().__init__(model=pref_model)
self.add_module('outcome_model', outcome_model)
self.register_buffer('previous_winner', previous_winner)
tkwargs = {'dtype': pref_model.datapoints.dtype, 'device': pref_model.datapoints.device}
std_norm = torch.distributions.nor... | Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO | AnalyticExpectedUtilityOfBestOption | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnalyticExpectedUtilityOfBestOption:
"""Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, previous_winner: Optional[Tensor]=None) -> None:
"""Analytic implementation o... | stack_v2_sparse_classes_36k_train_016248 | 7,676 | permissive | [
{
"docstring": "Analytic implementation of Expected Utility of the Best Option under the Laplace model (assumes a PairwiseGP is used as the preference model) as proposed in [Lin2022preference]_. Args: pref_model: The preference model that maps the outcomes (i.e., Y) to scalar-valued utility. outcome_model: A de... | 2 | null | Implement the Python class `AnalyticExpectedUtilityOfBestOption` described below.
Class description:
Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO
Method signatures and docstrings:
- def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, previous_winner: ... | Implement the Python class `AnalyticExpectedUtilityOfBestOption` described below.
Class description:
Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO
Method signatures and docstrings:
- def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, previous_winner: ... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class AnalyticExpectedUtilityOfBestOption:
"""Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, previous_winner: Optional[Tensor]=None) -> None:
"""Analytic implementation o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnalyticExpectedUtilityOfBestOption:
"""Analytic Prefential Expected Utility of Best Options, i.e., Analytical EUBO"""
def __init__(self, pref_model: Model, outcome_model: Optional[DeterministicModel]=None, previous_winner: Optional[Tensor]=None) -> None:
"""Analytic implementation of Expected Ut... | the_stack_v2_python_sparse | botorch/acquisition/preference.py | pytorch/botorch | train | 2,891 |
f23e90411ba6de38675b575baeb305f911ac803d | [
"self.dic = {}\nself.freqMap = collections.defaultdict(dQueue)\nself.cap = capacity\nself.minfreq = 0\nself.totalsize = 0",
"if self.cap <= 0:\n return -1\nif key not in self.dic:\n return -1\ncurrnode = self.dic[key]\ncurrfreq = currnode.freq\ncurrdlist = self.freqMap[currfreq]\ncurrdlist.removeNode(currno... | <|body_start_0|>
self.dic = {}
self.freqMap = collections.defaultdict(dQueue)
self.cap = capacity
self.minfreq = 0
self.totalsize = 0
<|end_body_0|>
<|body_start_1|>
if self.cap <= 0:
return -1
if key not in self.dic:
return -1
cur... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
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: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_016249 | 2,962 | 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: void",
"name": "pu... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache 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: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache 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: void
<|sk... | b0ce69985c51a9a794397cd98a996fca0e91d7d1 | <|skeleton|>
class LFUCache:
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: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.dic = {}
self.freqMap = collections.defaultdict(dQueue)
self.cap = capacity
self.minfreq = 0
self.totalsize = 0
def get(self, key):
""":type key: int :rtype: int"""
if se... | the_stack_v2_python_sparse | Solutions/460-LFU-Cache/python.py | JerryHu1994/LeetCode-Practice | train | 0 | |
694d30d01fbc910d05cab760c604425888f6983e | [
"self.data = data\nself.next = None\nreturn",
"if self.data == value:\n return True\nelse:\n return False"
] | <|body_start_0|>
self.data = data
self.next = None
return
<|end_body_0|>
<|body_start_1|>
if self.data == value:
return True
else:
return False
<|end_body_1|>
| Node | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def __init__(self, data):
"""constructor to initiate this object"""
<|body_0|>
def has_value(self, value):
"""method to compare the value with the node data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.data = data
self.next = N... | stack_v2_sparse_classes_36k_train_016250 | 4,807 | no_license | [
{
"docstring": "constructor to initiate this object",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "method to compare the value with the node data",
"name": "has_value",
"signature": "def has_value(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019428 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, data): constructor to initiate this object
- def has_value(self, value): method to compare the value with the node data | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def __init__(self, data): constructor to initiate this object
- def has_value(self, value): method to compare the value with the node data
<|skeleton|>
class Node:
def __init__(sel... | 33f710d423e8dd18a70e9426aab1810ae1c44b29 | <|skeleton|>
class Node:
def __init__(self, data):
"""constructor to initiate this object"""
<|body_0|>
def has_value(self, value):
"""method to compare the value with the node data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Node:
def __init__(self, data):
"""constructor to initiate this object"""
self.data = data
self.next = None
return
def has_value(self, value):
"""method to compare the value with the node data"""
if self.data == value:
return True
else:
... | the_stack_v2_python_sparse | SingleLinkedList.py | raindewGH/test | train | 0 | |
ae734686acc72409694c7301a992e4b8d7b19ab9 | [
"threading.Thread.__init__(self)\nself.daemon = True\nself.queueIn = queueIn\nself.queueOut = queueOut\nself.proxyList = proxyList\nself.rxList = [re.compile(item) for item in googleResultsStrList]",
"while not self.queueIn.empty():\n host = self.queueIn.get()\n data = self.GetData(host)\n print('- %s: %... | <|body_start_0|>
threading.Thread.__init__(self)
self.daemon = True
self.queueIn = queueIn
self.queueOut = queueOut
self.proxyList = proxyList
self.rxList = [re.compile(item) for item in googleResultsStrList]
<|end_body_0|>
<|body_start_1|>
while not self.queueIn... | Поточный чекер кейвордов в гугле | KeywordsChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordsChecker:
"""Поточный чекер кейвордов в гугле"""
def __init__(self, queueIn, queueOut, proxyList):
"""Инициализация"""
<|body_0|>
def run(self):
"""Обработка очередей"""
<|body_1|>
def GetData(self, host):
"""Делаем запрос в гугл"""
... | stack_v2_sparse_classes_36k_train_016251 | 10,867 | no_license | [
{
"docstring": "Инициализация",
"name": "__init__",
"signature": "def __init__(self, queueIn, queueOut, proxyList)"
},
{
"docstring": "Обработка очередей",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Делаем запрос в гугл",
"name": "GetData",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_002578 | Implement the Python class `KeywordsChecker` described below.
Class description:
Поточный чекер кейвордов в гугле
Method signatures and docstrings:
- def __init__(self, queueIn, queueOut, proxyList): Инициализация
- def run(self): Обработка очередей
- def GetData(self, host): Делаем запрос в гугл | Implement the Python class `KeywordsChecker` described below.
Class description:
Поточный чекер кейвордов в гугле
Method signatures and docstrings:
- def __init__(self, queueIn, queueOut, proxyList): Инициализация
- def run(self): Обработка очередей
- def GetData(self, host): Делаем запрос в гугл
<|skeleton|>
class ... | d2771bf04aa187dda6d468883a5a167237589369 | <|skeleton|>
class KeywordsChecker:
"""Поточный чекер кейвордов в гугле"""
def __init__(self, queueIn, queueOut, proxyList):
"""Инициализация"""
<|body_0|>
def run(self):
"""Обработка очередей"""
<|body_1|>
def GetData(self, host):
"""Делаем запрос в гугл"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeywordsChecker:
"""Поточный чекер кейвордов в гугле"""
def __init__(self, queueIn, queueOut, proxyList):
"""Инициализация"""
threading.Thread.__init__(self)
self.daemon = True
self.queueIn = queueIn
self.queueOut = queueOut
self.proxyList = proxyList
... | the_stack_v2_python_sparse | tools/freehostsfinder.py | cash2one/doorscenter | train | 0 |
9c879ac91c2692085274e3567788772c03231a63 | [
"try:\n trigger = await self.nyuki.storage.triggers.get_one(tid)\nexcept AutoReconnect:\n return Response(status=503)\nif not trigger:\n return Response(status=404)\nreturn Response(trigger)",
"try:\n trigger = await self.nyuki.storage.triggers.get_one(tid)\nexcept AutoReconnect:\n return Response(... | <|body_start_0|>
try:
trigger = await self.nyuki.storage.triggers.get_one(tid)
except AutoReconnect:
return Response(status=503)
if not trigger:
return Response(status=404)
return Response(trigger)
<|end_body_0|>
<|body_start_1|>
try:
... | ApiWorkflowTrigger | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"LicenseRef-scancode-warran... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiWorkflowTrigger:
async def get(self, request, tid):
"""Return a single trigger form"""
<|body_0|>
async def delete(self, request, tid):
"""Delete a trigger form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
trigger = await self... | stack_v2_sparse_classes_36k_train_016252 | 15,185 | permissive | [
{
"docstring": "Return a single trigger form",
"name": "get",
"signature": "async def get(self, request, tid)"
},
{
"docstring": "Delete a trigger form",
"name": "delete",
"signature": "async def delete(self, request, tid)"
}
] | 2 | null | Implement the Python class `ApiWorkflowTrigger` described below.
Class description:
Implement the ApiWorkflowTrigger class.
Method signatures and docstrings:
- async def get(self, request, tid): Return a single trigger form
- async def delete(self, request, tid): Delete a trigger form | Implement the Python class `ApiWorkflowTrigger` described below.
Class description:
Implement the ApiWorkflowTrigger class.
Method signatures and docstrings:
- async def get(self, request, tid): Return a single trigger form
- async def delete(self, request, tid): Delete a trigger form
<|skeleton|>
class ApiWorkflowT... | f185fababee380660930243515652093855acfe7 | <|skeleton|>
class ApiWorkflowTrigger:
async def get(self, request, tid):
"""Return a single trigger form"""
<|body_0|>
async def delete(self, request, tid):
"""Delete a trigger form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiWorkflowTrigger:
async def get(self, request, tid):
"""Return a single trigger form"""
try:
trigger = await self.nyuki.storage.triggers.get_one(tid)
except AutoReconnect:
return Response(status=503)
if not trigger:
return Response(status=4... | the_stack_v2_python_sparse | nyuki/workflow/api/instances.py | d-nery/nyuki | train | 0 | |
ae9c066f9dac57118147a05f618b6acbc2d519e1 | [
"authorized: bool = True\nif authorized:\n query = Users.objects()\n fields = {'email', 'password', 'name', 'phone', 'roles'}\n return jsonify(convert_query(query, fields))\nelse:\n return forbidden()",
"authorized: bool = True\nif authorized:\n output = Users.objects.delete()\n return jsonify(o... | <|body_start_0|>
authorized: bool = True
if authorized:
query = Users.objects()
fields = {'email', 'password', 'name', 'phone', 'roles'}
return jsonify(convert_query(query, fields))
else:
return forbidden()
<|end_body_0|>
<|body_start_1|>
... | Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Flask(__name__) >>> app.config.update(default_config) >>> api = Api(app=app) ... | UsersApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersApi:
"""Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Flask(__name__) >>> app.config.update(def... | stack_v2_sparse_classes_36k_train_016253 | 7,554 | no_license | [
{
"docstring": "GET response method for acquiring all user data. JSON Web Token is required. Authorization is required: Access(admin=true) :return: JSON object",
"name": "get",
"signature": "def get(self) -> Response"
},
{
"docstring": "DELETE response method for deleting all users. JSON Web Tok... | 3 | stack_v2_sparse_classes_30k_train_001893 | Implement the Python class `UsersApi` described below.
Class description:
Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Fl... | Implement the Python class `UsersApi` described below.
Class description:
Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Fl... | 7f44c736c95866aaf820627ea54d3f00b3ada779 | <|skeleton|>
class UsersApi:
"""Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Flask(__name__) >>> app.config.update(def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsersApi:
"""Flask-resftul resource for returning db.user collection. :Example: >>> from flask import Flask >>> from flask_restful import Api >>> from app import default_config # Create flask app, config, and resftul api, then add UsersApi route >>> app = Flask(__name__) >>> app.config.update(default_config) ... | the_stack_v2_python_sparse | backend/uimpactify/controller/user.py | ObaidaSaleh/E-learning-app | train | 1 |
487b06c5b909cd6a9f8d5679a30579f2b43bb0ad | [
"units = None\nself.source_files = []\nif hasattr(self, 'find_code_units'):\n self.find_code_units(morfs)\nelse:\n units = self.find_file_reporters(morfs)\nif units is None:\n units = self.code_units if hasattr(self, 'code_units') else self.file_reporters\nfor cu in units:\n try:\n self.parse_fil... | <|body_start_0|>
units = None
self.source_files = []
if hasattr(self, 'find_code_units'):
self.find_code_units(morfs)
else:
units = self.find_file_reporters(morfs)
if units is None:
units = self.code_units if hasattr(self, 'code_units') else se... | Custom coverage.py reporter for coveralls.io | CoverallReporter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoverallReporter:
"""Custom coverage.py reporter for coveralls.io"""
def report(self, morfs=None):
"""Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write the json to."""
<|body_0|>
def get_hits(self,... | stack_v2_sparse_classes_36k_train_016254 | 4,797 | permissive | [
{
"docstring": "Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write the json to.",
"name": "report",
"signature": "def report(self, morfs=None)"
},
{
"docstring": "Source file stats for each line. * A positive integer if the... | 4 | null | Implement the Python class `CoverallReporter` described below.
Class description:
Custom coverage.py reporter for coveralls.io
Method signatures and docstrings:
- def report(self, morfs=None): Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write t... | Implement the Python class `CoverallReporter` described below.
Class description:
Custom coverage.py reporter for coveralls.io
Method signatures and docstrings:
- def report(self, morfs=None): Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write t... | 359db63ff1fa79696b7bc803bcfa0042bff8ab44 | <|skeleton|>
class CoverallReporter:
"""Custom coverage.py reporter for coveralls.io"""
def report(self, morfs=None):
"""Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write the json to."""
<|body_0|>
def get_hits(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoverallReporter:
"""Custom coverage.py reporter for coveralls.io"""
def report(self, morfs=None):
"""Generate a part of json report for coveralls `morfs` is a list of modules or filenames. `outfile` is a file object to write the json to."""
units = None
self.source_files = []
... | the_stack_v2_python_sparse | python/flask-webservices-labs/flask-graphql/.venv/lib/python2.7/site-packages/coveralls/reporter.py | marcosptf/fedora | train | 6 |
cedcdac85359e60fa882d5612bff95852eaf1e20 | [
"squares = [i ** 2 for i in range(1, int(math.sqrt(n)) + 1)]\ndp = [0] * (n + 1)\nfor i in range(1, n + 1):\n if i in squares:\n dp[i] = 1\n else:\n choices = [dp[i - square] for square in squares if i > square]\n dp[i] = 1 + min(choices)\nreturn dp[-1]",
"dp = [0] * (n + 1)\nfor i in r... | <|body_start_0|>
squares = [i ** 2 for i in range(1, int(math.sqrt(n)) + 1)]
dp = [0] * (n + 1)
for i in range(1, n + 1):
if i in squares:
dp[i] = 1
else:
choices = [dp[i - square] for square in squares if i > square]
dp[i] ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值"""
<|body_0|>
def numSquares_2(self, n: int) -> int:
"""超时"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_016255 | 1,604 | no_license | [
{
"docstring": "例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值",
"name": "numSquares",
"signature": "def numSquares(self, n: int) -> int"
},
{
"docstring": "超时",
"name": "numSquares_2",
"signature": "def numSquares_2(self, n: in... | 2 | stack_v2_sparse_classes_30k_train_011989 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: 例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值
- def numSquares_2(self, n: int) -... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: 例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值
- def numSquares_2(self, n: int) -... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值"""
<|body_0|>
def numSquares_2(self, n: int) -> int:
"""超时"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n: int) -> int:
"""例如: n = 15 小于 n 的平方数:1、4、9 dp[15] = dp[15 - 1] + 1 dp[15] = dp[15 - 4] + 1 dp[15] = dp[15 - 9] + 1 三者中最小的值"""
squares = [i ** 2 for i in range(1, int(math.sqrt(n)) + 1)]
dp = [0] * (n + 1)
for i in range(1, n + 1):
i... | the_stack_v2_python_sparse | .leetcode/279.完全平方数.py | xiaoruijiang/algorithm | train | 0 | |
716ec896226449afe3205e7c147ad000e9181a5d | [
"self.id_num = 0\nself.storage = {}\nself.visited = []\nself.map = m",
"dug = location.desc\nlocation.get_visited(self.id_num)\nprint(self.map)\nif dug in GEMS:\n self.storage[dug] = self.storage.get(dug, 0) + 1\nlocation.get_dug()\nself.visited.append(location)\ntime.sleep(0.5)",
"def should_stop(self) -> b... | <|body_start_0|>
self.id_num = 0
self.storage = {}
self.visited = []
self.map = m
<|end_body_0|>
<|body_start_1|>
dug = location.desc
location.get_visited(self.id_num)
print(self.map)
if dug in GEMS:
self.storage[dug] = self.storage.get(dug, 0... | A class to represent the 'player' that collects gems on the map. | DrillBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DrillBot:
"""A class to represent the 'player' that collects gems on the map."""
def __init__(self, m: Map) -> None:
"""Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to record the map data. Construct an empty dictionary storage t... | stack_v2_sparse_classes_36k_train_016256 | 9,181 | no_license | [
{
"docstring": "Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to record the map data. Construct an empty dictionary storage to record the gems the drillbot digs. Construct an empty list visited to record all the positions that the drillbot has visited. Set ... | 3 | null | Implement the Python class `DrillBot` described below.
Class description:
A class to represent the 'player' that collects gems on the map.
Method signatures and docstrings:
- def __init__(self, m: Map) -> None: Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to rec... | Implement the Python class `DrillBot` described below.
Class description:
A class to represent the 'player' that collects gems on the map.
Method signatures and docstrings:
- def __init__(self, m: Map) -> None: Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to rec... | c7437d387dc2b9a8039c60d8786373899c2e28bd | <|skeleton|>
class DrillBot:
"""A class to represent the 'player' that collects gems on the map."""
def __init__(self, m: Map) -> None:
"""Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to record the map data. Construct an empty dictionary storage t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DrillBot:
"""A class to represent the 'player' that collects gems on the map."""
def __init__(self, m: Map) -> None:
"""Construct a Drillbot object which can move to different tiles and collect gems. Given a Map object m to record the map data. Construct an empty dictionary storage to record the ... | the_stack_v2_python_sparse | CSC148/A2/part1/final drillbot.py | xxcocoymlxx/Study-Notes | train | 2 |
18994cec870428a6d79abf69af4dd5b7cfef635b | [
"self.model = model\nbase_dir = os.path.split(os.path.realpath(__file__))[0]\nos.chdir(base_dir)\nself.model_config = yaml.load(open('utils/paddlecv.yml', 'rb'), Loader=yaml.Loader)\nself.yml = self.model_config[self.model]['yml']\nself.input = self.model_config[self.model]['input']\nself.output_json = self.model_c... | <|body_start_0|>
self.model = model
base_dir = os.path.split(os.path.realpath(__file__))[0]
os.chdir(base_dir)
self.model_config = yaml.load(open('utils/paddlecv.yml', 'rb'), Loader=yaml.Loader)
self.yml = self.model_config[self.model]['yml']
self.input = self.model_confi... | TestPaddleCVPredict | TestPaddleCVPredict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPaddleCVPredict:
"""TestPaddleCVPredict"""
def __init__(self, model=''):
"""__init__"""
<|body_0|>
def test_cv_predict(self, run_mode='paddle', device='CPU'):
"""test_cv_predict"""
<|body_1|>
def test_wheel_predict(self):
"""test_wheel_pr... | stack_v2_sparse_classes_36k_train_016257 | 3,002 | no_license | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self, model='')"
},
{
"docstring": "test_cv_predict",
"name": "test_cv_predict",
"signature": "def test_cv_predict(self, run_mode='paddle', device='CPU')"
},
{
"docstring": "test_wheel_predict",
"name":... | 3 | null | Implement the Python class `TestPaddleCVPredict` described below.
Class description:
TestPaddleCVPredict
Method signatures and docstrings:
- def __init__(self, model=''): __init__
- def test_cv_predict(self, run_mode='paddle', device='CPU'): test_cv_predict
- def test_wheel_predict(self): test_wheel_predict | Implement the Python class `TestPaddleCVPredict` described below.
Class description:
TestPaddleCVPredict
Method signatures and docstrings:
- def __init__(self, model=''): __init__
- def test_cv_predict(self, run_mode='paddle', device='CPU'): test_cv_predict
- def test_wheel_predict(self): test_wheel_predict
<|skelet... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class TestPaddleCVPredict:
"""TestPaddleCVPredict"""
def __init__(self, model=''):
"""__init__"""
<|body_0|>
def test_cv_predict(self, run_mode='paddle', device='CPU'):
"""test_cv_predict"""
<|body_1|>
def test_wheel_predict(self):
"""test_wheel_pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPaddleCVPredict:
"""TestPaddleCVPredict"""
def __init__(self, model=''):
"""__init__"""
self.model = model
base_dir = os.path.split(os.path.realpath(__file__))[0]
os.chdir(base_dir)
self.model_config = yaml.load(open('utils/paddlecv.yml', 'rb'), Loader=yaml.Loa... | the_stack_v2_python_sparse | models/paddlecv/PaddleCVTestFramwork.py | PaddlePaddle/PaddleTest | train | 42 |
2be5aaedec134dfb0ec8bf5a54cc52652ad19cf8 | [
"trimmed_r1 = re.sub('.fastq.gz', '_val_1.fq.gz', self.r1)\ntrimmed_r2 = re.sub('.fastq.gz', '_val_2.fq.gz', self.r2)\nif not os.path.exists(trimmed_r1):\n trim_cmd = ('time trim_galore -o {} --gzip ' + '--quality 0 --paired {} {}').format(self.home_dir + 'FASTQ/', self.r1, self.r2)\n print(trim_cmd)\n sub... | <|body_start_0|>
trimmed_r1 = re.sub('.fastq.gz', '_val_1.fq.gz', self.r1)
trimmed_r2 = re.sub('.fastq.gz', '_val_2.fq.gz', self.r2)
if not os.path.exists(trimmed_r1):
trim_cmd = ('time trim_galore -o {} --gzip ' + '--quality 0 --paired {} {}').format(self.home_dir + 'FASTQ/', self.r... | Create a FastQ object with QC commands. | fq_pair_qc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fq_pair_qc:
"""Create a FastQ object with QC commands."""
def TrimAdapters(self):
"""Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 files (Source: https://www.biostars.org/p/256388/#256612)... | stack_v2_sparse_classes_36k_train_016258 | 5,699 | no_license | [
{
"docstring": "Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 files (Source: https://www.biostars.org/p/256388/#256612) Checking ASCII scores: https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Inf... | 2 | stack_v2_sparse_classes_30k_train_016493 | Implement the Python class `fq_pair_qc` described below.
Class description:
Create a FastQ object with QC commands.
Method signatures and docstrings:
- def TrimAdapters(self): Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 ... | Implement the Python class `fq_pair_qc` described below.
Class description:
Create a FastQ object with QC commands.
Method signatures and docstrings:
- def TrimAdapters(self): Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 ... | eb84ab40dcd2915b09a3126948e83ebdf981ec3d | <|skeleton|>
class fq_pair_qc:
"""Create a FastQ object with QC commands."""
def TrimAdapters(self):
"""Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 files (Source: https://www.biostars.org/p/256388/#256612)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fq_pair_qc:
"""Create a FastQ object with QC commands."""
def TrimAdapters(self):
"""Trime adapters. Manual/methods: https://github.com/FelixKrueger/TrimGalore/blob/master/Docs/Trim_Galore_User_Guide.md Use the val_1 and val_2 files (Source: https://www.biostars.org/p/256388/#256612) Checking ASC... | the_stack_v2_python_sparse | code_variants/align_qc_class.py | frichter/embryo_rnaseq | train | 2 |
42e276dba5736f372e79251e55eb095fa8cd7a88 | [
"super(BayesianLinearRegression, self).__init__(basis_function, mu, s, deg)\nself.S = None\nself.M = None\nself.N = 0\nself.alpha = alpha\nself.beta = beta",
"self.N = X.shape[0]\nif optimize_evidence:\n self._optimize_evidence(X, y, max_iter, threshold)\ndesign_mat = self.make_design_mat(X)\nself.M = design_m... | <|body_start_0|>
super(BayesianLinearRegression, self).__init__(basis_function, mu, s, deg)
self.S = None
self.M = None
self.N = 0
self.alpha = alpha
self.beta = beta
<|end_body_0|>
<|body_start_1|>
self.N = X.shape[0]
if optimize_evidence:
se... | BayesianLinearRegression | BayesianLinearRegression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianLinearRegression:
"""BayesianLinearRegression"""
def __init__(self, alpha=0.1, beta=0.1, basis_function='gauss', mu=None, s=None, deg=None):
"""Args: alpha (float) : regularization parameter beta (float) : precision parameter basis_funtion (str) : "gauss" or "sigmoid" or "pol... | stack_v2_sparse_classes_36k_train_016259 | 8,340 | permissive | [
{
"docstring": "Args: alpha (float) : regularization parameter beta (float) : precision parameter basis_funtion (str) : \"gauss\" or \"sigmoid\" or \"polynomial\" mu (1-D array) : mean parameter s (1-D array) : standard deviation parameter deg (int) : max degree of polynomial features Node: alpha/beta performs ... | 6 | stack_v2_sparse_classes_30k_train_006517 | Implement the Python class `BayesianLinearRegression` described below.
Class description:
BayesianLinearRegression
Method signatures and docstrings:
- def __init__(self, alpha=0.1, beta=0.1, basis_function='gauss', mu=None, s=None, deg=None): Args: alpha (float) : regularization parameter beta (float) : precision par... | Implement the Python class `BayesianLinearRegression` described below.
Class description:
BayesianLinearRegression
Method signatures and docstrings:
- def __init__(self, alpha=0.1, beta=0.1, basis_function='gauss', mu=None, s=None, deg=None): Args: alpha (float) : regularization parameter beta (float) : precision par... | 992f2c07e88b2bad331e08303bdba84684f04d40 | <|skeleton|>
class BayesianLinearRegression:
"""BayesianLinearRegression"""
def __init__(self, alpha=0.1, beta=0.1, basis_function='gauss', mu=None, s=None, deg=None):
"""Args: alpha (float) : regularization parameter beta (float) : precision parameter basis_funtion (str) : "gauss" or "sigmoid" or "pol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianLinearRegression:
"""BayesianLinearRegression"""
def __init__(self, alpha=0.1, beta=0.1, basis_function='gauss', mu=None, s=None, deg=None):
"""Args: alpha (float) : regularization parameter beta (float) : precision parameter basis_funtion (str) : "gauss" or "sigmoid" or "polynomial" mu (... | the_stack_v2_python_sparse | prml/linear_regression.py | hedwig100/PRML | train | 1 |
ac7133c5114e950fd81979f27e5219fafa1a574f | [
"memory = set()\nl = len(graph)\nedge = [[] for _ in range(l)]\nfor i, line in enumerate(graph):\n for j in range(i + 1, l):\n if line[j] == 1:\n edge[i].append(j)\n edge[j].append(i)\n\ndef dfs(node, part_set):\n if node in memory:\n return part_set\n memory.add(node)\n... | <|body_start_0|>
memory = set()
l = len(graph)
edge = [[] for _ in range(l)]
for i, line in enumerate(graph):
for j in range(i + 1, l):
if line[j] == 1:
edge[i].append(j)
edge[j].append(i)
def dfs(node, part_set... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minMalwareSpread(self, graph, initial):
""":type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms"""
<|body_0|>
def minMalwareSpread_1(self, graph, initial):
""":type graph: List[List[int]] :type initial: List[int] :rtype: int 100ms"""... | stack_v2_sparse_classes_36k_train_016260 | 3,817 | no_license | [
{
"docstring": ":type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms",
"name": "minMalwareSpread",
"signature": "def minMalwareSpread(self, graph, initial)"
},
{
"docstring": ":type graph: List[List[int]] :type initial: List[int] :rtype: int 100ms",
"name": "minMalwareSpr... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMalwareSpread(self, graph, initial): :type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms
- def minMalwareSpread_1(self, graph, initial): :type graph: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minMalwareSpread(self, graph, initial): :type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms
- def minMalwareSpread_1(self, graph, initial): :type graph: ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def minMalwareSpread(self, graph, initial):
""":type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms"""
<|body_0|>
def minMalwareSpread_1(self, graph, initial):
""":type graph: List[List[int]] :type initial: List[int] :rtype: int 100ms"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minMalwareSpread(self, graph, initial):
""":type graph: List[List[int]] :type initial: List[int] :rtype: int 244 ms"""
memory = set()
l = len(graph)
edge = [[] for _ in range(l)]
for i, line in enumerate(graph):
for j in range(i + 1, l):
... | the_stack_v2_python_sparse | MinimizeMalwareSpread_HARD_924.py | 953250587/leetcode-python | train | 2 | |
2a8fddd7b954d845e9579ec98b531b02bfb0ed32 | [
"self.bot = bot\nself.guild = guild\nself.streamer_role = streamer\nself.live_role = live\nself.streamer_mode.start()",
"guild = self.bot.get_guild(self.guild)\nrole = utils.get(guild.roles, name=self.streamer_role)\nliverole = utils.get(guild.roles, name=self.live_role)\nstreamers = role.members\nfor streamer in... | <|body_start_0|>
self.bot = bot
self.guild = guild
self.streamer_role = streamer
self.live_role = live
self.streamer_mode.start()
<|end_body_0|>
<|body_start_1|>
guild = self.bot.get_guild(self.guild)
role = utils.get(guild.roles, name=self.streamer_role)
... | The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed streamer_role (str): The name of the role with all the people to be checked if stream... | StreamerRole | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamerRole:
"""The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed streamer_role (str): The name of the role wit... | stack_v2_sparse_classes_36k_train_016261 | 3,186 | no_license | [
{
"docstring": "Constructor for the StreamerRole class Args: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed streamer (str): The name of the role with the people who can be given the live role live (str): The name of the role given when someone i... | 2 | stack_v2_sparse_classes_30k_train_001886 | Implement the Python class `StreamerRole` described below.
Class description:
The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed stream... | Implement the Python class `StreamerRole` described below.
Class description:
The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed stream... | eba3dff8feaadbe81d87220d2cdebb771f64a505 | <|skeleton|>
class StreamerRole:
"""The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed streamer_role (str): The name of the role wit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamerRole:
"""The goal of this class is to give people whose discord activity shows streaming, and give them the Live role Attributes: bot (class): The discord.py bot object guild (int): The ID for the guild where the streamer role is to be managed streamer_role (str): The name of the role with all the peo... | the_stack_v2_python_sparse | cogs/streamer_role.py | zambam5/discord-bot | train | 3 |
93deaaefc92950bb0a26747f82bc7a4da22fea15 | [
"m = context.accessor.get_metric(name)\nif not m:\n rp.abort(404)\nreturn m.as_string_dict()",
"if not context.accessor.has_metric(name):\n return (\"Unknown metric: '%s'\" % name, 404)\npayload = request.json\nmetadata = bg_metric.MetricMetadata.create(aggregator=bg_metric.Aggregator.from_config_name(paylo... | <|body_start_0|>
m = context.accessor.get_metric(name)
if not m:
rp.abort(404)
return m.as_string_dict()
<|end_body_0|>
<|body_start_1|>
if not context.accessor.has_metric(name):
return ("Unknown metric: '%s'" % name, 404)
payload = request.json
m... | A Metric. | MetricResource | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
<|body_0|>
def post(self, name):
"""Update a metric."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = context.accessor.get_metric(name)
if not m:
rp.... | stack_v2_sparse_classes_36k_train_016262 | 2,775 | permissive | [
{
"docstring": "Get a metric.",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "Update a metric.",
"name": "post",
"signature": "def post(self, name)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000503 | Implement the Python class `MetricResource` described below.
Class description:
A Metric.
Method signatures and docstrings:
- def get(self, name): Get a metric.
- def post(self, name): Update a metric. | Implement the Python class `MetricResource` described below.
Class description:
A Metric.
Method signatures and docstrings:
- def get(self, name): Get a metric.
- def post(self, name): Update a metric.
<|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
... | 1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30 | <|skeleton|>
class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
<|body_0|>
def post(self, name):
"""Update a metric."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricResource:
"""A Metric."""
def get(self, name):
"""Get a metric."""
m = context.accessor.get_metric(name)
if not m:
rp.abort(404)
return m.as_string_dict()
def post(self, name):
"""Update a metric."""
if not context.accessor.has_metric... | the_stack_v2_python_sparse | biggraphite/cli/web/namespaces/biggraphite.py | criteo/biggraphite | train | 129 |
1c6315bf1ee497701ab03a0319aa9cf1024b13f0 | [
"url = '/createdbasket/'\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_code, 302)",
"url = '/createdbasket/'\nself.client.login(username=self.adminUN, password='pass')\nresponse = self.client.get(url, HTTP_HOST='website.domain')\nself.assertEqual(response.status_co... | <|body_start_0|>
url = '/createdbasket/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
<|end_body_0|>
<|body_start_1|>
url = '/createdbasket/'
self.client.login(username=self.adminUN, password='pass')
response = s... | CreatedBasketTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatedBasketTestCase:
def test_not_logged_in_no_basket(self):
"""Test that the basket view will redirect whilst not logged in and no basket."""
<|body_0|>
def test_logged_in_admin_no_basket(self):
"""Test that the basket view will redirect whilst logged in as admin ... | stack_v2_sparse_classes_36k_train_016263 | 26,818 | permissive | [
{
"docstring": "Test that the basket view will redirect whilst not logged in and no basket.",
"name": "test_not_logged_in_no_basket",
"signature": "def test_not_logged_in_no_basket(self)"
},
{
"docstring": "Test that the basket view will redirect whilst logged in as admin and no basket.",
"n... | 3 | null | Implement the Python class `CreatedBasketTestCase` described below.
Class description:
Implement the CreatedBasketTestCase class.
Method signatures and docstrings:
- def test_not_logged_in_no_basket(self): Test that the basket view will redirect whilst not logged in and no basket.
- def test_logged_in_admin_no_basket... | Implement the Python class `CreatedBasketTestCase` described below.
Class description:
Implement the CreatedBasketTestCase class.
Method signatures and docstrings:
- def test_not_logged_in_no_basket(self): Test that the basket view will redirect whilst not logged in and no basket.
- def test_logged_in_admin_no_basket... | 37d2942efcbdaad072f7a06ac876a40e0f69f702 | <|skeleton|>
class CreatedBasketTestCase:
def test_not_logged_in_no_basket(self):
"""Test that the basket view will redirect whilst not logged in and no basket."""
<|body_0|>
def test_logged_in_admin_no_basket(self):
"""Test that the basket view will redirect whilst logged in as admin ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreatedBasketTestCase:
def test_not_logged_in_no_basket(self):
"""Test that the basket view will redirect whilst not logged in and no basket."""
url = '/createdbasket/'
response = self.client.get(url, HTTP_HOST='website.domain')
self.assertEqual(response.status_code, 302)
... | the_stack_v2_python_sparse | mooring/test_views.py | dbca-wa/moorings | train | 0 | |
13642efb5454f2b5e122664dbb346ac8bb65e96c | [
"self.path = join(working_dir, path)\npx = px_per_unit[unit]\nself.x, self.y, self.w, self.h, self.plotting_function = (x * px, y * px, w * px, h * px, plotting_function)\ninch = px_per_unit[unit] / px_per_unit['in']\nself.w_in, self.h_in = (w * inch, h * inch)\nself.keep_aspect_ratio = keep_aspect_ratio",
"if se... | <|body_start_0|>
self.path = join(working_dir, path)
px = px_per_unit[unit]
self.x, self.y, self.w, self.h, self.plotting_function = (x * px, y * px, w * px, h * px, plotting_function)
inch = px_per_unit[unit] / px_per_unit['in']
self.w_in, self.h_in = (w * inch, h * inch)
... | A panel in a figure. | Panel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Panel:
"""A panel in a figure."""
def __init__(self, path: str, x: float, y: float, w: float, h: float, plotting_function: Optional[Callable[[plt.Axes], None]]=None, keep_aspect_ratio: bool=True):
""":param path: relative path from working directory to the SVG image for this panel. :... | stack_v2_sparse_classes_36k_train_016264 | 7,890 | permissive | [
{
"docstring": ":param path: relative path from working directory to the SVG image for this panel. :param x: desired distance between the left of the panel and the left of the figure. :param y: desired distance between the top of the panel and the top of the figure. :param w: desired width of the panel. :param ... | 3 | stack_v2_sparse_classes_30k_train_001522 | Implement the Python class `Panel` described below.
Class description:
A panel in a figure.
Method signatures and docstrings:
- def __init__(self, path: str, x: float, y: float, w: float, h: float, plotting_function: Optional[Callable[[plt.Axes], None]]=None, keep_aspect_ratio: bool=True): :param path: relative path ... | Implement the Python class `Panel` described below.
Class description:
A panel in a figure.
Method signatures and docstrings:
- def __init__(self, path: str, x: float, y: float, w: float, h: float, plotting_function: Optional[Callable[[plt.Axes], None]]=None, keep_aspect_ratio: bool=True): :param path: relative path ... | 908f084b36c7387daf0cbfe75f16bab70cf96db9 | <|skeleton|>
class Panel:
"""A panel in a figure."""
def __init__(self, path: str, x: float, y: float, w: float, h: float, plotting_function: Optional[Callable[[plt.Axes], None]]=None, keep_aspect_ratio: bool=True):
""":param path: relative path from working directory to the SVG image for this panel. :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Panel:
"""A panel in a figure."""
def __init__(self, path: str, x: float, y: float, w: float, h: float, plotting_function: Optional[Callable[[plt.Axes], None]]=None, keep_aspect_ratio: bool=True):
""":param path: relative path from working directory to the SVG image for this panel. :param x: desi... | the_stack_v2_python_sparse | analysis/utils/svg_layout.py | DrugowitschLab/motion-structure-identification | train | 3 |
de7a2e8109892d2b3123de6943550dcc4bb0b7a8 | [
"self.model = model\nself.mean_img = mean_img\nself.shape = tuple(self.model.input.shape[1:3].as_list())",
"img = np.flip(img, axis=2)\nimg = img.astype(np.float)\nimg = cv2.resize(img, self.shape)\nimg = np.expand_dims(img, axis=0)\nfeatures = self.model.predict(img - self.mean_img)\nreturn features"
] | <|body_start_0|>
self.model = model
self.mean_img = mean_img
self.shape = tuple(self.model.input.shape[1:3].as_list())
<|end_body_0|>
<|body_start_1|>
img = np.flip(img, axis=2)
img = img.astype(np.float)
img = cv2.resize(img, self.shape)
img = np.expand_dims(img... | Functor for extraction of classification features from detections. | ClassificationFeatureExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassificationFeatureExtractor:
"""Functor for extraction of classification features from detections."""
def __init__(self, model, mean_img):
"""Constructor. Inputs: model -- Model used to extract appearance features. mean_img -- Mean image which is subtracted before applying the mod... | stack_v2_sparse_classes_36k_train_016265 | 1,561 | permissive | [
{
"docstring": "Constructor. Inputs: model -- Model used to extract appearance features. mean_img -- Mean image which is subtracted before applying the model.",
"name": "__init__",
"signature": "def __init__(self, model, mean_img)"
},
{
"docstring": "Extracts features from the given image. Input... | 2 | null | Implement the Python class `ClassificationFeatureExtractor` described below.
Class description:
Functor for extraction of classification features from detections.
Method signatures and docstrings:
- def __init__(self, model, mean_img): Constructor. Inputs: model -- Model used to extract appearance features. mean_img ... | Implement the Python class `ClassificationFeatureExtractor` described below.
Class description:
Functor for extraction of classification features from detections.
Method signatures and docstrings:
- def __init__(self, model, mean_img): Constructor. Inputs: model -- Model used to extract appearance features. mean_img ... | fae655f396380dbe74413812a41b734e267faffe | <|skeleton|>
class ClassificationFeatureExtractor:
"""Functor for extraction of classification features from detections."""
def __init__(self, model, mean_img):
"""Constructor. Inputs: model -- Model used to extract appearance features. mean_img -- Mean image which is subtracted before applying the mod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassificationFeatureExtractor:
"""Functor for extraction of classification features from detections."""
def __init__(self, model, mean_img):
"""Constructor. Inputs: model -- Model used to extract appearance features. mean_img -- Mean image which is subtracted before applying the model."""
... | the_stack_v2_python_sparse | train/siamese/extractors/classification_feature_extractor.py | openem-team/openem | train | 11 |
a1da4c99a85f5d6f7e1ed55d7740f3124455f0ed | [
"if source.hasText():\n snippet = source.text()\n QApplication.setOverrideCursor(Qt.WaitCursor)\n try:\n output, err = topy(snippet)\n pysnippet = output + '\\n'\n source = QMimeData()\n source.setText(pysnippet)\n if err:\n print(err)\n except Exception as ... | <|body_start_0|>
if source.hasText():
snippet = source.text()
QApplication.setOverrideCursor(Qt.WaitCursor)
try:
output, err = topy(snippet)
pysnippet = output + '\n'
source = QMimeData()
source.setText(pysnippet... | Custom editor for showing python code and converting mxs code to python when dropped or pasted. | CustomEditor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomEditor:
"""Custom editor for showing python code and converting mxs code to python when dropped or pasted."""
def insertFromMimeData(self, source):
"""Insert code from mime data"""
<|body_0|>
def keyPressEvent(self, event):
"""Simulate a tab"""
<|bo... | stack_v2_sparse_classes_36k_train_016266 | 6,722 | permissive | [
{
"docstring": "Insert code from mime data",
"name": "insertFromMimeData",
"signature": "def insertFromMimeData(self, source)"
},
{
"docstring": "Simulate a tab",
"name": "keyPressEvent",
"signature": "def keyPressEvent(self, event)"
}
] | 2 | null | Implement the Python class `CustomEditor` described below.
Class description:
Custom editor for showing python code and converting mxs code to python when dropped or pasted.
Method signatures and docstrings:
- def insertFromMimeData(self, source): Insert code from mime data
- def keyPressEvent(self, event): Simulate ... | Implement the Python class `CustomEditor` described below.
Class description:
Custom editor for showing python code and converting mxs code to python when dropped or pasted.
Method signatures and docstrings:
- def insertFromMimeData(self, source): Insert code from mime data
- def keyPressEvent(self, event): Simulate ... | 44445cd4faa410d46deef3ed8cf4a1fc20fd0ba6 | <|skeleton|>
class CustomEditor:
"""Custom editor for showing python code and converting mxs code to python when dropped or pasted."""
def insertFromMimeData(self, source):
"""Insert code from mime data"""
<|body_0|>
def keyPressEvent(self, event):
"""Simulate a tab"""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomEditor:
"""Custom editor for showing python code and converting mxs code to python when dropped or pasted."""
def insertFromMimeData(self, source):
"""Insert code from mime data"""
if source.hasText():
snippet = source.text()
QApplication.setOverrideCursor(Qt... | the_stack_v2_python_sparse | src/packages/mxstranslate/mxstranslate/translate.py | ADN-DevTech/3dsMax-Python-HowTos | train | 172 |
19041d04fabe848aeb10e6b81d6b880c2706d622 | [
"super().__init__(host, port, ssl_channel, ca_file)\nself._metadata = Metadata(api_key, secret_key, aud=aud['stt'])\nself._api_key = api_key\nself._secret_key = secret_key\nself._stub = SpeechToTextStub(self._channel)\nuploader_config = {} if uploader_config is None else uploader_config\nself._uploader = Uploader(s... | <|body_start_0|>
super().__init__(host, port, ssl_channel, ca_file)
self._metadata = Metadata(api_key, secret_key, aud=aud['stt'])
self._api_key = api_key
self._secret_key = secret_key
self._stub = SpeechToTextStub(self._channel)
uploader_config = {} if uploader_config is... | ClientSTT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientSTT:
def __init__(self, api_key: str, secret_key: str, host: str=client_config['host_stt'], port: int=client_config['port'], ssl_channel: bool=True, ca_file: str=None, uploader_config: dict=None):
"""Create client for speech recognition. :param api_key: client public api key :param... | stack_v2_sparse_classes_36k_train_016267 | 6,499 | permissive | [
{
"docstring": "Create client for speech recognition. :param api_key: client public api key :param secret_key: client secret api key :param host: Tinkoff Voicekit speech recognition host url :param port: Tinkoff Voicekit speech recognition port, default value: 443 :param ca_file: optional certificate file :uplo... | 5 | stack_v2_sparse_classes_30k_train_011252 | Implement the Python class `ClientSTT` described below.
Class description:
Implement the ClientSTT class.
Method signatures and docstrings:
- def __init__(self, api_key: str, secret_key: str, host: str=client_config['host_stt'], port: int=client_config['port'], ssl_channel: bool=True, ca_file: str=None, uploader_conf... | Implement the Python class `ClientSTT` described below.
Class description:
Implement the ClientSTT class.
Method signatures and docstrings:
- def __init__(self, api_key: str, secret_key: str, host: str=client_config['host_stt'], port: int=client_config['port'], ssl_channel: bool=True, ca_file: str=None, uploader_conf... | d9103b88cdfa8fc3afb9164bd9dd87a1b6f7f2f5 | <|skeleton|>
class ClientSTT:
def __init__(self, api_key: str, secret_key: str, host: str=client_config['host_stt'], port: int=client_config['port'], ssl_channel: bool=True, ca_file: str=None, uploader_config: dict=None):
"""Create client for speech recognition. :param api_key: client public api key :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClientSTT:
def __init__(self, api_key: str, secret_key: str, host: str=client_config['host_stt'], port: int=client_config['port'], ssl_channel: bool=True, ca_file: str=None, uploader_config: dict=None):
"""Create client for speech recognition. :param api_key: client public api key :param secret_key: c... | the_stack_v2_python_sparse | tinkoff_voicekit_client/STT/client_stt.py | Morracheg/voicekit_client_python | train | 0 | |
390e44d37e8846878eb9af457ffedefd32ca9661 | [
"res = 0\ndic = {}\ntmp = 0\nfor j in range(1, len(s)):\n i = dic.get(s[j], -1)\n dic[s[j]] = j\n tmp = tmp + 1 if tmp < j - i else j - i\n res = max(res, tmp)\nreturn res",
"dic = {}\nres = 0\ni = -1\nfor j in range(len(s)):\n if s[j] in dic:\n i = max(dic[s[j]], i)\n dic[s[j]] = j\n ... | <|body_start_0|>
res = 0
dic = {}
tmp = 0
for j in range(1, len(s)):
i = dic.get(s[j], -1)
dic[s[j]] = j
tmp = tmp + 1 if tmp < j - i else j - i
res = max(res, tmp)
return res
<|end_body_0|>
<|body_start_1|>
dic = {}
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def LengthOfLongestSubstring(self, s: str) -> int:
"""计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:"""
<|body_0|>
def LengthOfLongestSubstringByDoublePointer(self, s: str) -> int:
"""计算无重复字符串的最大长度 方法一:双指针+哈希表 :param s: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_016268 | 3,381 | no_license | [
{
"docstring": "计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:",
"name": "LengthOfLongestSubstring",
"signature": "def LengthOfLongestSubstring(self, s: str) -> int"
},
{
"docstring": "计算无重复字符串的最大长度 方法一:双指针+哈希表 :param s: :return:",
"name": "LengthOfLongestSubstringByDoublePointer",
"signa... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LengthOfLongestSubstring(self, s: str) -> int: 计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:
- def LengthOfLongestSubstringByDoublePointer(self, s: str) -> int: 计算无重复字符串的最大长度... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def LengthOfLongestSubstring(self, s: str) -> int: 计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:
- def LengthOfLongestSubstringByDoublePointer(self, s: str) -> int: 计算无重复字符串的最大长度... | 32941ee052d0985a9569441d314378700ff4d225 | <|skeleton|>
class Solution:
def LengthOfLongestSubstring(self, s: str) -> int:
"""计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:"""
<|body_0|>
def LengthOfLongestSubstringByDoublePointer(self, s: str) -> int:
"""计算无重复字符串的最大长度 方法一:双指针+哈希表 :param s: :return:"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def LengthOfLongestSubstring(self, s: str) -> int:
"""计算无重复字符串的最大长度 方法一:动态规划+哈希表 :param s: :return:"""
res = 0
dic = {}
tmp = 0
for j in range(1, len(s)):
i = dic.get(s[j], -1)
dic[s[j]] = j
tmp = tmp + 1 if tmp < j - i else... | the_stack_v2_python_sparse | cecilia-python/剑指offer/chapter-7/LengthOfLongestSubstring.py | Cecilia520/algorithmic-learning-leetcode | train | 7 | |
c5fb848c63bea4cfe0e1da7984780e4f83828bb8 | [
"self.primary_language = primary_language\nself.secondary_language = secondary_language\nself.xml_signature = xml_signature\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nprimary_language = dictionary.get('PrimaryLanguage')\nsecondary_language = dictionary.get('Sec... | <|body_start_0|>
self.primary_language = primary_language
self.secondary_language = secondary_language
self.xml_signature = xml_signature
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
pri... | Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_signature (string): Xml package signa... | TemplateWithIdPreview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op... | stack_v2_sparse_classes_36k_train_016269 | 2,616 | permissive | [
{
"docstring": "Constructor for the TemplateWithIdPreview class",
"name": "__init__",
"signature": "def __init__(self, primary_language=None, secondary_language=None, xml_signature=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dicti... | 2 | stack_v2_sparse_classes_30k_train_001354 | Implement the Python class `TemplateWithIdPreview` described below.
Class description:
Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second... | Implement the Python class `TemplateWithIdPreview` described below.
Class description:
Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Second... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (op... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateWithIdPreview:
"""Implementation of the 'TemplateWithIdPreview' model. TODO: type model description here. Attributes: primary_language (PrimaryLanguage): Primary language to use in the preview (required) secondary_language (SecondaryLanguage): Secondary language to use in the prewview (optional) xml_s... | the_stack_v2_python_sparse | idfy_rest_client/models/template_with_id_preview.py | dealflowteam/Idfy | train | 0 |
8cf24450fcb25e40dcbb6a833c45cccde901a6ee | [
"if not s or k == 0:\n return 0\nmaxheap = []\ninwindow = {}\nj, maxlen = (0, 1)\nfor i in xrange(len(s)):\n ch = s[i]\n if len(inwindow) == k and ch not in inwindow:\n idx, first = heapq.heappop(maxheap)\n del inwindow[first]\n j = idx + 1\n if ch in inwindow:\n for idx in x... | <|body_start_0|>
if not s or k == 0:
return 0
maxheap = []
inwindow = {}
j, maxlen = (0, 1)
for i in xrange(len(s)):
ch = s[i]
if len(inwindow) == k and ch not in inwindow:
idx, first = heapq.heappop(maxheap)
del... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def followup(self, s, k):
"""the question follow up is data char, only can read one char"""
<|body_0|>
def lengthOfLongestSubstringKDistinct(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_016270 | 1,759 | permissive | [
{
"docstring": "the question follow up is data char, only can read one char",
"name": "followup",
"signature": "def followup(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "lengthOfLongestSubstringKDistinct",
"signature": "def lengthOfLongestSubstringKDis... | 2 | stack_v2_sparse_classes_30k_train_007702 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def followup(self, s, k): the question follow up is data char, only can read one char
- def lengthOfLongestSubstringKDistinct(self, s, k): :type s: str :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def followup(self, s, k): the question follow up is data char, only can read one char
- def lengthOfLongestSubstringKDistinct(self, s, k): :type s: str :type k: int :rtype: int
... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def followup(self, s, k):
"""the question follow up is data char, only can read one char"""
<|body_0|>
def lengthOfLongestSubstringKDistinct(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def followup(self, s, k):
"""the question follow up is data char, only can read one char"""
if not s or k == 0:
return 0
maxheap = []
inwindow = {}
j, maxlen = (0, 1)
for i in xrange(len(s)):
ch = s[i]
if len(inwindo... | the_stack_v2_python_sparse | 340-Longest-Substring-with-At-Most-K-Distinct-Characters/solution.py | Tanych/CodeTracking | train | 0 | |
83a1040ac26506fdd22f77cee492899e78c0401c | [
"ObjetGraph.__init__(self, couche, couleur)\nTaxi.taille = 20\nself.texte = MiniNombre(11)\nTaxi.arrete = Etat(11, (1.0, 1.0, 1.0), 'arrete')\nTaxi.chercheClient = Etat(11, (0.4, 0.4, 1.0), 'chercheClient')\nTaxi.conduitClient = Etat(11, (1.0, 0.0, 0.0), 'conduitClient')\nTaxi.retourStation = Etat(11, (1.0, 0.67, 0... | <|body_start_0|>
ObjetGraph.__init__(self, couche, couleur)
Taxi.taille = 20
self.texte = MiniNombre(11)
Taxi.arrete = Etat(11, (1.0, 1.0, 1.0), 'arrete')
Taxi.chercheClient = Etat(11, (0.4, 0.4, 1.0), 'chercheClient')
Taxi.conduitClient = Etat(11, (1.0, 0.0, 0.0), 'condu... | Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri | Taxi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Taxi:
"""Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri"""
def __init__(self, couche=0, couleur=(1.0, 1.0, 0.0)):
"""Initialisation d'un taxi. Initialise differentes donnees membr... | stack_v2_sparse_classes_36k_train_016271 | 3,381 | no_license | [
{
"docstring": "Initialisation d'un taxi. Initialise differentes donnees membres. @param int couche : la couche sur laquelle se trouve l'objet @param (float, float, float) couleur : la couleur du taxi @return Rien : Ne retourne rien @author Gregory Burri",
"name": "__init__",
"signature": "def __init__(... | 2 | stack_v2_sparse_classes_30k_train_016255 | Implement the Python class `Taxi` described below.
Class description:
Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri
Method signatures and docstrings:
- def __init__(self, couche=0, couleur=(1.0, 1.0, 0.0)): Initi... | Implement the Python class `Taxi` described below.
Class description:
Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri
Method signatures and docstrings:
- def __init__(self, couche=0, couleur=(1.0, 1.0, 0.0)): Initi... | 2a215d8f3fa49e1db1de0e7759bf0cd1399b43b7 | <|skeleton|>
class Taxi:
"""Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri"""
def __init__(self, couche=0, couleur=(1.0, 1.0, 0.0)):
"""Initialisation d'un taxi. Initialise differentes donnees membr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Taxi:
"""Classe dessinant un taxi. Classe derivant de ObjetGraph et permettant de dessiner des taxis en OpenGL. :version: $Revision 1.0 $ :author: Gregory Burri"""
def __init__(self, couche=0, couleur=(1.0, 1.0, 0.0)):
"""Initialisation d'un taxi. Initialise differentes donnees membres. @param in... | the_stack_v2_python_sparse | dev/gui/TaxiGL.py | jburdy/SimTaxi | train | 2 |
26346493498beae5fd79753e004af8e8ab10c0d6 | [
"try:\n release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)\nexcept Release.DoesNotExist:\n raise ResourceDoesNotExist\nreturn self.get_releasefiles(request, release, project.organization_id)",
"try:\n release = Release.objects.get(organization_id=pro... | <|body_start_0|>
try:
release = Release.objects.get(organization_id=project.organization_id, projects=project, version=version)
except Release.DoesNotExist:
raise ResourceDoesNotExist
return self.get_releasefiles(request, release, project.organization_id)
<|end_body_0|>
... | ProjectReleaseFilesEndpoint | [
"Apache-2.0",
"BUSL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectReleaseFilesEndpoint:
def get(self, request: Request, project, version) -> Response:
"""List a Project Release's Files `````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release belongs to... | stack_v2_sparse_classes_36k_train_016272 | 10,556 | permissive | [
{
"docstring": "List a Project Release's Files `````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release belongs to. :pparam string project_slug: the slug of the project to list the release files of. :pparam string ver... | 2 | null | Implement the Python class `ProjectReleaseFilesEndpoint` described below.
Class description:
Implement the ProjectReleaseFilesEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version) -> Response: List a Project Release's Files `````````````````````````````` Retrieve a list... | Implement the Python class `ProjectReleaseFilesEndpoint` described below.
Class description:
Implement the ProjectReleaseFilesEndpoint class.
Method signatures and docstrings:
- def get(self, request: Request, project, version) -> Response: List a Project Release's Files `````````````````````````````` Retrieve a list... | d9dd4f382f96b5c4576b64cbf015db651556c18b | <|skeleton|>
class ProjectReleaseFilesEndpoint:
def get(self, request: Request, project, version) -> Response:
"""List a Project Release's Files `````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release belongs to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectReleaseFilesEndpoint:
def get(self, request: Request, project, version) -> Response:
"""List a Project Release's Files `````````````````````````````` Retrieve a list of files for a given release. :pparam string organization_slug: the slug of the organization the release belongs to. :pparam stri... | the_stack_v2_python_sparse | src/sentry/api/endpoints/project_release_files.py | nagyist/sentry | train | 0 | |
cb8475bc7f0fa167be67ad9cfbcd2b1c71a8c96d | [
"def computation(a, b):\n return a + b\nself.assertEqual(self.evaluate(xla.compile(computation, [1, 2])[0]), 3)",
"@def_function.function\ndef func_wrapper(a):\n\n def compute(a):\n return a + 1\n return xla.compile(compute, [a])\nself.assertEqual(self.evaluate(func_wrapper(1))[0], 2)",
"a = var... | <|body_start_0|>
def computation(a, b):
return a + b
self.assertEqual(self.evaluate(xla.compile(computation, [1, 2])[0]), 3)
<|end_body_0|>
<|body_start_1|>
@def_function.function
def func_wrapper(a):
def compute(a):
return a + 1
retu... | XlaCompileTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XlaCompileTest:
def test_xla_compile_eager(self):
"""Tests that xla.compile raises proper exception when used eagerly."""
<|body_0|>
def test_xla_compile_in_function(self):
"""Tests that xla.compile works in tf.function."""
<|body_1|>
def test_xla_compil... | stack_v2_sparse_classes_36k_train_016273 | 12,981 | permissive | [
{
"docstring": "Tests that xla.compile raises proper exception when used eagerly.",
"name": "test_xla_compile_eager",
"signature": "def test_xla_compile_eager(self)"
},
{
"docstring": "Tests that xla.compile works in tf.function.",
"name": "test_xla_compile_in_function",
"signature": "de... | 3 | null | Implement the Python class `XlaCompileTest` described below.
Class description:
Implement the XlaCompileTest class.
Method signatures and docstrings:
- def test_xla_compile_eager(self): Tests that xla.compile raises proper exception when used eagerly.
- def test_xla_compile_in_function(self): Tests that xla.compile w... | Implement the Python class `XlaCompileTest` described below.
Class description:
Implement the XlaCompileTest class.
Method signatures and docstrings:
- def test_xla_compile_eager(self): Tests that xla.compile raises proper exception when used eagerly.
- def test_xla_compile_in_function(self): Tests that xla.compile w... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class XlaCompileTest:
def test_xla_compile_eager(self):
"""Tests that xla.compile raises proper exception when used eagerly."""
<|body_0|>
def test_xla_compile_in_function(self):
"""Tests that xla.compile works in tf.function."""
<|body_1|>
def test_xla_compil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XlaCompileTest:
def test_xla_compile_eager(self):
"""Tests that xla.compile raises proper exception when used eagerly."""
def computation(a, b):
return a + b
self.assertEqual(self.evaluate(xla.compile(computation, [1, 2])[0]), 3)
def test_xla_compile_in_function(self):... | the_stack_v2_python_sparse | tensorflow/python/compiler/xla/xla_test.py | tensorflow/tensorflow | train | 208,740 | |
8d0fb60f57f96a83650fc65d414876140adbcabf | [
"while True:\n i = 7 * (rand7() - 1) + rand7\n if i <= 40:\n return 1 + (i - 1) % 10",
"while True:\n a = rand7()\n b = rand7()\n i = 7 * (a - 1) + b\n if i <= 40:\n return 1 + (i - 1) % 10\n a = i - 40\n b = rand7()\n i = 7 * (a - 1) + b\n if i <= 60:\n return 1... | <|body_start_0|>
while True:
i = 7 * (rand7() - 1) + rand7
if i <= 40:
return 1 + (i - 1) % 10
<|end_body_0|>
<|body_start_1|>
while True:
a = rand7()
b = rand7()
i = 7 * (a - 1) + b
if i <= 40:
retu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rand10_1(self) -> int:
"""Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 19 20 21 4 22 23 24 25 26 27 28 5 29 30 31 32 33 34 35 6 36 37 38 39 40 41 42 7 43 44 45 46 47 48... | stack_v2_sparse_classes_36k_train_016274 | 2,283 | no_license | [
{
"docstring": "Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 19 20 21 4 22 23 24 25 26 27 28 5 29 30 31 32 33 34 35 6 36 37 38 39 40 41 42 7 43 44 45 46 47 48 49 So 7 * (r - 1) + c will give us 1 to 49 when... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10_1(self) -> int: Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10_1(self) -> int: Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 ... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def rand10_1(self) -> int:
"""Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 19 20 21 4 22 23 24 25 26 27 28 5 29 30 31 32 33 34 35 6 36 37 38 39 40 41 42 7 43 44 45 46 47 48... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rand10_1(self) -> int:
"""Use rejection sampling to generate rand49 from rand7 with the matrix showed as below: 1 2 3 4 5 6 7 1 1 2 3 4 5 6 7 2 8 9 10 11 12 13 14 3 15 16 17 18 19 20 21 4 22 23 24 25 26 27 28 5 29 30 31 32 33 34 35 6 36 37 38 39 40 41 42 7 43 44 45 46 47 48 49 So 7 * (r ... | the_stack_v2_python_sparse | 2020/implement_rand10_using_rand7.py | eronekogin/leetcode | train | 0 | |
2583d285110e1a6627b591a3b3e788d35173cd3a | [
"num_theta = 6\nnum_phi = 4\nexpected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))\ntheta = jnp.linspace(0, math.pi, num_theta)\nphi = jnp.linspace(0, 2.0 * math.pi, num_phi)\nsph_harm = spherical_harmonics.SphericalHarmonics(l_max=0, theta=theta, phi=phi)\nactual = jnp.real(sph_harm.harmo... | <|body_start_0|>
num_theta = 6
num_phi = 4
expected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))
theta = jnp.linspace(0, math.pi, num_theta)
phi = jnp.linspace(0, 2.0 * math.pi, num_phi)
sph_harm = spherical_harmonics.SphericalHarmonics(l_max=0, ... | SphericalHarmonicsTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
<|body_0|>
def testOrderOneDegreeZero(self):
"""Tests the spherical harmonics of order one and degree zero."""
<|body_1|>
def te... | stack_v2_sparse_classes_36k_train_016275 | 4,604 | permissive | [
{
"docstring": "Tests the spherical harmonics of order zero and degree zero.",
"name": "testOrderZeroDegreeZero",
"signature": "def testOrderZeroDegreeZero(self)"
},
{
"docstring": "Tests the spherical harmonics of order one and degree zero.",
"name": "testOrderOneDegreeZero",
"signature... | 5 | stack_v2_sparse_classes_30k_val_001080 | Implement the Python class `SphericalHarmonicsTest` described below.
Class description:
Implement the SphericalHarmonicsTest class.
Method signatures and docstrings:
- def testOrderZeroDegreeZero(self): Tests the spherical harmonics of order zero and degree zero.
- def testOrderOneDegreeZero(self): Tests the spherica... | Implement the Python class `SphericalHarmonicsTest` described below.
Class description:
Implement the SphericalHarmonicsTest class.
Method signatures and docstrings:
- def testOrderZeroDegreeZero(self): Tests the spherical harmonics of order zero and degree zero.
- def testOrderOneDegreeZero(self): Tests the spherica... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
<|body_0|>
def testOrderOneDegreeZero(self):
"""Tests the spherical harmonics of order one and degree zero."""
<|body_1|>
def te... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalHarmonicsTest:
def testOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
num_theta = 6
num_phi = 4
expected = 1.0 / jnp.sqrt(4.0 * math.pi) * jnp.ones((1, 1, num_theta, num_phi))
theta = jnp.linspace(0, math.pi, num_t... | the_stack_v2_python_sparse | simulation_research/signal_processing/spherical/spherical_harmonics_test.py | Jimmy-INL/google-research | train | 1 | |
e583e89287990d813c3666bfaff0353c03bcd839 | [
"self.boys_no = no_boys\nself.girls_no = no_girls\nself.gift_no = no_gifts",
"try:\n with open('./data/boys.csv', 'w') as csvfile:\n fieldnames = ['name', 'attractiveness', 'min_attr', 'intelligence', 'budget', 'is_committed', 'b_type']\n bwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n... | <|body_start_0|>
self.boys_no = no_boys
self.girls_no = no_girls
self.gift_no = no_gifts
<|end_body_0|>
<|body_start_1|>
try:
with open('./data/boys.csv', 'w') as csvfile:
fieldnames = ['name', 'attractiveness', 'min_attr', 'intelligence', 'budget', 'is_commi... | Creates random boys and girls | randomWriter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class randomWriter:
"""Creates random boys and girls"""
def __init__(self, no_boys, no_girls, no_gifts):
"""initializes a randomwriter sets number of boys, girls and gifts"""
<|body_0|>
def makeBoys(self):
"""this function creates random boys and places them in boys.cs... | stack_v2_sparse_classes_36k_train_016276 | 5,409 | no_license | [
{
"docstring": "initializes a randomwriter sets number of boys, girls and gifts",
"name": "__init__",
"signature": "def __init__(self, no_boys, no_girls, no_gifts)"
},
{
"docstring": "this function creates random boys and places them in boys.csv",
"name": "makeBoys",
"signature": "def ma... | 4 | stack_v2_sparse_classes_30k_train_003216 | Implement the Python class `randomWriter` described below.
Class description:
Creates random boys and girls
Method signatures and docstrings:
- def __init__(self, no_boys, no_girls, no_gifts): initializes a randomwriter sets number of boys, girls and gifts
- def makeBoys(self): this function creates random boys and p... | Implement the Python class `randomWriter` described below.
Class description:
Creates random boys and girls
Method signatures and docstrings:
- def __init__(self, no_boys, no_girls, no_gifts): initializes a randomwriter sets number of boys, girls and gifts
- def makeBoys(self): this function creates random boys and p... | c6e96a7ca5251837281d8d2b8c2123c787ad00de | <|skeleton|>
class randomWriter:
"""Creates random boys and girls"""
def __init__(self, no_boys, no_girls, no_gifts):
"""initializes a randomwriter sets number of boys, girls and gifts"""
<|body_0|>
def makeBoys(self):
"""this function creates random boys and places them in boys.cs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class randomWriter:
"""Creates random boys and girls"""
def __init__(self, no_boys, no_girls, no_gifts):
"""initializes a randomwriter sets number of boys, girls and gifts"""
self.boys_no = no_boys
self.girls_no = no_girls
self.gift_no = no_gifts
def makeBoys(self):
... | the_stack_v2_python_sparse | part3/question11/PermissionError/helper/creater.py | PPL-IIITA/ppl-assignment-dewana-dewan | train | 0 |
1b48c25051464bb76f02165f9264e94b63006a40 | [
"self.assertEqual(max_list_iter([1]), 1)\nself.assertEqual(max_list_iter([1, 2, 3]), 3)\nself.assertEqual(max_list_iter([-1, -2, -3]), -1)\nself.assertEqual(max_list_iter([1, 1, 1]), 1)\nself.assertEqual(max_list_iter([2, 1, 3]), 3)\nself.assertEqual(max_list_iter([]), None)\nself.assertEqual(max_list_iter([1, 3, 3... | <|body_start_0|>
self.assertEqual(max_list_iter([1]), 1)
self.assertEqual(max_list_iter([1, 2, 3]), 3)
self.assertEqual(max_list_iter([-1, -2, -3]), -1)
self.assertEqual(max_list_iter([1, 1, 1]), 1)
self.assertEqual(max_list_iter([2, 1, 3]), 3)
self.assertEqual(max_list_i... | TestLab1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
<|body_0|>
def test_reverse_rec(self):
"""tests reverse_rec, a methon for reculsivly reversing a list"""
<|body_1|>
def test_bin_search(self):
"""A test of binary sear... | stack_v2_sparse_classes_36k_train_016277 | 1,782 | no_license | [
{
"docstring": "Tests max list through iteration",
"name": "test_max_list_iter",
"signature": "def test_max_list_iter(self)"
},
{
"docstring": "tests reverse_rec, a methon for reculsivly reversing a list",
"name": "test_reverse_rec",
"signature": "def test_reverse_rec(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_016954 | Implement the Python class `TestLab1` described below.
Class description:
Implement the TestLab1 class.
Method signatures and docstrings:
- def test_max_list_iter(self): Tests max list through iteration
- def test_reverse_rec(self): tests reverse_rec, a methon for reculsivly reversing a list
- def test_bin_search(sel... | Implement the Python class `TestLab1` described below.
Class description:
Implement the TestLab1 class.
Method signatures and docstrings:
- def test_max_list_iter(self): Tests max list through iteration
- def test_reverse_rec(self): tests reverse_rec, a methon for reculsivly reversing a list
- def test_bin_search(sel... | 8f3bb6433ea8555f0ba73cb0db2fabd98c95d8ee | <|skeleton|>
class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
<|body_0|>
def test_reverse_rec(self):
"""tests reverse_rec, a methon for reculsivly reversing a list"""
<|body_1|>
def test_bin_search(self):
"""A test of binary sear... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestLab1:
def test_max_list_iter(self):
"""Tests max list through iteration"""
self.assertEqual(max_list_iter([1]), 1)
self.assertEqual(max_list_iter([1, 2, 3]), 3)
self.assertEqual(max_list_iter([-1, -2, -3]), -1)
self.assertEqual(max_list_iter([1, 1, 1]), 1)
s... | the_stack_v2_python_sparse | CSC202/lab1-baileywickham/lab1_test_cases.py | baileywickham/college | train | 1 | |
f2300951f9be0ea4c4854ee42463fa3b20d68ebc | [
"self.pump = Pump('127.0.0.1', 1000)\nself.sensor = Sensor('127.0.0.2', 2000)\nself.decider = Decider(300, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=275)\nself.pump.get_state = MagicMock(return_value='PUMP_OFF')\nself.controller.tick ... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(300, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=275)
... | Module tests for the water-regulation module | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
<|body_0|>
def test_tick(self):
"""This method performs an integration test for tick"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_016278 | 1,011 | no_license | [
{
"docstring": "This method does a setup for integration testing raterregulation",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This method performs an integration test for tick",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | null | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): This method does a setup for integration testing raterregulation
- def test_tick(self): This method performs an integration test for tick | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): This method does a setup for integration testing raterregulation
- def test_tick(self): This method performs an integration test for tick
<|sk... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
<|body_0|>
def test_tick(self):
"""This method performs an integration test for tick"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""This method does a setup for integration testing raterregulation"""
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(300, 0.05)
sel... | the_stack_v2_python_sparse | students/AurelP/lesson6/water-regulation/waterregulation/integrationtest.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
8928a33628fa4a8872e1c63cd2c9740c519eee47 | [
"with mock.patch('version.FetchValuesFromFile') as fetch_values_from_file_mock:\n fetch_values_from_file_mock.side_effect = lambda values, file: values.update(dict(_VersionTest._EXAMPLE_VERSION, **new_version_values))\n new_args = get_new_args(_VersionTest._EXAMPLE_ARGS)\n return version.BuildOutput(new_ar... | <|body_start_0|>
with mock.patch('version.FetchValuesFromFile') as fetch_values_from_file_mock:
fetch_values_from_file_mock.side_effect = lambda values, file: values.update(dict(_VersionTest._EXAMPLE_VERSION, **new_version_values))
new_args = get_new_args(_VersionTest._EXAMPLE_ARGS)
... | Unittests for the version module. | _VersionTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _E... | stack_v2_sparse_classes_36k_train_016279 | 6,236 | permissive | [
{
"docstring": "Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _EXAMPLE_VERSION get_new_args -- lambda for updating _EXAMPLE_ANDROID_ARGS",
"name": "_RunBuildOutput",
"signature": "def _RunBuildOutput(new_versi... | 6 | stack_v2_sparse_classes_30k_train_000928 | Implement the Python class `_VersionTest` described below.
Class description:
Unittests for the version module.
Method signatures and docstrings:
- def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args): Parameterized helper method for running the main testable method in version.py. Keywor... | Implement the Python class `_VersionTest` described below.
Class description:
Unittests for the version module.
Method signatures and docstrings:
- def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args): Parameterized helper method for running the main testable method in version.py. Keywor... | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | <|skeleton|>
class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _E... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _VersionTest:
"""Unittests for the version module."""
def _RunBuildOutput(new_version_values={}, get_new_args=lambda old_args: old_args):
"""Parameterized helper method for running the main testable method in version.py. Keyword arguments: new_version_values -- dict used to update _EXAMPLE_VERSIO... | the_stack_v2_python_sparse | build/util/version_test.py | chromium/chromium | train | 17,408 |
956f247874901fea184dbd0b0f8980c80483f7a3 | [
"pygame.init()\nself.screen = pygame.display.set_mode((800, 600))\npygame.display.set_caption('Keys')\nself.bg_color = (66, 158, 245)",
"while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n print(e... | <|body_start_0|>
pygame.init()
self.screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Keys')
self.bg_color = (66, 158, 245)
<|end_body_0|>
<|body_start_1|>
while True:
for event in pygame.event.get():
if event.type == pygame.QUI... | overrall class to manage assets and behavior | Keys | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Keys:
"""overrall class to manage assets and behavior"""
def __init__(self):
"""Initialize the game and create resources"""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pygam... | stack_v2_sparse_classes_36k_train_016280 | 1,392 | no_license | [
{
"docstring": "Initialize the game and create resources",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Start the main loop for the game.",
"name": "run_game",
"signature": "def run_game(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003159 | Implement the Python class `Keys` described below.
Class description:
overrall class to manage assets and behavior
Method signatures and docstrings:
- def __init__(self): Initialize the game and create resources
- def run_game(self): Start the main loop for the game. | Implement the Python class `Keys` described below.
Class description:
overrall class to manage assets and behavior
Method signatures and docstrings:
- def __init__(self): Initialize the game and create resources
- def run_game(self): Start the main loop for the game.
<|skeleton|>
class Keys:
"""overrall class to... | c50b58077762f4042635b80643e598240ff50205 | <|skeleton|>
class Keys:
"""overrall class to manage assets and behavior"""
def __init__(self):
"""Initialize the game and create resources"""
<|body_0|>
def run_game(self):
"""Start the main loop for the game."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Keys:
"""overrall class to manage assets and behavior"""
def __init__(self):
"""Initialize the game and create resources"""
pygame.init()
self.screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Keys')
self.bg_color = (66, 158, 245)
def ru... | the_stack_v2_python_sparse | Chapter12/Keys/keys.py | ingenium21/PythonCrashCourse | train | 0 |
b8a35ff83563cd4a2bdedbbce46ace657eaa0377 | [
"super().__init__()\nself.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]\nself.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_size': 16}\nself.max_reward_per_episode = 1.0",
"self.state = 0\nself.done = False\nreturn self.state",
"assert ... | <|body_start_0|>
super().__init__()
self.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]
self.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_size': 16}
self.max_reward_per_episode = 1.0
<|end_body_0|>
<|body_start_... | FrozenLakeEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
<|body_0|>
def reset(self):
"""Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the en... | stack_v2_sparse_classes_36k_train_016281 | 3,043 | no_license | [
{
"docstring": "Initialise the FrozenLake environment.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the environment ... | 3 | stack_v2_sparse_classes_30k_train_021576 | Implement the Python class `FrozenLakeEnv` described below.
Class description:
Implement the FrozenLakeEnv class.
Method signatures and docstrings:
- def __init__(self): Initialise the FrozenLake environment.
- def reset(self): Resets the enviroment. Should be called after every episode of a learning procedure. Retur... | Implement the Python class `FrozenLakeEnv` described below.
Class description:
Implement the FrozenLakeEnv class.
Method signatures and docstrings:
- def __init__(self): Initialise the FrozenLake environment.
- def reset(self): Resets the enviroment. Should be called after every episode of a learning procedure. Retur... | ea6db735b432471bb0e0a1a9db063403ecc08333 | <|skeleton|>
class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
<|body_0|>
def reset(self):
"""Resets the enviroment. Should be called after every episode of a learning procedure. Returns: - self.state: np.array, represents the current state of the en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FrozenLakeEnv:
def __init__(self):
"""Initialise the FrozenLake environment."""
super().__init__()
self.grid = [['S', 'F', 'F', 'F'], ['F', 'H', 'F', 'H'], ['F', 'F', 'F', 'H'], ['H', 'F', 'F', 'G']]
self.env_info = {'policy_type': 'grid', 'action_space': [0, 1, 2, 3], 'state_s... | the_stack_v2_python_sparse | src/reinforcement_learning/environments/frozenlake.py | Timsey/simple-machine-learning | train | 0 | |
52ac05de1d1f508b94dee705a4401edafc44538a | [
"def parse(st):\n stack = []\n for x in st:\n if x == '#' and stack:\n stack.pop()\n elif x.isalpha():\n stack.append(x)\n return stack\nreturn parse(S) == parse(T)",
"i, j, del1, del2 = (len(S) - 1, len(T) - 1, 0, 0)\nwhile i >= 0 or j >= 0:\n while i >= 0:\n ... | <|body_start_0|>
def parse(st):
stack = []
for x in st:
if x == '#' and stack:
stack.pop()
elif x.isalpha():
stack.append(x)
return stack
return parse(S) == parse(T)
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def backspaceCompare1(self, S: str, T: str) -> bool:
"""常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)"""
<|body_0|>
def backspaceCompare2(self, S: str, T: str) -> bool:
"""Follow up: 要求空间复杂度O(1),双指针逆序遍历"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def ... | stack_v2_sparse_classes_36k_train_016282 | 1,998 | no_license | [
{
"docstring": "常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)",
"name": "backspaceCompare1",
"signature": "def backspaceCompare1(self, S: str, T: str) -> bool"
},
{
"docstring": "Follow up: 要求空间复杂度O(1),双指针逆序遍历",
"name": "backspaceCompare2",
"signature": "def backspaceCompare2(self, S: str, T: str) -> bo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backspaceCompare1(self, S: str, T: str) -> bool: 常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)
- def backspaceCompare2(self, S: str, T: str) -> bool: Follow up: 要求空间复杂度O(1),双指针逆序遍历 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def backspaceCompare1(self, S: str, T: str) -> bool: 常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)
- def backspaceCompare2(self, S: str, T: str) -> bool: Follow up: 要求空间复杂度O(1),双指针逆序遍历
<|skelet... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
def backspaceCompare1(self, S: str, T: str) -> bool:
"""常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)"""
<|body_0|>
def backspaceCompare2(self, S: str, T: str) -> bool:
"""Follow up: 要求空间复杂度O(1),双指针逆序遍历"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def backspaceCompare1(self, S: str, T: str) -> bool:
"""常规解法,利用栈,时间空间复杂度都是O(S+T)即O(n)"""
def parse(st):
stack = []
for x in st:
if x == '#' and stack:
stack.pop()
elif x.isalpha():
stack.a... | the_stack_v2_python_sparse | 844_backspace-string-compare.py | helloocc/algorithm | train | 1 | |
5844acb242d79af6ebf50afb39fed05351a23d46 | [
"if obj is None:\n raise Exception('Object cannot be null')\nif name is None:\n raise Exception('Property name cannot be null')\nname = name.lower()\nif isinstance(obj, dict):\n for key in obj.keys():\n if name == str(key).lower():\n obj[key] = value\n return\n obj[name] = v... | <|body_start_0|>
if obj is None:
raise Exception('Object cannot be null')
if name is None:
raise Exception('Property name cannot be null')
name = name.lower()
if isinstance(obj, dict):
for key in obj.keys():
if name == str(key).lower():... | Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is also able to handle maps and arrays. For maps properties are key-pairs identified... | ObjectWriter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectWriter:
"""Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is also able to handle maps and arrays. For ... | stack_v2_sparse_classes_36k_train_016283 | 3,803 | permissive | [
{
"docstring": "ets args of object property specified by its name. The object can be a user defined object, map or array. The property name correspondently must be object property, map key or array index. If the property does not exist or introspection fails this method doesn't do anything and doesn't any throw... | 2 | null | Implement the Python class `ObjectWriter` described below.
Class description:
Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is al... | Implement the Python class `ObjectWriter` described below.
Class description:
Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is al... | 17f8a231fb75684032ec57b24025c9a3ca3dcdd6 | <|skeleton|>
class ObjectWriter:
"""Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is also able to handle maps and arrays. For ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectWriter:
"""Helper class to perform property introspection and dynamic writing. In contrast to :class:`PropertyReflector <pip_services3_commons.reflect.PropertyReflector.PropertyReflector>` which only introspects regular objects, this ObjectWriter is also able to handle maps and arrays. For maps properti... | the_stack_v2_python_sparse | pip_services3_commons/reflect/ObjectWriter.py | pip-services3-python/pip-services3-commons-python | train | 0 |
252b5415aeb413e64e87b927c93f63474bf5ce65 | [
"set_seed(int(time()))\ntokenizer = create_tokenizer(tokenizer)\nmodel = create_model(model)\nself._text_generation_pipiline = _create_pipiline(tokenizer, model, device, framework)",
"seqs = [seqs] if isinstance(seqs, str) else seqs\nmax_length = max(map(len, seqs)) * 2\nreturn self._text_generation_pipiline(seqs... | <|body_start_0|>
set_seed(int(time()))
tokenizer = create_tokenizer(tokenizer)
model = create_model(model)
self._text_generation_pipiline = _create_pipiline(tokenizer, model, device, framework)
<|end_body_0|>
<|body_start_1|>
seqs = [seqs] if isinstance(seqs, str) else seqs
... | Text generator pipiline. | TextGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextGenerator:
"""Text generator pipiline."""
def __init__(self, tokenizer, model, device=-1, framework='pt'):
"""Init class object."""
<|body_0|>
def __call__(self, seqs):
"""Call class object."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_36k_train_016284 | 1,880 | no_license | [
{
"docstring": "Init class object.",
"name": "__init__",
"signature": "def __init__(self, tokenizer, model, device=-1, framework='pt')"
},
{
"docstring": "Call class object.",
"name": "__call__",
"signature": "def __call__(self, seqs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016395 | Implement the Python class `TextGenerator` described below.
Class description:
Text generator pipiline.
Method signatures and docstrings:
- def __init__(self, tokenizer, model, device=-1, framework='pt'): Init class object.
- def __call__(self, seqs): Call class object. | Implement the Python class `TextGenerator` described below.
Class description:
Text generator pipiline.
Method signatures and docstrings:
- def __init__(self, tokenizer, model, device=-1, framework='pt'): Init class object.
- def __call__(self, seqs): Call class object.
<|skeleton|>
class TextGenerator:
"""Text ... | b6e52ed56928ea3e67327c46eb021dd3bfd5b4f3 | <|skeleton|>
class TextGenerator:
"""Text generator pipiline."""
def __init__(self, tokenizer, model, device=-1, framework='pt'):
"""Init class object."""
<|body_0|>
def __call__(self, seqs):
"""Call class object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextGenerator:
"""Text generator pipiline."""
def __init__(self, tokenizer, model, device=-1, framework='pt'):
"""Init class object."""
set_seed(int(time()))
tokenizer = create_tokenizer(tokenizer)
model = create_model(model)
self._text_generation_pipiline = _creat... | the_stack_v2_python_sparse | gpt/gptrun.py | erdzhemadinov/MADE_FINAL_PROJECT | train | 0 |
98c257929487290b4af7a5e9f824f0a14554f2b4 | [
"p2c, c2p = ({}, {})\nfor edge in edges:\n p, c = edge\n p2c[p] = p2c.get(p, [])\n p2c[p].append(c)\n c2p[c] = p\np2c_dist = {}\nfor p in p2c:\n p2c_dist[p] = []\n stack = [(c, 1) for c in p2c[p]]\n while stack:\n node, depth = stack.pop()\n p2c_dist[p].append((node, depth))\n ... | <|body_start_0|>
p2c, c2p = ({}, {})
for edge in edges:
p, c = edge
p2c[p] = p2c.get(p, [])
p2c[p].append(c)
c2p[c] = p
p2c_dist = {}
for p in p2c:
p2c_dist[p] = []
stack = [(c, 1) for c in p2c[p]]
while ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumOfDistancesInTree2(self, N, edges):
"""Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List... | stack_v2_sparse_classes_36k_train_016285 | 4,875 | no_license | [
{
"docstring": "Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]",
"name": "sumOfDistancesInTree",
"signature": "def sumOfDistancesInTree(self, N, edges)"
},
{
"docstring": "Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List[int]] :rtype: List... | 4 | stack_v2_sparse_classes_30k_test_000604 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfDistancesInTree(self, N, edges): Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]
- def sumOfDistancesInTree2(self, N, edges): Brute force, TLE... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumOfDistancesInTree(self, N, edges): Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]
- def sumOfDistancesInTree2(self, N, edges): Brute force, TLE... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
<|body_0|>
def sumOfDistancesInTree2(self, N, edges):
"""Brute force, TLE Time: O(N^2) Space: O(N) :type N: int :type edges: List[List... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sumOfDistancesInTree(self, N, edges):
"""Wrong attempt. :type N: int :type edges: List[List[int]] :rtype: List[int]"""
p2c, c2p = ({}, {})
for edge in edges:
p, c = edge
p2c[p] = p2c.get(p, [])
p2c[p].append(c)
c2p[c] = p
... | the_stack_v2_python_sparse | py/leetcode_py/834.py | imsure/tech-interview-prep | train | 0 | |
fd8fc14510a0d3184fb16bc9cb5dba0dac443f25 | [
"def helper(cur):\n if not cur:\n return\n ans.append(cur.val)\n helper(cur.left)\n helper(cur.right)\n return ans\nans = []\nhelper(root)\nreturn ','.join([str(elem) for elem in ans])",
"def helper(target, cur):\n if not cur:\n return TreeNode(target)\n elif target < cur.val:\n... | <|body_start_0|>
def helper(cur):
if not cur:
return
ans.append(cur.val)
helper(cur.left)
helper(cur.right)
return ans
ans = []
helper(root)
return ','.join([str(elem) for elem in ans])
<|end_body_0|>
<|body_sta... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(cur... | stack_v2_sparse_classes_36k_train_016286 | 5,056 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_007831 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 1abc28919abb55b93d3879860ac9c1297d493d09 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def helper(cur):
if not cur:
return
ans.append(cur.val)
helper(cur.left)
helper(cur.right)
return ans
ans = []
... | the_stack_v2_python_sparse | lc/449.SerializeAndDeserializeBST.py | akimi-yano/algorithm-practice | train | 0 | |
f0e43234444c7094363ebb2b24a04a508ad0f3a3 | [
"self.order = order\nself.images = calibration_images\nself.positions = calibration_positions\nself.Dx = None\nself.Dy = None\nself.model_x = None\nself.model_y = None\nself.calibrate()",
"Dx = np.empty((0, 2), float)\nDy = np.empty((0, 2), float)\nfor i, im in enumerate(self.images):\n el = detector.find_pupi... | <|body_start_0|>
self.order = order
self.images = calibration_images
self.positions = calibration_positions
self.Dx = None
self.Dy = None
self.model_x = None
self.model_y = None
self.calibrate()
<|end_body_0|>
<|body_start_1|>
Dx = np.empty((0, 2)... | Linear regression model for gaze estimation. | PolynomialGaze | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PolynomialGaze:
"""Linear regression model for gaze estimation."""
def __init__(self, calibration_images, calibration_positions, order):
"""Uses calibration_images and calibratoin_positions to create regression mode."""
<|body_0|>
def calibrate(self):
"""Create t... | stack_v2_sparse_classes_36k_train_016287 | 3,848 | no_license | [
{
"docstring": "Uses calibration_images and calibratoin_positions to create regression mode.",
"name": "__init__",
"signature": "def __init__(self, calibration_images, calibration_positions, order)"
},
{
"docstring": "Create the regression model here.",
"name": "calibrate",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_003257 | Implement the Python class `PolynomialGaze` described below.
Class description:
Linear regression model for gaze estimation.
Method signatures and docstrings:
- def __init__(self, calibration_images, calibration_positions, order): Uses calibration_images and calibratoin_positions to create regression mode.
- def cali... | Implement the Python class `PolynomialGaze` described below.
Class description:
Linear regression model for gaze estimation.
Method signatures and docstrings:
- def __init__(self, calibration_images, calibration_positions, order): Uses calibration_images and calibratoin_positions to create regression mode.
- def cali... | 92f9e637a54bad9f76a180570fbb83958f0517ae | <|skeleton|>
class PolynomialGaze:
"""Linear regression model for gaze estimation."""
def __init__(self, calibration_images, calibration_positions, order):
"""Uses calibration_images and calibratoin_positions to create regression mode."""
<|body_0|>
def calibrate(self):
"""Create t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PolynomialGaze:
"""Linear regression model for gaze estimation."""
def __init__(self, calibration_images, calibration_positions, order):
"""Uses calibration_images and calibratoin_positions to create regression mode."""
self.order = order
self.images = calibration_images
s... | the_stack_v2_python_sparse | gaze.py | sruthi-pasham/IAML_GH_2021 | train | 0 |
62302a2abe554dda8ac4750e5831d5cc91f1ec72 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers. | AdGroupBidModifierServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupBidModifierServiceServicer:
"""Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers."""
def GetAdGroupBidModifier(self, request, context):
"""Returns the requested ad group bid modifier in full detail."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_016288 | 3,720 | permissive | [
{
"docstring": "Returns the requested ad group bid modifier in full detail.",
"name": "GetAdGroupBidModifier",
"signature": "def GetAdGroupBidModifier(self, request, context)"
},
{
"docstring": "Creates, updates, or removes ad group bid modifiers. Operation statuses are returned.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_020798 | Implement the Python class `AdGroupBidModifierServiceServicer` described below.
Class description:
Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers.
Method signatures and docstrings:
- def GetAdGroupBidModifier(self, request, context): Returns the requested ad group bi... | Implement the Python class `AdGroupBidModifierServiceServicer` described below.
Class description:
Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers.
Method signatures and docstrings:
- def GetAdGroupBidModifier(self, request, context): Returns the requested ad group bi... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class AdGroupBidModifierServiceServicer:
"""Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers."""
def GetAdGroupBidModifier(self, request, context):
"""Returns the requested ad group bid modifier in full detail."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdGroupBidModifierServiceServicer:
"""Proto file describing the Ad Group Bid Modifier service. Service to manage ad group bid modifiers."""
def GetAdGroupBidModifier(self, request, context):
"""Returns the requested ad group bid modifier in full detail."""
context.set_code(grpc.StatusCode... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/ad_group_bid_modifier_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
06caa818d4be07e4c676f90f315ae2cd2f1d1d54 | [
"if GuidedBackprop.GuidedReluRegistered is False:\n\n @tf.RegisterGradient('GuidedRelu')\n def _GuidedReluGrad(op, grad):\n gate_g = tf.cast(grad > 0, 'float32')\n gate_y = tf.cast(op.outputs[0] > 0, 'float32')\n return gate_y * gate_g * grad\nGuidedBackprop.GuidedReluRegistered = True\n'... | <|body_start_0|>
if GuidedBackprop.GuidedReluRegistered is False:
@tf.RegisterGradient('GuidedRelu')
def _GuidedReluGrad(op, grad):
gate_g = tf.cast(grad > 0, 'float32')
gate_y = tf.cast(op.outputs[0] > 0, 'float32')
return gate_y * gate_g... | A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806 | GuidedBackprop | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GuidedBackprop:
"""A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806"""
def __init__(self, model, output_index=0, custom_los... | stack_v2_sparse_classes_36k_train_016289 | 8,246 | no_license | [
{
"docstring": "Constructs a GuidedBackprop SaliencyMask.",
"name": "__init__",
"signature": "def __init__(self, model, output_index=0, custom_loss=None)"
},
{
"docstring": "Returns a GuidedBackprop mask.",
"name": "get_mask",
"signature": "def get_mask(self, input_image)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001515 | Implement the Python class `GuidedBackprop` described below.
Class description:
A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806
Method signatures an... | Implement the Python class `GuidedBackprop` described below.
Class description:
A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806
Method signatures an... | 7f31289483bad437268df2778494744fd8eb02e4 | <|skeleton|>
class GuidedBackprop:
"""A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806"""
def __init__(self, model, output_index=0, custom_los... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GuidedBackprop:
"""A SaliencyMask class that computes saliency masks with GuidedBackProp. This implementation copies the TensorFlow graph to a new graph with the ReLU gradient overwritten as in the paper: https://arxiv.org/abs/1412.6806"""
def __init__(self, model, output_index=0, custom_loss=None):
... | the_stack_v2_python_sparse | Algos/06-CNN-Optimized/CNN_model_Visualization/SaliencyMaps.py | freedomandfinally/Sleep_Apnea_Detection | train | 1 |
8cd089e5fe8ac3149330de8c17073ee2b4a187c4 | [
"super(Literal, self).__init__(value)\nself.value = value\nself.validate()",
"if self.value is None or self.value is True or self.value is False:\n return\nif isinstance(self.value, six.string_types):\n validate_safe_string(self.value)\n return\nif isinstance(self.value, int):\n return\nif isinstance(... | <|body_start_0|>
super(Literal, self).__init__(value)
self.value = value
self.validate()
<|end_body_0|>
<|body_start_1|>
if self.value is None or self.value is True or self.value is False:
return
if isinstance(self.value, six.string_types):
validate_safe_... | A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they trigger string interpolation in Groovy/Gremlin. http://docs.groovy-lang.org/... | Literal | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Literal:
"""A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they trigger string interpolation in Groovy/Gr... | stack_v2_sparse_classes_36k_train_016290 | 41,432 | permissive | [
{
"docstring": "Construct a new Literal object with the given value.",
"name": "__init__",
"signature": "def __init__(self, value)"
},
{
"docstring": "Validate that the Literal is correctly representable.",
"name": "validate",
"signature": "def validate(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_019577 | Implement the Python class `Literal` described below.
Class description:
A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they tr... | Implement the Python class `Literal` described below.
Class description:
A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they tr... | 4511793281698bd55e63fd7a3f25f9cb094084d4 | <|skeleton|>
class Literal:
"""A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they trigger string interpolation in Groovy/Gr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Literal:
"""A literal, such as a boolean value, null, or a fixed string value. We have to be extra careful with string literals -- for ease of escaping, we use json.dumps() to represent strings. However, we must then manually escape '$' characters as they trigger string interpolation in Groovy/Gremlin. http:/... | the_stack_v2_python_sparse | graphql_compiler/compiler/expressions.py | jb-kensho/graphql-compiler | train | 0 |
b31dbddd2fb70acb1c19b2dfb5bfb8219b8e90b8 | [
"super().__init__([place1, place2])\nself.place1: str = place1\nself.place2: str = place2",
"if self.place1 not in assignment or self.place2 not in assignment:\n return True\nreturn assignment[self.place1] != assignment[self.place2]"
] | <|body_start_0|>
super().__init__([place1, place2])
self.place1: str = place1
self.place2: str = place2
<|end_body_0|>
<|body_start_1|>
if self.place1 not in assignment or self.place2 not in assignment:
return True
return assignment[self.place1] != assignment[self.pl... | MapColoringConstraint is a subclass of Constraint class. | MapColoringConstraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MapColoringConstraint:
"""MapColoringConstraint is a subclass of Constraint class."""
def __init__(self, place1: str, place2: str) -> None:
"""Constructor for MapColoringConstraint."""
<|body_0|>
def satisfied(self, assignment: Dict[str, str]) -> bool:
"""Abstrac... | stack_v2_sparse_classes_36k_train_016291 | 10,604 | no_license | [
{
"docstring": "Constructor for MapColoringConstraint.",
"name": "__init__",
"signature": "def __init__(self, place1: str, place2: str) -> None"
},
{
"docstring": "Abstract method satisfied in subclass.",
"name": "satisfied",
"signature": "def satisfied(self, assignment: Dict[str, str]) ... | 2 | stack_v2_sparse_classes_30k_train_010879 | Implement the Python class `MapColoringConstraint` described below.
Class description:
MapColoringConstraint is a subclass of Constraint class.
Method signatures and docstrings:
- def __init__(self, place1: str, place2: str) -> None: Constructor for MapColoringConstraint.
- def satisfied(self, assignment: Dict[str, s... | Implement the Python class `MapColoringConstraint` described below.
Class description:
MapColoringConstraint is a subclass of Constraint class.
Method signatures and docstrings:
- def __init__(self, place1: str, place2: str) -> None: Constructor for MapColoringConstraint.
- def satisfied(self, assignment: Dict[str, s... | 892d9c25b9712bf3bbfd7f29529eca8b47fb8039 | <|skeleton|>
class MapColoringConstraint:
"""MapColoringConstraint is a subclass of Constraint class."""
def __init__(self, place1: str, place2: str) -> None:
"""Constructor for MapColoringConstraint."""
<|body_0|>
def satisfied(self, assignment: Dict[str, str]) -> bool:
"""Abstrac... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MapColoringConstraint:
"""MapColoringConstraint is a subclass of Constraint class."""
def __init__(self, place1: str, place2: str) -> None:
"""Constructor for MapColoringConstraint."""
super().__init__([place1, place2])
self.place1: str = place1
self.place2: str = place2
... | the_stack_v2_python_sparse | sem-4/Lab7_15_2/Lab7_GraphColoringProblem_ConstraintSatisfactionAlgorithm.py | B-Tech-AI-Python/Class-assignments | train | 0 |
d95c17b183fa43f359efccbd343a70b0565b9d25 | [
"if x < 0:\n return -self.reverse(-x)\nresult = 0\nwhile x:\n result = result * 10 + x % 10\n x //= 10\nreturn result if result <= 2147483647 else 0",
"if x < 0:\n x = int(str(x)[::-1][-1] + str(x)[::-1][:-1])\nelse:\n x = int(str(x)[::-1])\nx = 0 if abs(x) > 2147483647 else x\nreturn x",
"def cm... | <|body_start_0|>
if x < 0:
return -self.reverse(-x)
result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if result <= 2147483647 else 0
<|end_body_0|>
<|body_start_1|>
if x < 0:
x = int(str(x)[::-1][-1] + str(x)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
def reverse3(self, x):
""":type x: int :rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_016292 | 2,497 | no_license | [
{
"docstring": ":type x: int :rtype: int",
"name": "reverse",
"signature": "def reverse(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse2",
"signature": "def reverse2(self, x)"
},
{
"docstring": ":type x: int :rtype: int",
"name": "reverse3",
"sign... | 3 | stack_v2_sparse_classes_30k_train_005705 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
- def reverse3(self, x): :type x: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x): :type x: int :rtype: int
- def reverse2(self, x): :type x: int :rtype: int
- def reverse3(self, x): :type x: int :rtype: int
<|skeleton|>
class Solution:
... | 5195b032d8000a3d888e2d4068984011bebd3b84 | <|skeleton|>
class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
<|body_0|>
def reverse2(self, x):
""":type x: int :rtype: int"""
<|body_1|>
def reverse3(self, x):
""":type x: int :rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse(self, x):
""":type x: int :rtype: int"""
if x < 0:
return -self.reverse(-x)
result = 0
while x:
result = result * 10 + x % 10
x //= 10
return result if result <= 2147483647 else 0
def reverse2(self, x):
... | the_stack_v2_python_sparse | leetcode_python/Math/reverse-integer.py | ChillOrb/CS_basics | train | 1 | |
0aa1b2ff1cf2aa85261794a31af4e90979e79a5a | [
"super().__init__()\nself.critic1 = CriticNet(state_dim, action_dim, hidden_dims=hidden_dims)\nself.critic2 = CriticNet(state_dim, action_dim, hidden_dims=hidden_dims)",
"q1 = self.critic1(states, actions)\nq2 = self.critic2(states, actions)\nreturn (q1, q2)"
] | <|body_start_0|>
super().__init__()
self.critic1 = CriticNet(state_dim, action_dim, hidden_dims=hidden_dims)
self.critic2 = CriticNet(state_dim, action_dim, hidden_dims=hidden_dims)
<|end_body_0|>
<|body_start_1|>
q1 = self.critic1(states, actions)
q2 = self.critic2(states, acti... | A critic network that estimates a dual Q-function. | Critic | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of hidden dimensions."""
<|body_0|>
def call(s... | stack_v2_sparse_classes_36k_train_016293 | 3,135 | permissive | [
{
"docstring": "Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of hidden dimensions.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim, hidden_dims=(256, 256))"
},
{
"docstring": "Returns Q-value estimates for given states and... | 2 | null | Implement the Python class `Critic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of... | Implement the Python class `Critic` described below.
Class description:
A critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Critic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of hidden dimensions."""
<|body_0|>
def call(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
"""A critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_dim, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_dim: Action size. hidden_dims: List of hidden dimensions."""
super().__init__()
self.critic1... | the_stack_v2_python_sparse | fisher_brc/critic.py | Jimmy-INL/google-research | train | 1 |
4a78dabddfdf462145a873d2986c334e7e4d0b04 | [
"self.data = data\nself.tokenizer = RegexpTokenizer('[A-Za-z\\\\d]+')\nself.STOP = set([w for w in stopwords.words('english') if len(w) > 1])\nself.STOP.update(['pathway', 'pathways'])",
"features = dict()\nkb_tokens = string_utils.tokenize_string(pair['kb_cls'], self.tokenizer, self.STOP)\npw_tokens = string_uti... | <|body_start_0|>
self.data = data
self.tokenizer = RegexpTokenizer('[A-Za-z\\d]+')
self.STOP = set([w for w in stopwords.words('english') if len(w) > 1])
self.STOP.update(['pathway', 'pathways'])
<|end_body_0|>
<|body_start_1|>
features = dict()
kb_tokens = string_utils.... | FeatureGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureGenerator:
def __init__(self, data):
"""Initialize feature vector"""
<|body_0|>
def compute_one(self, pair):
"""Compute features for one pair :return:"""
<|body_1|>
def compute_features(self, show_progress=False):
"""Compute sparse feature... | stack_v2_sparse_classes_36k_train_016294 | 2,988 | permissive | [
{
"docstring": "Initialize feature vector",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Compute features for one pair :return:",
"name": "compute_one",
"signature": "def compute_one(self, pair)"
},
{
"docstring": "Compute sparse features from da... | 3 | stack_v2_sparse_classes_30k_train_017915 | Implement the Python class `FeatureGenerator` described below.
Class description:
Implement the FeatureGenerator class.
Method signatures and docstrings:
- def __init__(self, data): Initialize feature vector
- def compute_one(self, pair): Compute features for one pair :return:
- def compute_features(self, show_progre... | Implement the Python class `FeatureGenerator` described below.
Class description:
Implement the FeatureGenerator class.
Method signatures and docstrings:
- def __init__(self, data): Initialize feature vector
- def compute_one(self, pair): Compute features for one pair :return:
- def compute_features(self, show_progre... | 56178260f499bab60bab0061f05101c92922c45c | <|skeleton|>
class FeatureGenerator:
def __init__(self, data):
"""Initialize feature vector"""
<|body_0|>
def compute_one(self, pair):
"""Compute features for one pair :return:"""
<|body_1|>
def compute_features(self, show_progress=False):
"""Compute sparse feature... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureGenerator:
def __init__(self, data):
"""Initialize feature vector"""
self.data = data
self.tokenizer = RegexpTokenizer('[A-Za-z\\d]+')
self.STOP = set([w for w in stopwords.words('english') if len(w) > 1])
self.STOP.update(['pathway', 'pathways'])
def comput... | the_stack_v2_python_sparse | pathhier/feature_generator.py | lucylw/pathhier | train | 2 | |
a4bd136857769352d181965d0072472887e8c4bd | [
"self.xinput = xinput\nself.var_scope = var_scope\nself.critic_layers = critic_layers\nself.clusters_no = clusters_no\nself.input_clusters = input_clusters\nself.reuse = reuse\nself.dist = dist",
"with tf.variable_scope(var_scope, reuse=reuse):\n for i_lay, output_size in enumerate(critic_layers):\n wit... | <|body_start_0|>
self.xinput = xinput
self.var_scope = var_scope
self.critic_layers = critic_layers
self.clusters_no = clusters_no
self.input_clusters = input_clusters
self.reuse = reuse
self.dist = dist
<|end_body_0|>
<|body_start_1|>
with tf.variable_sc... | Generic class for the Critic network | Critic | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Critic:
"""Generic class for the Critic network"""
def __init__(self, xinput, dist, var_scope, critic_layers, input_clusters=None, clusters_no=None, reuse=None):
"""Default constructor. Parameters ---------- xinput : Tensor Tensor containing the input cells. dist : Tensor Tensor cont... | stack_v2_sparse_classes_36k_train_016295 | 29,633 | permissive | [
{
"docstring": "Default constructor. Parameters ---------- xinput : Tensor Tensor containing the input cells. dist : Tensor Tensor containing the output of the Critic (e.g. the Wasserstein distance). var_scope : str Variable scope used for the created tensors. critic_layers : list List of integers corresponding... | 4 | stack_v2_sparse_classes_30k_train_015430 | Implement the Python class `Critic` described below.
Class description:
Generic class for the Critic network
Method signatures and docstrings:
- def __init__(self, xinput, dist, var_scope, critic_layers, input_clusters=None, clusters_no=None, reuse=None): Default constructor. Parameters ---------- xinput : Tensor Ten... | Implement the Python class `Critic` described below.
Class description:
Generic class for the Critic network
Method signatures and docstrings:
- def __init__(self, xinput, dist, var_scope, critic_layers, input_clusters=None, clusters_no=None, reuse=None): Default constructor. Parameters ---------- xinput : Tensor Ten... | a06f8ccd6a071d57e591dacd6164c9f78987a794 | <|skeleton|>
class Critic:
"""Generic class for the Critic network"""
def __init__(self, xinput, dist, var_scope, critic_layers, input_clusters=None, clusters_no=None, reuse=None):
"""Default constructor. Parameters ---------- xinput : Tensor Tensor containing the input cells. dist : Tensor Tensor cont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Critic:
"""Generic class for the Critic network"""
def __init__(self, xinput, dist, var_scope, critic_layers, input_clusters=None, clusters_no=None, reuse=None):
"""Default constructor. Parameters ---------- xinput : Tensor Tensor containing the input cells. dist : Tensor Tensor containing the ou... | the_stack_v2_python_sparse | estimators/utilities.py | imsb-uke/scGAN | train | 73 |
c56f5b5aae34bf45f271a48cc1e7124f540759b6 | [
"assert start_num >= 0\ncurrent_verse = self.verse(start_num) + '\\n'\nif start_num > 0 and start_num > end_num:\n return current_verse + self.sing(start_num - 1, end_num)\nelse:\n return current_verse",
"if num_bottles == 0:\n return 'No more bottles of beer on the wall, no more bottles of beer.\\nGo to... | <|body_start_0|>
assert start_num >= 0
current_verse = self.verse(start_num) + '\n'
if start_num > 0 and start_num > end_num:
return current_verse + self.sing(start_num - 1, end_num)
else:
return current_verse
<|end_body_0|>
<|body_start_1|>
if num_bottle... | Beer Song Simulator 20XX | Beer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Beer:
"""Beer Song Simulator 20XX"""
def sing(self, start_num, end_num=0):
"""Sing the verses of the beer song from range start to end."""
<|body_0|>
def verse(self, num_bottles):
"""Recite the n-th verse of the beer song."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_016296 | 1,523 | no_license | [
{
"docstring": "Sing the verses of the beer song from range start to end.",
"name": "sing",
"signature": "def sing(self, start_num, end_num=0)"
},
{
"docstring": "Recite the n-th verse of the beer song.",
"name": "verse",
"signature": "def verse(self, num_bottles)"
}
] | 2 | null | Implement the Python class `Beer` described below.
Class description:
Beer Song Simulator 20XX
Method signatures and docstrings:
- def sing(self, start_num, end_num=0): Sing the verses of the beer song from range start to end.
- def verse(self, num_bottles): Recite the n-th verse of the beer song. | Implement the Python class `Beer` described below.
Class description:
Beer Song Simulator 20XX
Method signatures and docstrings:
- def sing(self, start_num, end_num=0): Sing the verses of the beer song from range start to end.
- def verse(self, num_bottles): Recite the n-th verse of the beer song.
<|skeleton|>
class... | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | <|skeleton|>
class Beer:
"""Beer Song Simulator 20XX"""
def sing(self, start_num, end_num=0):
"""Sing the verses of the beer song from range start to end."""
<|body_0|>
def verse(self, num_bottles):
"""Recite the n-th verse of the beer song."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Beer:
"""Beer Song Simulator 20XX"""
def sing(self, start_num, end_num=0):
"""Sing the verses of the beer song from range start to end."""
assert start_num >= 0
current_verse = self.verse(start_num) + '\n'
if start_num > 0 and start_num > end_num:
return curren... | the_stack_v2_python_sparse | all_data/exercism_data/python/beer-song/6d48abf4bc5040f0991687a2062a2773.py | itsolutionscorp/AutoStyle-Clustering | train | 4 |
1bb69a91efb77ee151f70f2ba35860b4a4cbaaea | [
"dirpath_test_tree = os.path.join(dirpath_testdata, 'dir_with_files_and_folders_for_filtering')\nactual_output = tuple(da.lwc.search.filtered_filepath_generator(root=dirpath_test_tree, direxcl=None, pathincl=None, pathexcl=None))\nexpected_output = (os.path.join(dirpath_test_tree, 'dir_to_be_filtered', 'file_in_fil... | <|body_start_0|>
dirpath_test_tree = os.path.join(dirpath_testdata, 'dir_with_files_and_folders_for_filtering')
actual_output = tuple(da.lwc.search.filtered_filepath_generator(root=dirpath_test_tree, direxcl=None, pathincl=None, pathexcl=None))
expected_output = (os.path.join(dirpath_test_tree, ... | Specify the da.lwc.search.filtered_filepath_generator function. | SpecifyFilteredFilepathGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecifyFilteredFilepathGenerator:
"""Specify the da.lwc.search.filtered_filepath_generator function."""
def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata):
"""Test that undefined filters cause all filepaths to be returned."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_016297 | 29,518 | permissive | [
{
"docstring": "Test that undefined filters cause all filepaths to be returned.",
"name": "it_undefined_filters_shall_cause_all_filepaths_to_be_returned",
"signature": "def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata)"
},
{
"docstring": "Test we exclude w... | 4 | null | Implement the Python class `SpecifyFilteredFilepathGenerator` described below.
Class description:
Specify the da.lwc.search.filtered_filepath_generator function.
Method signatures and docstrings:
- def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata): Test that undefined filters c... | Implement the Python class `SpecifyFilteredFilepathGenerator` described below.
Class description:
Specify the da.lwc.search.filtered_filepath_generator function.
Method signatures and docstrings:
- def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata): Test that undefined filters c... | 04a13be2792323e3f9fdb83fd236a8e9cfe6aa2d | <|skeleton|>
class SpecifyFilteredFilepathGenerator:
"""Specify the da.lwc.search.filtered_filepath_generator function."""
def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata):
"""Test that undefined filters cause all filepaths to be returned."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecifyFilteredFilepathGenerator:
"""Specify the da.lwc.search.filtered_filepath_generator function."""
def it_undefined_filters_shall_cause_all_filepaths_to_be_returned(self, dirpath_testdata):
"""Test that undefined filters cause all filepaths to be returned."""
dirpath_test_tree = os.p... | the_stack_v2_python_sparse | a3_src/h70_internal/da/lwc/spec/spec_search.py | wtpayne/hiai | train | 5 |
fb7b86666d2cc65ea663da18fb4a08aa8788a22d | [
"self.model = model.eval()\nself.save_dir = save_dir\nif os.path.exists(save_dir) is False:\n os.makedirs(save_dir)",
"path = os.path.join(self.save_path, save_name + '.npy')\nif os.path.exists(path) is True:\n print('{} already exist'.format(path))\n return False\ntry:\n extracted_feature = self.mode... | <|body_start_0|>
self.model = model.eval()
self.save_dir = save_dir
if os.path.exists(save_dir) is False:
os.makedirs(save_dir)
<|end_body_0|>
<|body_start_1|>
path = os.path.join(self.save_path, save_name + '.npy')
if os.path.exists(path) is True:
print(... | BaseFeatureExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
<|body_0|>
def extract_feature(self, video, save_name):
"""Extract feature from video and save as save_path... | stack_v2_sparse_classes_36k_train_016298 | 3,195 | no_license | [
{
"docstring": "Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save",
"name": "__init__",
"signature": "def __init__(self, model, save_dir)"
},
{
"docstring": "Extract feature from video and save as save_path/save_name.npy Args: video (Tensor): Video Te... | 3 | stack_v2_sparse_classes_30k_train_012766 | Implement the Python class `BaseFeatureExtractor` described below.
Class description:
Implement the BaseFeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, model, save_dir): Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save
- def extract_feature(... | Implement the Python class `BaseFeatureExtractor` described below.
Class description:
Implement the BaseFeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, model, save_dir): Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save
- def extract_feature(... | dc6fdb5ed4ee7746e731cbe449ce83a0831eb860 | <|skeleton|>
class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
<|body_0|>
def extract_feature(self, video, save_name):
"""Extract feature from video and save as save_path... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFeatureExtractor:
def __init__(self, model, save_dir):
"""Args: model (subclass torch.nn.Module): Model for extraction save_dir (str): Directory to save"""
self.model = model.eval()
self.save_dir = save_dir
if os.path.exists(save_dir) is False:
os.makedirs(save_... | the_stack_v2_python_sparse | agents/base.py | robinstart/video2text_abr | train | 5 | |
86032cf0a044b388109cde1acea1d15ff76b1105 | [
"m, n = (len(grid), len(grid[0]))\n\ndef bfs(grid, i, j, visited):\n Q = deque()\n Q.append((i, j))\n while len(Q):\n i1, j1 = Q.popleft()\n if grid[i1][j1] == 1:\n return abs(i1 - i) + abs(j1 - j)\n visited[i1][j1] = 1\n if 0 <= j1 - 1 < n and visited[i1][j1 - 1] == ... | <|body_start_0|>
m, n = (len(grid), len(grid[0]))
def bfs(grid, i, j, visited):
Q = deque()
Q.append((i, j))
while len(Q):
i1, j1 = Q.popleft()
if grid[i1][j1] == 1:
return abs(i1 - i) + abs(j1 - j)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDistance(self, grid) -> int:
"""BFS,超时 :param list[list[int]] grid: :return:"""
<|body_0|>
def maxDistance2(self, grid) -> int:
"""多源BFS,其实就是有一个超级原点,然后从该点进行BFS遍历,多源点是超级原点的邻接点。 :param grid: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_016299 | 3,231 | no_license | [
{
"docstring": "BFS,超时 :param list[list[int]] grid: :return:",
"name": "maxDistance",
"signature": "def maxDistance(self, grid) -> int"
},
{
"docstring": "多源BFS,其实就是有一个超级原点,然后从该点进行BFS遍历,多源点是超级原点的邻接点。 :param grid: :return:",
"name": "maxDistance2",
"signature": "def maxDistance2(self, gri... | 2 | stack_v2_sparse_classes_30k_train_002743 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistance(self, grid) -> int: BFS,超时 :param list[list[int]] grid: :return:
- def maxDistance2(self, grid) -> int: 多源BFS,其实就是有一个超级原点,然后从该点进行BFS遍历,多源点是超级原点的邻接点。 :param grid: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDistance(self, grid) -> int: BFS,超时 :param list[list[int]] grid: :return:
- def maxDistance2(self, grid) -> int: 多源BFS,其实就是有一个超级原点,然后从该点进行BFS遍历,多源点是超级原点的邻接点。 :param grid: ... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def maxDistance(self, grid) -> int:
"""BFS,超时 :param list[list[int]] grid: :return:"""
<|body_0|>
def maxDistance2(self, grid) -> int:
"""多源BFS,其实就是有一个超级原点,然后从该点进行BFS遍历,多源点是超级原点的邻接点。 :param grid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDistance(self, grid) -> int:
"""BFS,超时 :param list[list[int]] grid: :return:"""
m, n = (len(grid), len(grid[0]))
def bfs(grid, i, j, visited):
Q = deque()
Q.append((i, j))
while len(Q):
i1, j1 = Q.popleft()
... | the_stack_v2_python_sparse | 华为题库/地图分析.py | 2226171237/Algorithmpractice | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.