blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6ccaa1fbba33f9a0bbcb608307505b1b45f8a05f | [
"N = len(nums) - 1\ndp = [sys.maxsize] * N\nif N <= 0:\n return 0\nfor i in range(N - 1, -1, -1):\n cur = nums[i]\n if cur == 0:\n continue\n if cur + i < N:\n for j in range(cur, 0, -1):\n if dp[i + j] != sys.maxsize:\n dp[i] = min(dp[i], dp[i + j] + 1)\n else... | <|body_start_0|>
N = len(nums) - 1
dp = [sys.maxsize] * N
if N <= 0:
return 0
for i in range(N - 1, -1, -1):
cur = nums[i]
if cur == 0:
continue
if cur + i < N:
for j in range(cur, 0, -1):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
N = len(nums) - 1
dp = [sys.maxsize] * N
i... | stack_v2_sparse_classes_75kplus_train_001600 | 1,613 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "jump2",
"signature": "def jump2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014609 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int
- def jump2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def jump(self, nums):
... | b77130a0133cd40990c4d7096db5e388de67cbf2 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def jump2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int"""
N = len(nums) - 1
dp = [sys.maxsize] * N
if N <= 0:
return 0
for i in range(N - 1, -1, -1):
cur = nums[i]
if cur == 0:
continue
if cur... | the_stack_v2_python_sparse | 45.JumpGame.py | flavorfan/MyLeetCode | train | 0 | |
4e6f02186fef9da7c51b474e393fb27708fd198d | [
"try:\n self._search_publish_manager = search_publish_manager.SearchPublishManager()\nexcept exceptions.Error as e:\n self._search_publish_manager = None\n logger.error(e)",
"assert isinstance(request, http_io.Request)\nassert isinstance(response, http_io.Response)\nif not self._search_publish_manager:\n... | <|body_start_0|>
try:
self._search_publish_manager = search_publish_manager.SearchPublishManager()
except exceptions.Error as e:
self._search_publish_manager = None
logger.error(e)
<|end_body_0|>
<|body_start_1|>
assert isinstance(request, http_io.Request)
... | Class for delegating search publishing requests to handlers. | SearchPublishHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchPublishHandler:
"""Class for delegating search publishing requests to handlers."""
def __init__(self):
"""Inits SearchPublishServlet."""
<|body_0|>
def DoRequest(self, request, response):
"""Handles request by delegating it to search publish manager."""
... | stack_v2_sparse_classes_75kplus_train_001601 | 3,086 | permissive | [
{
"docstring": "Inits SearchPublishServlet.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Handles request by delegating it to search publish manager.",
"name": "DoRequest",
"signature": "def DoRequest(self, request, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040187 | Implement the Python class `SearchPublishHandler` described below.
Class description:
Class for delegating search publishing requests to handlers.
Method signatures and docstrings:
- def __init__(self): Inits SearchPublishServlet.
- def DoRequest(self, request, response): Handles request by delegating it to search pu... | Implement the Python class `SearchPublishHandler` described below.
Class description:
Class for delegating search publishing requests to handlers.
Method signatures and docstrings:
- def __init__(self): Inits SearchPublishServlet.
- def DoRequest(self, request, response): Handles request by delegating it to search pu... | f7ea83f769485d9c28021b951fec8f15f641b16c | <|skeleton|>
class SearchPublishHandler:
"""Class for delegating search publishing requests to handlers."""
def __init__(self):
"""Inits SearchPublishServlet."""
<|body_0|>
def DoRequest(self, request, response):
"""Handles request by delegating it to search publish manager."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SearchPublishHandler:
"""Class for delegating search publishing requests to handlers."""
def __init__(self):
"""Inits SearchPublishServlet."""
try:
self._search_publish_manager = search_publish_manager.SearchPublishManager()
except exceptions.Error as e:
se... | the_stack_v2_python_sparse | earth_enterprise/src/server/wsgi/serve/publish/search/search_publish_handler.py | tst-ccamp/earthenterprise | train | 2 |
4683ba3ea887248810f6fab85f99953828a499ef | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedGroupSource()",
"from ..group import Group\nfrom .data_source import DataSource\nfrom .source_type import SourceType\nfrom ..group import Group\nfrom .data_source import DataSource\nfrom .source_type import SourceType\nfields: D... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UnifiedGroupSource()
<|end_body_0|>
<|body_start_1|>
from ..group import Group
from .data_source import DataSource
from .source_type import SourceType
from ..group import... | UnifiedGroupSource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedGroupSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedGroupSource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus_train_001602 | 2,587 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UnifiedGroupSource",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_012068 | Implement the Python class `UnifiedGroupSource` described below.
Class description:
Implement the UnifiedGroupSource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedGroupSource: Creates a new instance of the appropriate class based on disc... | Implement the Python class `UnifiedGroupSource` described below.
Class description:
Implement the UnifiedGroupSource class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedGroupSource: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UnifiedGroupSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedGroupSource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UnifiedGroupSource:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedGroupSource:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Un... | the_stack_v2_python_sparse | msgraph/generated/models/security/unified_group_source.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
44eafb8c193c6c5ba65faf9c6863a6951af3361c | [
"def back_track(string='', left=0, right=0):\n if len(string) == 2 * num:\n combinations.append(string)\n if left < num:\n back_track(string + '(', left + 1, right)\n if right < left:\n back_track(string + ')', left, right + 1)\nif num == 0:\n return ['']\ncombinations = []\nback_tr... | <|body_start_0|>
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combinations.append(string)
if left < num:
back_track(string + '(', left + 1, right)
if right < left:
back_track(string + ')', left, right +... | Parenthesis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_75kplus_train_001603 | 1,434 | no_license | [
{
"docstring": "Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:",
"name": "generate_combinations",
"signature": "def generate_combinations(self, num: int) -> List[str]"
},
{
"docstring": "Approach: Closure Number Time Complexity: ... | 2 | stack_v2_sparse_classes_30k_train_019035 | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | Implement the Python class `Parenthesis` described below.
Class description:
Implement the Parenthesis class.
Method signatures and docstrings:
- def generate_combinations(self, num: int) -> List[str]: Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:
- ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
<|body_0|>
def generate_combinations_(self, num: int) -> List[str]:
"""Approac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Parenthesis:
def generate_combinations(self, num: int) -> List[str]:
"""Approach: Back tracking Time Complexity: O(4^n / sqrt(n)) Space Complexity: O(4^n / sqrt(n)) :param num: :return:"""
def back_track(string='', left=0, right=0):
if len(string) == 2 * num:
combin... | the_stack_v2_python_sparse | math_and_srings/paranthesis.py | Shiv2157k/leet_code | train | 1 | |
ca19e2618fd0c75e7e88eda4c492f32a7ecb1214 | [
"self.client_id = client_id\nself.file_path = file_path\nself.view_name = view_name",
"if dictionary is None:\n return None\nclient_id = dictionary.get('clientId')\nfile_path = dictionary.get('filePath')\nview_name = dictionary.get('viewName')\nreturn cls(client_id, file_path, view_name)"
] | <|body_start_0|>
self.client_id = client_id
self.file_path = file_path
self.view_name = view_name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
client_id = dictionary.get('clientId')
file_path = dictionary.get('filePath')
view_nam... | Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string): Specifies the filepath in the view relative to the root filesystem. If this field is spe... | ClearNlmLocksParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClearNlmLocksParameters:
"""Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string): Specifies the filepath in the view re... | stack_v2_sparse_classes_75kplus_train_001604 | 2,167 | permissive | [
{
"docstring": "Constructor for the ClearNlmLocksParameters class",
"name": "__init__",
"signature": "def __init__(self, client_id=None, file_path=None, view_name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representat... | 2 | stack_v2_sparse_classes_30k_train_012614 | Implement the Python class `ClearNlmLocksParameters` described below.
Class description:
Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string)... | Implement the Python class `ClearNlmLocksParameters` described below.
Class description:
Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string)... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClearNlmLocksParameters:
"""Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string): Specifies the filepath in the view re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClearNlmLocksParameters:
"""Implementation of the 'ClearNlmLocksParameters' model. Specifies parameters required to force clear NLM Locks. Attributes: client_id (string): Specifies the id of the client, related NLM locks needs to be clear. file_path (string): Specifies the filepath in the view relative to the... | the_stack_v2_python_sparse | cohesity_management_sdk/models/clear_nlm_locks_parameters.py | cohesity/management-sdk-python | train | 24 |
463d1a4a13d45f0248bf08483e85f05db627fd86 | [
"setting_rec, created = DeviceMonitorSetting.objects.get_or_create(id=1)\nserializer = DeviceMonitorTresholdSerializer(setting_rec)\nreturn Response(serializer.data, status=status.HTTP_200_OK)",
"setting_rec, created = DeviceMonitorSetting.objects.get_or_create(id=1)\nserializer = DeviceMonitorTresholdSerializer(... | <|body_start_0|>
setting_rec, created = DeviceMonitorSetting.objects.get_or_create(id=1)
serializer = DeviceMonitorTresholdSerializer(setting_rec)
return Response(serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
setting_rec, created = DeviceMonitorSetting.obje... | DeviceMonitorTresholdView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceMonitorTresholdView:
def get(self, request, *args, **kwargs):
"""custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资产监控的使用阈值设置信息 response: examples1: { 'security_cpu_alert_percent':10, 'security_memory_alert_percent':10, 'security... | stack_v2_sparse_classes_75kplus_train_001605 | 37,149 | no_license | [
{
"docstring": "custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资产监控的使用阈值设置信息 response: examples1: { 'security_cpu_alert_percent':10, 'security_memory_alert_percent':10, 'security_disk_alert_percent':10, 'communication_cpu_alert_percent':10, 'communication_m... | 2 | null | Implement the Python class `DeviceMonitorTresholdView` described below.
Class description:
Implement the DeviceMonitorTresholdView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资... | Implement the Python class `DeviceMonitorTresholdView` described below.
Class description:
Implement the DeviceMonitorTresholdView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资... | ae1ade20044b59de1e29288fcd61ba0b71d92be3 | <|skeleton|>
class DeviceMonitorTresholdView:
def get(self, request, *args, **kwargs):
"""custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资产监控的使用阈值设置信息 response: examples1: { 'security_cpu_alert_percent':10, 'security_memory_alert_percent':10, 'security... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceMonitorTresholdView:
def get(self, request, *args, **kwargs):
"""custom_swagger: 自定义 api 接口文档 get: request: description: 所有资产监控的使用阈值设置信息 response: 200: description: 所有资产监控的使用阈值设置信息 response: examples1: { 'security_cpu_alert_percent':10, 'security_memory_alert_percent':10, 'security_disk_alert_pe... | the_stack_v2_python_sparse | base_app/views.py | liushiwen555/unified_management_platform_backend | train | 0 | |
154be23c8286dc6fb60172416cc360dbc2b6bcc0 | [
"t = k % len(nums)\nnums[:] = nums[-t:] + nums[:-t]\nreturn nums",
"a = nums[:]\nif len(nums) == 1 or len(nums) == k or k == 0:\n print(nums)\nelse:\n for i in range(len(nums)):\n nums[(i + k) % len(nums)] = a[i]\nreturn nums",
"for _ in range(k % len(nums)):\n nums.insert(0, nums[-1])\n nums... | <|body_start_0|>
t = k % len(nums)
nums[:] = nums[-t:] + nums[:-t]
return nums
<|end_body_0|>
<|body_start_1|>
a = nums[:]
if len(nums) == 1 or len(nums) == k or k == 0:
print(nums)
else:
for i in range(len(nums)):
nums[(i + k) % l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate_2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_001606 | 1,365 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead.",
"name": "rotate_2",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_039022 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead.
- def rotate_2(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anyt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums, k): Do not return anything, modify nums in-place instead.
- def rotate_2(self, nums, k): :type nums: List[int] :type k: int :rtype: void Do not return anyt... | 7f89c28917c9949fd4f19d3fbbb282abeec2f427 | <|skeleton|>
class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def rotate_2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rotate(self, nums, k):
"""Do not return anything, modify nums in-place instead."""
t = k % len(nums)
nums[:] = nums[-t:] + nums[:-t]
return nums
def rotate_2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: void Do not return anything, mo... | the_stack_v2_python_sparse | pycode/26_rotate_array.py | xiaoguangjj/leetcode | train | 2 | |
200f93291966cf9ba8d037ad0ca377c1088525ab | [
"self.card_game = []\nfor i in range(2, 15):\n for j in range(0, 4):\n self.card_game.append((i, j))\n j += 1\n i += 1",
"name_dict = {11: 'Jack', 12: 'Lady', 13: 'King', 14: 'Ace'}\nname = name_dict.get(card[0], card[0])\ncolor_dict = {0: 'Spades', 1: 'Clover', 2: 'Diamond', 3: 'Heart'}\ncolo... | <|body_start_0|>
self.card_game = []
for i in range(2, 15):
for j in range(0, 4):
self.card_game.append((i, j))
j += 1
i += 1
<|end_body_0|>
<|body_start_1|>
name_dict = {11: 'Jack', 12: 'Lady', 13: 'King', 14: 'Ace'}
name = name_d... | Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly | Cardgame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cardgame:
"""Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly"""
def __init__(self):
"""Creates a list of 52 tuples, each tuples represent a card of the game (height & color)"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus_train_001607 | 4,269 | no_license | [
{
"docstring": "Creates a list of 52 tuples, each tuples represent a card of the game (height & color)",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Receive a tuple descriptor (for instance (14, 3)) & displays the card name: its heigth and color ('Ace of Spades' here... | 5 | stack_v2_sparse_classes_30k_train_013239 | Implement the Python class `Cardgame` described below.
Class description:
Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly
Method signatures and docstrings:
- def __init__(self): Creates a list of 52 tuples, each tuples represent a card of... | Implement the Python class `Cardgame` described below.
Class description:
Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly
Method signatures and docstrings:
- def __init__(self): Creates a list of 52 tuples, each tuples represent a card of... | e858542dd20a7454db462854ba736c4dfca2b267 | <|skeleton|>
class Cardgame:
"""Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly"""
def __init__(self):
"""Creates a list of 52 tuples, each tuples represent a card of the game (height & color)"""
<|body_0|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Cardgame:
"""Definition of the Cardgame class with the following methods: constructor, card_name, shuffle, choose_card, choose_card_randomly"""
def __init__(self):
"""Creates a list of 52 tuples, each tuples represent a card of the game (height & color)"""
self.card_game = []
for ... | the_stack_v2_python_sparse | 12.07.card_game.py | obrunet/Apprendre-a-programmer-Python3 | train | 0 |
9fa30d97a1872b9786da3fcaaff9aa5de620dfb9 | [
"if type(columnName) != str:\n raise InvalidColumnName(str(columnName) + ' is not a string')\nif len(columnName) > 4:\n raise InvalidColumnName(columnName + ' is not in the range \"A\" to \"ZZZZ\"')\ncolumnNumber = -1\nfor c in columnName:\n if ord(c) < 65 or ord(c) > 90:\n raise InvalidColumnName('... | <|body_start_0|>
if type(columnName) != str:
raise InvalidColumnName(str(columnName) + ' is not a string')
if len(columnName) > 4:
raise InvalidColumnName(columnName + ' is not in the range "A" to "ZZZZ"')
columnNumber = -1
for c in columnName:
if ord(... | ColumnNameConversionUtility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnNameConversionUtility:
def columnNameToColumnNumber(self, columnName):
"""Transform strings used as cell column names (e.g., "A" in the cell reference "A5") to integers (for efficiency reasons). Requirements: - "A" is converted to 0 - "Z" is converted to 25 - "AA" follows "Z" and i... | stack_v2_sparse_classes_75kplus_train_001608 | 2,577 | no_license | [
{
"docstring": "Transform strings used as cell column names (e.g., \"A\" in the cell reference \"A5\") to integers (for efficiency reasons). Requirements: - \"A\" is converted to 0 - \"Z\" is converted to 25 - \"AA\" follows \"Z\" and is converted to 26, and so on - only strings in the range \"A\" to \"ZZZZ\" a... | 2 | stack_v2_sparse_classes_30k_train_051407 | Implement the Python class `ColumnNameConversionUtility` described below.
Class description:
Implement the ColumnNameConversionUtility class.
Method signatures and docstrings:
- def columnNameToColumnNumber(self, columnName): Transform strings used as cell column names (e.g., "A" in the cell reference "A5") to intege... | Implement the Python class `ColumnNameConversionUtility` described below.
Class description:
Implement the ColumnNameConversionUtility class.
Method signatures and docstrings:
- def columnNameToColumnNumber(self, columnName): Transform strings used as cell column names (e.g., "A" in the cell reference "A5") to intege... | d900f58f0ddc1891831b298d9b37fbe98193719d | <|skeleton|>
class ColumnNameConversionUtility:
def columnNameToColumnNumber(self, columnName):
"""Transform strings used as cell column names (e.g., "A" in the cell reference "A5") to integers (for efficiency reasons). Requirements: - "A" is converted to 0 - "Z" is converted to 25 - "AA" follows "Z" and i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ColumnNameConversionUtility:
def columnNameToColumnNumber(self, columnName):
"""Transform strings used as cell column names (e.g., "A" in the cell reference "A5") to integers (for efficiency reasons). Requirements: - "A" is converted to 0 - "Z" is converted to 25 - "AA" follows "Z" and is converted to... | the_stack_v2_python_sparse | Assignment1/Task1.py | pombreda/comp304 | train | 1 | |
8637466786620512b27563603391a25214a52602 | [
"super(CrossEntropyLoss, self).__init__()\nassert use_sigmoid is False or use_mask is False\nself.use_sigmoid = use_sigmoid\nself.use_mask = use_mask\nself.reduction = reduction\nself.loss_weight = loss_weight\nself.class_weight = class_weight\nif self.use_sigmoid:\n self.cls_criterion = binary_cross_entropy\nel... | <|body_start_0|>
super(CrossEntropyLoss, self).__init__()
assert use_sigmoid is False or use_mask is False
self.use_sigmoid = use_sigmoid
self.use_mask = use_mask
self.reduction = reduction
self.loss_weight = loss_weight
self.class_weight = class_weight
if... | CrossEntropyLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossEntropyLoss:
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0):
"""CrossEntropyLoss. Args: use_sigmoid (bool, optional): Whether the prediction uses sigmoid of softmax. Defaults to False. use_mask (bool, optional): Whether to... | stack_v2_sparse_classes_75kplus_train_001609 | 17,992 | no_license | [
{
"docstring": "CrossEntropyLoss. Args: use_sigmoid (bool, optional): Whether the prediction uses sigmoid of softmax. Defaults to False. use_mask (bool, optional): Whether to use mask cross entropy loss. Defaults to False. reduction (str, optional): . Defaults to 'mean'. Options are \"none\", \"mean\" and \"sum... | 2 | stack_v2_sparse_classes_30k_train_040167 | Implement the Python class `CrossEntropyLoss` described below.
Class description:
Implement the CrossEntropyLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0): CrossEntropyLoss. Args: use_sigmoid (bool, optional):... | Implement the Python class `CrossEntropyLoss` described below.
Class description:
Implement the CrossEntropyLoss class.
Method signatures and docstrings:
- def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0): CrossEntropyLoss. Args: use_sigmoid (bool, optional):... | 1a78e8902292dc563c1f200ad1df2faaa24d5a01 | <|skeleton|>
class CrossEntropyLoss:
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0):
"""CrossEntropyLoss. Args: use_sigmoid (bool, optional): Whether the prediction uses sigmoid of softmax. Defaults to False. use_mask (bool, optional): Whether to... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CrossEntropyLoss:
def __init__(self, use_sigmoid=False, use_mask=False, reduction='mean', class_weight=None, loss_weight=1.0):
"""CrossEntropyLoss. Args: use_sigmoid (bool, optional): Whether the prediction uses sigmoid of softmax. Defaults to False. use_mask (bool, optional): Whether to use mask cros... | the_stack_v2_python_sparse | utils/loss_utils.py | zhufeng888/3DSSD_torch | train | 2 | |
efcadca8bb457452104d8c5de6c8fd1aa7d71bc4 | [
"resp = self.client.get('/')\nself.assertEqual(resp.status_code, 200)\nself.assertTemplateUsed(resp, 'menu/list_all_current_menus.html')\nself.assertEqual(len(Menu.objects.all()), 2)",
"resp = self.client.get(reverse('menu:menu_detail', kwargs={'pk': self.menu_1.pk}))\nself.assertEqual(resp.status_code, 200)\nsel... | <|body_start_0|>
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed(resp, 'menu/list_all_current_menus.html')
self.assertEqual(len(Menu.objects.all()), 2)
<|end_body_0|>
<|body_start_1|>
resp = self.client.get(reverse('menu:menu_detail', ... | MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing. | MenuTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MenuTest:
"""MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing."""
def test_menu_list_view(self):
"""Menu list test 1. status_code test 2. template used test 3. menu list length test"""
<|body_0|>
def test_menu_detail_view(self):
... | stack_v2_sparse_classes_75kplus_train_001610 | 8,827 | no_license | [
{
"docstring": "Menu list test 1. status_code test 2. template used test 3. menu list length test",
"name": "test_menu_list_view",
"signature": "def test_menu_list_view(self)"
},
{
"docstring": "Menu detail test 1. status_code test 2. template used test 3. menu item name test 4. menu season test... | 5 | stack_v2_sparse_classes_30k_test_001164 | Implement the Python class `MenuTest` described below.
Class description:
MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing.
Method signatures and docstrings:
- def test_menu_list_view(self): Menu list test 1. status_code test 2. template used test 3. menu list length test
- def test... | Implement the Python class `MenuTest` described below.
Class description:
MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing.
Method signatures and docstrings:
- def test_menu_list_view(self): Menu list test 1. status_code test 2. template used test 3. menu list length test
- def test... | dd1d469f7292451acb0722a7474a15f9994ad561 | <|skeleton|>
class MenuTest:
"""MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing."""
def test_menu_list_view(self):
"""Menu list test 1. status_code test 2. template used test 3. menu list length test"""
<|body_0|>
def test_menu_detail_view(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MenuTest:
"""MenuTest test class Inherit: - BaseTest - 5 tests are created for all views testing."""
def test_menu_list_view(self):
"""Menu list test 1. status_code test 2. template used test 3. menu list length test"""
resp = self.client.get('/')
self.assertEqual(resp.status_code... | the_stack_v2_python_sparse | menu/tests.py | OzRayan/Improve_Django_Project | train | 0 |
28506c278a28514eed97560e02c8b7b82afd8d51 | [
"request = self.context.get('request', None)\nuser = getattr(request, 'user', None)\nif self.instance and (data['role'] == models.RoleChoices.OWNER and (not self.instance.resource.is_owner(user)) or (self.instance.role == models.RoleChoices.OWNER and (not self.instance.user == user))) or (not self.instance and data... | <|body_start_0|>
request = self.context.get('request', None)
user = getattr(request, 'user', None)
if self.instance and (data['role'] == models.RoleChoices.OWNER and (not self.instance.resource.is_owner(user)) or (self.instance.role == models.RoleChoices.OWNER and (not self.instance.user == user... | A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room. | ResourceAccessSerializerMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceAccessSerializerMixin:
"""A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room."""
def validate(self, data):
"""Check access rights specific to writing (create/update)"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_001611 | 4,225 | permissive | [
{
"docstring": "Check access rights specific to writing (create/update)",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "The logged-in user must be administrator of the resource (directly or via a group).",
"name": "validate_resource",
"signature": "def va... | 2 | stack_v2_sparse_classes_30k_test_002467 | Implement the Python class `ResourceAccessSerializerMixin` described below.
Class description:
A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room.
Method signatures and docstrings:
- def validate(self, data): Check access rights specifi... | Implement the Python class `ResourceAccessSerializerMixin` described below.
Class description:
A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room.
Method signatures and docstrings:
- def validate(self, data): Check access rights specifi... | a4f563e9a56a1948f0ae4e21dcbfb9d9ef51483e | <|skeleton|>
class ResourceAccessSerializerMixin:
"""A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room."""
def validate(self, data):
"""Check access rights specific to writing (create/update)"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceAccessSerializerMixin:
"""A serializer mixin to share controling that the logged-in user submitting a room access object is administrator on the targeted room."""
def validate(self, data):
"""Check access rights specific to writing (create/update)"""
request = self.context.get('re... | the_stack_v2_python_sparse | src/magnify/apps/core/serializers/rooms.py | openfun/jitsi-magnify | train | 23 |
178315773965ad42b1769c7b5d373b36bd69a270 | [
"self.page_size = self.get_page_size(request)\nself.page_number = self.get_page_number(request)\npaginator = DjangoPaginator(queryset, self.page_size)\npage = paginator.page(self.page_number)\nself.paginator = paginator\nreturn list(page)",
"if self.page_size_query_param:\n try:\n return _positive_int(r... | <|body_start_0|>
self.page_size = self.get_page_size(request)
self.page_number = self.get_page_number(request)
paginator = DjangoPaginator(queryset, self.page_size)
page = paginator.page(self.page_number)
self.paginator = paginator
return list(page)
<|end_body_0|>
<|body... | 自定义分页组件 | CustomPagination | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomPagination:
"""自定义分页组件"""
def paginate_queryset(self, queryset, request, view=None):
"""分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页"""
<|body_0|>
def get_page_size(self, request):
"""获取获取每页记录条数 :param request: 请求实例 :return: 每页... | stack_v2_sparse_classes_75kplus_train_001612 | 2,431 | permissive | [
{
"docstring": "分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页",
"name": "paginate_queryset",
"signature": "def paginate_queryset(self, queryset, request, view=None)"
},
{
"docstring": "获取获取每页记录条数 :param request: 请求实例 :return: 每页记录条数",
"name": "get_page_size",
... | 4 | null | Implement the Python class `CustomPagination` described below.
Class description:
自定义分页组件
Method signatures and docstrings:
- def paginate_queryset(self, queryset, request, view=None): 分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页
- def get_page_size(self, request): 获取获取每页记录条数 :param requ... | Implement the Python class `CustomPagination` described below.
Class description:
自定义分页组件
Method signatures and docstrings:
- def paginate_queryset(self, queryset, request, view=None): 分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页
- def get_page_size(self, request): 获取获取每页记录条数 :param requ... | 0705dbf3ae984800ceb98bc93135e042702bf6d8 | <|skeleton|>
class CustomPagination:
"""自定义分页组件"""
def paginate_queryset(self, queryset, request, view=None):
"""分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页"""
<|body_0|>
def get_page_size(self, request):
"""获取获取每页记录条数 :param request: 请求实例 :return: 每页... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomPagination:
"""自定义分页组件"""
def paginate_queryset(self, queryset, request, view=None):
"""分页 :param queryset: 查询模型 :param request: 请求实例 :param view: -- :return: 数据页"""
self.page_size = self.get_page_size(request)
self.page_number = self.get_page_number(request)
paginat... | the_stack_v2_python_sparse | utils/custom_pagination.py | gergulo/footprint_server | train | 0 |
db526939a2429897c2a3006edbc6c6b135715c77 | [
"if not root:\n return '#'\nq = [root]\nserial = [str(root.val)]\nwhile q:\n newq = []\n for x in q:\n if not x.left:\n serial.append('#')\n else:\n serial.append(str(x.left.val))\n newq.append(x.left)\n if not x.right:\n serial.append('#')\n... | <|body_start_0|>
if not root:
return '#'
q = [root]
serial = [str(root.val)]
while q:
newq = []
for x in q:
if not x.left:
serial.append('#')
else:
serial.append(str(x.left.val))
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_001613 | 3,922 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_024976 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 752ac00bea40be1e3794d80aa7b2be58c0a548f6 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '#'
q = [root]
serial = [str(root.val)]
while q:
newq = []
for x in q:
if not x.left:
... | the_stack_v2_python_sparse | Code/Serialize and Deserialize Binary Tree.py | mws19901118/Leetcode | train | 0 | |
7be8667b460c88fb3cc502f3a9583e0b0f872255 | [
"prefixs = collections.defaultdict(list)\nfor word in words:\n prefixs[word[0]].append(iter(word[1:]))\nfor c in S:\n for it in prefixs.pop(c, ()):\n prefixs[next(it, None)].append(it)\nreturn len(prefixs[None])",
"def match(word):\n i, j = (len(S) - 1, len(word) - 1)\n while i >= 0 and j >= 0:... | <|body_start_0|>
prefixs = collections.defaultdict(list)
for word in words:
prefixs[word[0]].append(iter(word[1:]))
for c in S:
for it in prefixs.pop(c, ()):
prefixs[next(it, None)].append(it)
return len(prefixs[None])
<|end_body_0|>
<|body_start_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def numMatchingSubseq_TLE(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_001614 | 2,891 | no_license | [
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseq",
"signature": "def numMatchingSubseq(self, S, words)"
},
{
"docstring": ":type S: str :type words: List[str] :rtype: int",
"name": "numMatchingSubseq_TLE",
"signature": "def numMatchingSubseq_TL... | 2 | stack_v2_sparse_classes_30k_train_051866 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def numMatchingSubseq_TLE(self, S, words): :type S: str :type words: List[str] :rtype: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numMatchingSubseq(self, S, words): :type S: str :type words: List[str] :rtype: int
- def numMatchingSubseq_TLE(self, S, words): :type S: str :type words: List[str] :rtype: in... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_0|>
def numMatchingSubseq_TLE(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def numMatchingSubseq(self, S, words):
""":type S: str :type words: List[str] :rtype: int"""
prefixs = collections.defaultdict(list)
for word in words:
prefixs[word[0]].append(iter(word[1:]))
for c in S:
for it in prefixs.pop(c, ()):
... | the_stack_v2_python_sparse | src/lt_792.py | oxhead/CodingYourWay | train | 0 | |
3f6165b197224705045e07b560c5804d087c6d2d | [
"value = '<div>'\nclase = 'actions'\nurl_cont = './' + str(obj.id_tipo_item)\nid_tipo = UrlParser.parse_id(request.url, 'tipositems')\nif id_tipo:\n url_cont = '../' + str(obj.id_tipo_item)\nif UrlParser.parse_nombre(request.url, 'post_buscar'):\n url_cont = '../' + str(obj.id_tipo_item)\nvalue += '<div>' + '... | <|body_start_0|>
value = '<div>'
clase = 'actions'
url_cont = './' + str(obj.id_tipo_item)
id_tipo = UrlParser.parse_id(request.url, 'tipositems')
if id_tipo:
url_cont = '../' + str(obj.id_tipo_item)
if UrlParser.parse_nombre(request.url, 'post_buscar'):
... | ProyectoTipoItemTableFiller | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProyectoTipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_proyecto=None, id_tipo=None, **kw):
"""Se muestra la lista de tipos de ítem para el proyecto en cuestión"""
... | stack_v2_sparse_classes_75kplus_train_001615 | 8,576 | no_license | [
{
"docstring": "Links de acciones para un registro dado",
"name": "__actions__",
"signature": "def __actions__(self, obj)"
},
{
"docstring": "Se muestra la lista de tipos de ítem para el proyecto en cuestión",
"name": "_do_get_provider_count_and_objs",
"signature": "def _do_get_provider_... | 2 | stack_v2_sparse_classes_30k_train_036572 | Implement the Python class `ProyectoTipoItemTableFiller` described below.
Class description:
Implement the ProyectoTipoItemTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_proyecto=None, id_tipo=No... | Implement the Python class `ProyectoTipoItemTableFiller` described below.
Class description:
Implement the ProyectoTipoItemTableFiller class.
Method signatures and docstrings:
- def __actions__(self, obj): Links de acciones para un registro dado
- def _do_get_provider_count_and_objs(self, id_proyecto=None, id_tipo=No... | 997531e130d1951b483f4a6a67f2df7467cd9fd1 | <|skeleton|>
class ProyectoTipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
<|body_0|>
def _do_get_provider_count_and_objs(self, id_proyecto=None, id_tipo=None, **kw):
"""Se muestra la lista de tipos de ítem para el proyecto en cuestión"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProyectoTipoItemTableFiller:
def __actions__(self, obj):
"""Links de acciones para un registro dado"""
value = '<div>'
clase = 'actions'
url_cont = './' + str(obj.id_tipo_item)
id_tipo = UrlParser.parse_id(request.url, 'tipositems')
if id_tipo:
url_c... | the_stack_v2_python_sparse | lpm/controllers/proyecto_tipoitem.py | jorgeramirez/LPM | train | 1 | |
5ff24d115c0b53d9962b8aad7c909328bbd9859b | [
"try:\n driver = HomeElement(self.driver)\n driver.get(self.url)\n driver.new_table_click(location=1)\n driver.full_windows_screen(self.screenshots_path, 1920, 980)\n self.first = driver.news_assert(url=self.data[0])\n self.assertEqual(self.first, self.second)\nexcept Exception:\n self.error = ... | <|body_start_0|>
try:
driver = HomeElement(self.driver)
driver.get(self.url)
driver.new_table_click(location=1)
driver.full_windows_screen(self.screenshots_path, 1920, 980)
self.first = driver.news_assert(url=self.data[0])
self.assertEqual(... | :param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法 | TestNewCenter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNewCenter:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_good_news_table_one(self):
"""验证GoodNews是否能正常打开并跳转; 1、打开首页; 2、点击GoodNews... | stack_v2_sparse_classes_75kplus_train_001616 | 3,012 | no_license | [
{
"docstring": "验证GoodNews是否能正常打开并跳转; 1、打开首页; 2、点击GoodNews; 3、断言跳转的url是否包含{/news/71.html}",
"name": "test_good_news_table_one",
"signature": "def test_good_news_table_one(self)"
},
{
"docstring": "验证GoodNewsTwo是否能正常打开并跳转; 1、打开首页; 2、点击GoodNewsTwo; 3、断言跳转的url是否包含{/news/48.html}",
"name": "test... | 3 | stack_v2_sparse_classes_30k_val_000102 | Implement the Python class `TestNewCenter` described below.
Class description:
:param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法
Method signatures and docstrings:
- def test_good_news_ta... | Implement the Python class `TestNewCenter` described below.
Class description:
:param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法
Method signatures and docstrings:
- def test_good_news_ta... | 86bb051e62abdf2ed5bbdbea4c9008a6c1f49060 | <|skeleton|>
class TestNewCenter:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_good_news_table_one(self):
"""验证GoodNews是否能正常打开并跳转; 1、打开首页; 2、点击GoodNews... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestNewCenter:
""":param: RE_LOGIN: 需要切换账号登录,当RE_LOGIN = True时,需要将LOGIN_INFO的value值全填写完成, 如果请求的账号中只有一家公司,那么company中的value就可以忽略不填写,否则会报错... :param: MODULE: 为当前运行的模块,根据当前运行的模块调用common中的对应的用例方法,需保留此变量方法"""
def test_good_news_table_one(self):
"""验证GoodNews是否能正常打开并跳转; 1、打开首页; 2、点击GoodNews; 3、断言跳转的url是... | the_stack_v2_python_sparse | Manufacture/home/new_center_st.py | yushu1987/UI | train | 0 |
050355171af2ff18d5c1f598ae5913cb1222b63a | [
"self.count = 0\nself.alist = []\nself.wlist = []",
"ndata = len(data)\nif self.count == 0:\n self.nchannels = ndata\n self.count += 1\n self.alist.append(data)\n self.wlist.append(wt)\nelif self.count > 0 and ndata != self.nchannels:\n print('accum:load - WARNING - number of points in spectrum doe... | <|body_start_0|>
self.count = 0
self.alist = []
self.wlist = []
<|end_body_0|>
<|body_start_1|>
ndata = len(data)
if self.count == 0:
self.nchannels = ndata
self.count += 1
self.alist.append(data)
self.wlist.append(wt)
elif... | Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack. | Accum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Accum:
"""Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack."""
def __init__(self):
"""Constructor for Accum class. Args: none Returns: none""... | stack_v2_sparse_classes_75kplus_train_001617 | 37,646 | no_license | [
{
"docstring": "Constructor for Accum class. Args: none Returns: none",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Loads a set of data to be averaged. Args: data (array): data array wt (float): weighting of data (default is 1) Returns: none",
"name": "load",
... | 3 | stack_v2_sparse_classes_30k_train_037522 | Implement the Python class `Accum` described below.
Class description:
Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack.
Method signatures and docstrings:
- def __init__(self)... | Implement the Python class `Accum` described below.
Class description:
Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack.
Method signatures and docstrings:
- def __init__(self)... | 4064f6ca5d2807fbb99626838493d0f91cbd8748 | <|skeleton|>
class Accum:
"""Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack."""
def __init__(self):
"""Constructor for Accum class. Args: none Returns: none""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Accum:
"""Class to manage spectral averaging. All spectra to be averaged must be aligned in channel/index space. Weighted averages are possible using weight provided when spectrum is added to the stack."""
def __init__(self):
"""Constructor for Accum class. Args: none Returns: none"""
sel... | the_stack_v2_python_sparse | lmtslr/reduction/line_reduction.py | myunm82/SpectralLineReduction | train | 0 |
6c067716a141f10b1af4d89086fc442c1dcc42fb | [
"n = len(s)\nif n == 0:\n return True\nfor i in range(n + 1):\n if s[:i] in wordDict and self.wordBreak(s[i:], wordDict):\n return True\nreturn False",
"n = len(s)\ndp = [False for _ in range(n + 1)]\ndp[0] = True\nfor i in range(1, n + 1):\n for j in range(i):\n if dp[j] and s[j:i] in word... | <|body_start_0|>
n = len(s)
if n == 0:
return True
for i in range(n + 1):
if s[:i] in wordDict and self.wordBreak(s[i:], wordDict):
return True
return False
<|end_body_0|>
<|body_start_1|>
n = len(s)
dp = [False for _ in range(n + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded"""
<|body_0|>
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
def wordBreak0(se... | stack_v2_sparse_classes_75kplus_train_001618 | 1,355 | no_license | [
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: List[str] :rtype: bool",
"name": "wordBreak1",
"signature": "def wordBreak1(self,... | 3 | stack_v2_sparse_classes_30k_train_042666 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded
- def wordBreak1(self, s, wordDict): :type s: str :type wordDict: List[s... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded"""
<|body_0|>
def wordBreak1(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool"""
<|body_1|>
def wordBreak0(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: List[str] :rtype: bool Time limit exceeded"""
n = len(s)
if n == 0:
return True
for i in range(n + 1):
if s[:i] in wordDict and self.wordBreak(s[i:], wordDict):
r... | the_stack_v2_python_sparse | PythonCode/src/0139_Word_Break.py | oneyuan/CodeforFun | train | 0 | |
8a450d85aeffed048e0aa7d98f81a54a6306b41d | [
"if root is None:\n return\nif root.left is None and root.right is None:\n return root\nleft_node = self.convert_node(root.left)\nif left_node:\n while left_node.right:\n left_node = left_node.right\nroot.left = left_node\nif left_node:\n left_node.right = root\nright_node = self.convert_node(roo... | <|body_start_0|>
if root is None:
return
if root.left is None and root.right is None:
return root
left_node = self.convert_node(root.left)
if left_node:
while left_node.right:
left_node = left_node.right
root.left = left_node
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convert_node(self, root):
"""二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点"""
<|body_0|>
def print_tree(self, root):
"""打印二叉树"""
<|body_1|>
def print_link(self, root):
"""打印双向链表"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_001619 | 3,819 | no_license | [
{
"docstring": "二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点",
"name": "convert_node",
"signature": "def convert_node(self, root)"
},
{
"docstring": "打印二叉树",
"name": "print_tree",
"signature": "def print_tree(self, root)"
},
{
"docstring": "打印双向链表",
"name": "print_link",
"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert_node(self, root): 二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点
- def print_tree(self, root): 打印二叉树
- def print_link(self, root): 打印双向链表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert_node(self, root): 二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点
- def print_tree(self, root): 打印二叉树
- def print_link(self, root): 打印双向链表
<|skeleton|>
class Solution:
... | 9fdc4b1a2b59b7aed22ddfe92aade487b4c19b71 | <|skeleton|>
class Solution:
def convert_node(self, root):
"""二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点"""
<|body_0|>
def print_tree(self, root):
"""打印二叉树"""
<|body_1|>
def print_link(self, root):
"""打印双向链表"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def convert_node(self, root):
"""二叉搜索树转换双向链表 :param root: 根节点 :return: 链表头结点"""
if root is None:
return
if root.left is None and root.right is None:
return root
left_node = self.convert_node(root.left)
if left_node:
while le... | the_stack_v2_python_sparse | my_target_offer/36_convert_binary_search_tree.py | MemoryForSky/Data-Structures-and-Algorithms | train | 0 | |
e9e5400d716966ed8e8b16ce2082636816128a42 | [
"super().__init__(name, **kwargs)\nself.frequency = frequency\nself.ntraces = ntraces",
"x = 1 * (np.random.rand(40 * self.ntraces) - 0.5)\nfor ii in range(self.ntraces):\n x[40 * ii + 4:40 * ii + 10] += 4\n x[40 * ii + 15:40 * ii + 22] += -2 + (self.frequency.get() - 10000000.0) / 100.0\n pspin = np.exp... | <|body_start_0|>
super().__init__(name, **kwargs)
self.frequency = frequency
self.ntraces = ntraces
<|end_body_0|>
<|body_start_1|>
x = 1 * (np.random.rand(40 * self.ntraces) - 0.5)
for ii in range(self.ntraces):
x[40 * ii + 4:40 * ii + 10] += 4
x[40 * ii... | digitizer_class | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class digitizer_class:
def __init__(self, name, frequency, ntraces=12, **kwargs):
"""Dummy instrument Resonance frequency at 10 MHz"""
<|body_0|>
def measure(self):
"""Dummy measure function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__... | stack_v2_sparse_classes_75kplus_train_001620 | 5,770 | no_license | [
{
"docstring": "Dummy instrument Resonance frequency at 10 MHz",
"name": "__init__",
"signature": "def __init__(self, name, frequency, ntraces=12, **kwargs)"
},
{
"docstring": "Dummy measure function",
"name": "measure",
"signature": "def measure(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011515 | Implement the Python class `digitizer_class` described below.
Class description:
Implement the digitizer_class class.
Method signatures and docstrings:
- def __init__(self, name, frequency, ntraces=12, **kwargs): Dummy instrument Resonance frequency at 10 MHz
- def measure(self): Dummy measure function | Implement the Python class `digitizer_class` described below.
Class description:
Implement the digitizer_class class.
Method signatures and docstrings:
- def __init__(self, name, frequency, ntraces=12, **kwargs): Dummy instrument Resonance frequency at 10 MHz
- def measure(self): Dummy measure function
<|skeleton|>
... | 4dd19f66b85beb4120f1fdb7d61a54ae29bf050c | <|skeleton|>
class digitizer_class:
def __init__(self, name, frequency, ntraces=12, **kwargs):
"""Dummy instrument Resonance frequency at 10 MHz"""
<|body_0|>
def measure(self):
"""Dummy measure function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class digitizer_class:
def __init__(self, name, frequency, ntraces=12, **kwargs):
"""Dummy instrument Resonance frequency at 10 MHz"""
super().__init__(name, **kwargs)
self.frequency = frequency
self.ntraces = ntraces
def measure(self):
"""Dummy measure function"""
... | the_stack_v2_python_sparse | qcodes_xiao/example_custom_loop.py | xuexiao1992/quantum-demonstrater | train | 1 | |
a0971ffd8d1e21d0d617d2e678f1a8e632a5f186 | [
"if not obj.author:\n obj.author = request.user\nobj.save()",
"if self.declared_fieldsets:\n fieldsets = self.declared_fieldsets\nelse:\n form = self.get_form(request, obj)\n fieldsets = form.base_fields.keys() + list(self.get_readonly_fields(request, obj))\nfieldsets = super(PostTypeAdmin, self).get_... | <|body_start_0|>
if not obj.author:
obj.author = request.user
obj.save()
<|end_body_0|>
<|body_start_1|>
if self.declared_fieldsets:
fieldsets = self.declared_fieldsets
else:
form = self.get_form(request, obj)
fieldsets = form.base_fields.... | PostTypeAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostTypeAdmin:
def save_model(self, request, obj, form, change):
"""On new saves, sets the post author to the current user if it wasn't already defined."""
<|body_0|>
def get_fieldsets(self, request, obj=None):
"""Hook for specifying fieldsets for the add form, modif... | stack_v2_sparse_classes_75kplus_train_001621 | 4,278 | permissive | [
{
"docstring": "On new saves, sets the post author to the current user if it wasn't already defined.",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "Hook for specifying fieldsets for the add form, modified to only display fields inside f... | 6 | stack_v2_sparse_classes_30k_train_036601 | Implement the Python class `PostTypeAdmin` described below.
Class description:
Implement the PostTypeAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): On new saves, sets the post author to the current user if it wasn't already defined.
- def get_fieldsets(self, request... | Implement the Python class `PostTypeAdmin` described below.
Class description:
Implement the PostTypeAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): On new saves, sets the post author to the current user if it wasn't already defined.
- def get_fieldsets(self, request... | d5582c0e511d56998e19efa07db1e4badfec483b | <|skeleton|>
class PostTypeAdmin:
def save_model(self, request, obj, form, change):
"""On new saves, sets the post author to the current user if it wasn't already defined."""
<|body_0|>
def get_fieldsets(self, request, obj=None):
"""Hook for specifying fieldsets for the add form, modif... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostTypeAdmin:
def save_model(self, request, obj, form, change):
"""On new saves, sets the post author to the current user if it wasn't already defined."""
if not obj.author:
obj.author = request.user
obj.save()
def get_fieldsets(self, request, obj=None):
"""Ho... | the_stack_v2_python_sparse | tumblelog/admin.py | registerguard/django-tumblelog | train | 0 | |
24926314df6c9ffd33e981f728db4adc6c8db6a1 | [
"url = url\nresponse = requests.get(url)\ntry:\n unziped_srt = gzip.GzipFile(fileobj=BytesIO(response.content))\n return unziped_srt.read().decode(encoding)\nexcept OSError:\n return response.content.decode(encoding)",
"sorted_subtitles = []\ntry:\n url = self._search_url.format(imdb_id=imdb_id, langu... | <|body_start_0|>
url = url
response = requests.get(url)
try:
unziped_srt = gzip.GzipFile(fileobj=BytesIO(response.content))
return unziped_srt.read().decode(encoding)
except OSError:
return response.content.decode(encoding)
<|end_body_0|>
<|body_start... | OpenSubtitles | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenSubtitles:
def _download_content(url: str, encoding='utf-8') -> str:
"""Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/...' encoding (str, optional): Defaults to "utf-8". Returns: StringIO: with the subtitle"""
<|bo... | stack_v2_sparse_classes_75kplus_train_001622 | 3,523 | permissive | [
{
"docstring": "Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/...' encoding (str, optional): Defaults to \"utf-8\". Returns: StringIO: with the subtitle",
"name": "_download_content",
"signature": "def _download_content(url: str, encoding='ut... | 3 | null | Implement the Python class `OpenSubtitles` described below.
Class description:
Implement the OpenSubtitles class.
Method signatures and docstrings:
- def _download_content(url: str, encoding='utf-8') -> str: Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/..... | Implement the Python class `OpenSubtitles` described below.
Class description:
Implement the OpenSubtitles class.
Method signatures and docstrings:
- def _download_content(url: str, encoding='utf-8') -> str: Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/..... | cea93e560b3f7924997b359e982cc66f2ac373a9 | <|skeleton|>
class OpenSubtitles:
def _download_content(url: str, encoding='utf-8') -> str:
"""Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/...' encoding (str, optional): Defaults to "utf-8". Returns: StringIO: with the subtitle"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenSubtitles:
def _download_content(url: str, encoding='utf-8') -> str:
"""Download, extract and read the subtitle. Args: url (str): 'https://dl.opensubtitles.org/en/download/src-api/...' encoding (str, optional): Defaults to "utf-8". Returns: StringIO: with the subtitle"""
url = url
... | the_stack_v2_python_sparse | mwc/core/subtitles/opensubtitles.py | Bgeninatti/MovieWordCloud | train | 3 | |
7cc296ad15e082c0c1620cdcf92e8ae3f2d4c54c | [
"if self.onOffset(date):\n return date\nelse:\n return date + QuarterEnd(month=self.month)",
"if self.onOffset(date):\n return date\nelse:\n return date - QuarterEnd(month=self.month)"
] | <|body_start_0|>
if self.onOffset(date):
return date
else:
return date + QuarterEnd(month=self.month)
<|end_body_0|>
<|body_start_1|>
if self.onOffset(date):
return date
else:
return date - QuarterEnd(month=self.month)
<|end_body_1|>
| QuarterEnd | [
"BSD-3-Clause",
"CC-BY-4.0",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuarterEnd:
def rollforward(self, date):
"""Roll date forward to nearest end of quarter"""
<|body_0|>
def rollback(self, date):
"""Roll date backward to nearest end of quarter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.onOffset(date):
... | stack_v2_sparse_classes_75kplus_train_001623 | 47,274 | permissive | [
{
"docstring": "Roll date forward to nearest end of quarter",
"name": "rollforward",
"signature": "def rollforward(self, date)"
},
{
"docstring": "Roll date backward to nearest end of quarter",
"name": "rollback",
"signature": "def rollback(self, date)"
}
] | 2 | stack_v2_sparse_classes_30k_train_041857 | Implement the Python class `QuarterEnd` described below.
Class description:
Implement the QuarterEnd class.
Method signatures and docstrings:
- def rollforward(self, date): Roll date forward to nearest end of quarter
- def rollback(self, date): Roll date backward to nearest end of quarter | Implement the Python class `QuarterEnd` described below.
Class description:
Implement the QuarterEnd class.
Method signatures and docstrings:
- def rollforward(self, date): Roll date forward to nearest end of quarter
- def rollback(self, date): Roll date backward to nearest end of quarter
<|skeleton|>
class QuarterE... | dd09bddc62d701721565bbed3731e9586ea306d0 | <|skeleton|>
class QuarterEnd:
def rollforward(self, date):
"""Roll date forward to nearest end of quarter"""
<|body_0|>
def rollback(self, date):
"""Roll date backward to nearest end of quarter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuarterEnd:
def rollforward(self, date):
"""Roll date forward to nearest end of quarter"""
if self.onOffset(date):
return date
else:
return date + QuarterEnd(month=self.month)
def rollback(self, date):
"""Roll date backward to nearest end of quarter... | the_stack_v2_python_sparse | xarray/coding/cftime_offsets.py | pydata/xarray | train | 2,916 | |
fdda61069f20db9251ada9d4cef33f36a90ca8a5 | [
"super(WordSegmentation, self).__init__()\n'变量说明\\n\\t\\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\\n\\t\\tself.stop_tokens: 分词停止符号\\n\\t\\tself.stop_words; 停止词\\n\\t\\t'\nself.default_speech_tag_filter = ['an', 'i', 'j', 'l', 'n', 'nr', 'nrfg', 'ns', 'nt', 'nz', 't', 'v', 'vd', 'vn', 'eng']\nself.stop_t... | <|body_start_0|>
super(WordSegmentation, self).__init__()
'变量说明\n\t\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\n\t\tself.stop_tokens: 分词停止符号\n\t\tself.stop_words; 停止词\n\t\t'
self.default_speech_tag_filter = ['an', 'i', 'j', 'l', 'n', 'nr', 'nrfg', 'ns', 'nt', 'nz', 't', 'v', 'vd', 'vn... | 分词 | WordSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
<|body_0|>
def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False):
"""函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否... | stack_v2_sparse_classes_75kplus_train_001624 | 6,042 | no_license | [
{
"docstring": "函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径",
"name": "__init__",
"signature": "def __init__(self, stop_words_file=None)"
},
{
"docstring": "函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否将英语单词转化为小写 with_stop_words: 若为True,则用停止词集合来过滤(去掉停止词),否则不过滤 speech_tag_filter: 若为True,则使用默认的self.de... | 3 | stack_v2_sparse_classes_30k_train_047076 | Implement the Python class `WordSegmentation` described below.
Class description:
分词
Method signatures and docstrings:
- def __init__(self, stop_words_file=None): 函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径
- def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False): 函数功能:对text进行分词处理 text: 待... | Implement the Python class `WordSegmentation` described below.
Class description:
分词
Method signatures and docstrings:
- def __init__(self, stop_words_file=None): 函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径
- def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False): 函数功能:对text进行分词处理 text: 待... | 9855d6e69598f9cbf1652c3bcea27133a755c03c | <|skeleton|>
class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
<|body_0|>
def segment_text(self, text, lower=True, with_stop_words=True, speech_tag_filter=False):
"""函数功能:对text进行分词处理 text: 待处理文本 lower = True: 是否... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordSegmentation:
"""分词"""
def __init__(self, stop_words_file=None):
"""函数功能:默认构造函数 stop_words_file: 保存停止词的文件路径"""
super(WordSegmentation, self).__init__()
'变量说明\n\t\tself.default_speech_tag_filter: 默认词性标注过滤器(只保留相应词性)\n\t\tself.stop_tokens: 分词停止符号\n\t\tself.stop_words; 停止词\n\t\t... | the_stack_v2_python_sparse | TextRank/Segmentation.py | xc15071347094/ASExtractor | train | 0 |
ba23e8bbb907f7950a0c4c88af6834e4afba8f36 | [
"super().__init__(serializer, bearer_token, tweet_fields, user_fields, media_fields, poll_fields, place_fields, *args, **kwargs)\nself.deleteAllFilters(self.getFilters())\nself.setFilters(filters)",
"response = requests.get('https://api.twitter.com/2/tweets/search/stream/rules', headers=self.headers)\nif response... | <|body_start_0|>
super().__init__(serializer, bearer_token, tweet_fields, user_fields, media_fields, poll_fields, place_fields, *args, **kwargs)
self.deleteAllFilters(self.getFilters())
self.setFilters(filters)
<|end_body_0|>
<|body_start_1|>
response = requests.get('https://api.twitter... | Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added | TwitterFilteredIngest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterFilteredIngest:
"""Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added"""
def __init__(self, serializer: EmptyStringSeria... | stack_v2_sparse_classes_75kplus_train_001625 | 4,144 | permissive | [
{
"docstring": "Initializes the TwitterFilteredIngest class with the `bearer_token` for authentication and query fields to populate the received tweet object Args: serializer (EmptyStringSerializer): An empty serializer for convention. filter (List[str]): List of filters to apply during streaming. bearer_token ... | 4 | stack_v2_sparse_classes_30k_train_045420 | Implement the Python class `TwitterFilteredIngest` described below.
Class description:
Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added
Method signatur... | Implement the Python class `TwitterFilteredIngest` described below.
Class description:
Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added
Method signatur... | 9e7c5717ea2afdb5f1afef9f9b632b5a765fce4e | <|skeleton|>
class TwitterFilteredIngest:
"""Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added"""
def __init__(self, serializer: EmptyStringSeria... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TwitterFilteredIngest:
"""Class for streaming from Twitter using the v2 API endpoints. Attributes: base_url (str): The endpoint for the streaming or filter request. Raises: Exception: Raised when filters can't be retrieved, deleted, or added"""
def __init__(self, serializer: EmptyStringSerializer, bearer... | the_stack_v2_python_sparse | python/edna/src/edna/ingest/streaming/TwitterFilteredIngest.py | prernaagarwal/cs6235Project | train | 0 |
10319e50e61be7f2c99a02e0c4c9945d7015cd10 | [
"def rserialize(root, string):\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return string\nreturn rserialize(root, '')",
"def rdeserialize(l):\n if l[0] ==... | <|body_start_0|>
def rserialize(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = rserialize(root.left, string)
string = rserialize(root.right, string)
return string
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_75kplus_train_001626 | 2,115 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_053735 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | f345b28530fb7c188e2db12c1e47e850a97aea52 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def rserialize(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = rser... | the_stack_v2_python_sparse | Serialize and Deserialize Binary Tree.py | piyush09/LeetCode | train | 0 | |
35b393ed44d3d82c6785f03beb2b1ae969e9d63b | [
"currency_id = False\naccount_move = self.account_move_id\nif account_move:\n if account_move.currency_id:\n currency_id = account_move.currency_id\n elif account_move.account_id.currency_id:\n currency_id = account_move.account_id.currency_id.id\n else:\n currency_id = account_move.co... | <|body_start_0|>
currency_id = False
account_move = self.account_move_id
if account_move:
if account_move.currency_id:
currency_id = account_move.currency_id
elif account_move.account_id.currency_id:
currency_id = account_move.account_id.cu... | Credit lines to reconcile payments from an invoice | invoice_reconciliation_credit_line | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class invoice_reconciliation_credit_line:
"""Credit lines to reconcile payments from an invoice"""
def _compute_currency_id(self):
"""On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle de la société de l'écriture comptable"""
<|body_... | stack_v2_sparse_classes_75kplus_train_001627 | 36,478 | no_license | [
{
"docstring": "On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle de la société de l'écriture comptable",
"name": "_compute_currency_id",
"signature": "def _compute_currency_id(self)"
},
{
"docstring": "Au changement du montant à réconcilier, on ... | 2 | stack_v2_sparse_classes_30k_train_047829 | Implement the Python class `invoice_reconciliation_credit_line` described below.
Class description:
Credit lines to reconcile payments from an invoice
Method signatures and docstrings:
- def _compute_currency_id(self): On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle... | Implement the Python class `invoice_reconciliation_credit_line` described below.
Class description:
Credit lines to reconcile payments from an invoice
Method signatures and docstrings:
- def _compute_currency_id(self): On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle... | eb394e1f79ba1995da2dcd81adfdd511c22caff9 | <|skeleton|>
class invoice_reconciliation_credit_line:
"""Credit lines to reconcile payments from an invoice"""
def _compute_currency_id(self):
"""On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle de la société de l'écriture comptable"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class invoice_reconciliation_credit_line:
"""Credit lines to reconcile payments from an invoice"""
def _compute_currency_id(self):
"""On récupère la devise de l'écriture comptable, ou celle du compte de l'écriture comptable, ou celle de la société de l'écriture comptable"""
currency_id = False
... | the_stack_v2_python_sparse | OpenPROD/openprod-addons/account_openprod/wizard/invoice_reconciliation.py | kazacube-mziouadi/ceci | train | 0 |
631965d710e23d35be36ba10954f9e15f61d2396 | [
"conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels * upscale_factor ** 2, kernel_size=1, padding=0)\nself.initialize_conv(conv, in_channels, out_channels, upscale_factor)\nlayers = [conv, activation(), normalization(num_features=out_channels * upscale_factor ** 2), nn.PixelShuffle(upscale_factor)]... | <|body_start_0|>
conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels * upscale_factor ** 2, kernel_size=1, padding=0)
self.initialize_conv(conv, in_channels, out_channels, upscale_factor)
layers = [conv, activation(), normalization(num_features=out_channels * upscale_factor ** 2)... | Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end) | PixelShuffleConvolutionLayer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixelShuffleConvolutionLayer:
"""Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end)"""
def __init__(self, in_channels: int, out_channels: int, upscale_factor: int, ac... | stack_v2_sparse_classes_75kplus_train_001628 | 8,139 | permissive | [
{
"docstring": ":param in_channels: input channels :param out_channels: output channels :param upscale_factor: factor to increase spatial resolution by :param activation: activation function :param normalization: normalization function :param: whether to blur at the end to remove checkerboard artifact",
"na... | 2 | stack_v2_sparse_classes_30k_train_053905 | Implement the Python class `PixelShuffleConvolutionLayer` described below.
Class description:
Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end)
Method signatures and docstrings:
- def __init_... | Implement the Python class `PixelShuffleConvolutionLayer` described below.
Class description:
Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end)
Method signatures and docstrings:
- def __init_... | b998d61800311d788bf3c4c5f517f1fd6d9c2e66 | <|skeleton|>
class PixelShuffleConvolutionLayer:
"""Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end)"""
def __init__(self, in_channels: int, out_channels: int, upscale_factor: int, ac... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PixelShuffleConvolutionLayer:
"""Upsample the image using normal convolution follow by pixel shuffling https://arxiv.org/pdf/1609.05158.pdf https://arxiv.org/pdf/1806.02658.pdf (additional blurring at the end)"""
def __init__(self, in_channels: int, out_channels: int, upscale_factor: int, activation=nn.R... | the_stack_v2_python_sparse | nntoolbox/vision/components/layers.py | sskram/nn-toolbox | train | 0 |
8e73ac3a95e3eeefa018e24ec9c60ecf2f89d5f4 | [
"closest = np.searchsorted(model_wave, data_wave)\nidx = np.clip(closest, 1, len(model_wave) - 1)\nleft = model_wave[idx - 1]\nright = model_wave[idx]\nidx -= data_wave - left < right - data_wave\nclosest_model_flux = model_flux[idx]\nreturn closest_model_flux",
"_stat = np.nansum(np.square(_data - _model) / _mod... | <|body_start_0|>
closest = np.searchsorted(model_wave, data_wave)
idx = np.clip(closest, 1, len(model_wave) - 1)
left = model_wave[idx - 1]
right = model_wave[idx]
idx -= data_wave - left < right - data_wave
closest_model_flux = model_flux[idx]
return closest_mode... | Fitting tools for least square fit. | fit | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fit:
"""Fitting tools for least square fit."""
def find_closest(data_wave, model_wave, model_flux):
"""Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns. model_wave : 1-D array wavelengths of model in microns. ... | stack_v2_sparse_classes_75kplus_train_001629 | 3,405 | permissive | [
{
"docstring": "Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns. model_wave : 1-D array wavelengths of model in microns. model_flux : 1-D array scaled flux of model in W M-2 Returns ------- closest_model_flux: array Subset of model flux... | 3 | null | Implement the Python class `fit` described below.
Class description:
Fitting tools for least square fit.
Method signatures and docstrings:
- def find_closest(data_wave, model_wave, model_flux): Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns.... | Implement the Python class `fit` described below.
Class description:
Fitting tools for least square fit.
Method signatures and docstrings:
- def find_closest(data_wave, model_wave, model_flux): Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns.... | 93a36683a8ec459e15e214875b9e8e3c03fd77a6 | <|skeleton|>
class fit:
"""Fitting tools for least square fit."""
def find_closest(data_wave, model_wave, model_flux):
"""Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns. model_wave : 1-D array wavelengths of model in microns. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class fit:
"""Fitting tools for least square fit."""
def find_closest(data_wave, model_wave, model_flux):
"""Find model fluxes closest in wavelength to data. Parameters ---------- data_wave : 1-D array wavelengths of data in microns. model_wave : 1-D array wavelengths of model in microns. model_flux : ... | the_stack_v2_python_sparse | desk/fitting/fitting_tools.py | s-goldman/Dusty-Evolved-Star-Kit | train | 17 |
b4ebc4a696933c46469b6fb1839b82262380a48f | [
"self.menu_ext = Menu()\nself.menu = None\nself.breadcrumbs = Breadcrumbs()\nself.weblinks = self.init_weblinks_dictionary()\nif app:\n self.init_app(app, **kwargs)\n self.setup_app(app)",
"self.init_config(app.config)\nself.menu_ext.init_app(app)\nself.menu = app.extensions['menu']\nself.breadcrumbs.init_a... | <|body_start_0|>
self.menu_ext = Menu()
self.menu = None
self.breadcrumbs = Breadcrumbs()
self.weblinks = self.init_weblinks_dictionary()
if app:
self.init_app(app, **kwargs)
self.setup_app(app)
<|end_body_0|>
<|body_start_1|>
self.init_config(app... | Invenio theme extension. | INSPIRETheme | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class INSPIRETheme:
"""Invenio theme extension."""
def __init__(self, app=None, **kwargs):
"""Extension initialization."""
<|body_0|>
def init_app(self, app, assets=None, **kwargs):
"""Initialize application object."""
<|body_1|>
def init_config(self, conf... | stack_v2_sparse_classes_75kplus_train_001630 | 3,793 | no_license | [
{
"docstring": "Extension initialization.",
"name": "__init__",
"signature": "def __init__(self, app=None, **kwargs)"
},
{
"docstring": "Initialize application object.",
"name": "init_app",
"signature": "def init_app(self, app, assets=None, **kwargs)"
},
{
"docstring": "Initializ... | 5 | stack_v2_sparse_classes_30k_train_041412 | Implement the Python class `INSPIRETheme` described below.
Class description:
Invenio theme extension.
Method signatures and docstrings:
- def __init__(self, app=None, **kwargs): Extension initialization.
- def init_app(self, app, assets=None, **kwargs): Initialize application object.
- def init_config(self, config):... | Implement the Python class `INSPIRETheme` described below.
Class description:
Invenio theme extension.
Method signatures and docstrings:
- def __init__(self, app=None, **kwargs): Extension initialization.
- def init_app(self, app, assets=None, **kwargs): Initialize application object.
- def init_config(self, config):... | 90032ba4825c6c4dda78c9c2b1d3edf18692b9dc | <|skeleton|>
class INSPIRETheme:
"""Invenio theme extension."""
def __init__(self, app=None, **kwargs):
"""Extension initialization."""
<|body_0|>
def init_app(self, app, assets=None, **kwargs):
"""Initialize application object."""
<|body_1|>
def init_config(self, conf... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class INSPIRETheme:
"""Invenio theme extension."""
def __init__(self, app=None, **kwargs):
"""Extension initialization."""
self.menu_ext = Menu()
self.menu = None
self.breadcrumbs = Breadcrumbs()
self.weblinks = self.init_weblinks_dictionary()
if app:
... | the_stack_v2_python_sparse | inspirehep/modules/theme/ext.py | spirosdelviniotis/inspire-next | train | 1 |
2b80b6935fcbad4f42c4848820192fe3ce44e7c7 | [
"self.cache = {}\nself.queue = deque([])\nself.size = 0\nself.capacity = capacity",
"if key not in self.cache:\n return -1\nself.queue.remove(key)\nself.queue.append(key)\nreturn self.cache.get(key)",
"if key not in self.cache:\n self.cache[key] = value\n self.queue.append(key)\n self.size += 1\n ... | <|body_start_0|>
self.cache = {}
self.queue = deque([])
self.size = 0
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.cache:
return -1
self.queue.remove(key)
self.queue.append(key)
return self.cache.get(key)
<|end_b... | 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_75kplus_train_001631 | 2,285 | 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 | stack_v2_sparse_classes_30k_train_052335 | 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... | cf4235170db3629b65790fd0855a8a72ac5886f7 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cache = {}
self.queue = deque([])
self.size = 0
self.capacity = capacity
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.cache:
return -1
... | the_stack_v2_python_sparse | lru_cache.py | buxizhizhoum/leetcode | train | 1 | |
1be1735112a3fcd166c986e007ac6ba66be0ffe3 | [
"title = 'Commission'\ndate_str = ''\nyear_str = ''\nfor item in response.css('.ms-rtestate-field > *'):\n if item.root.tag == 'h2':\n title = item.xpath('./text()').extract_first()\n continue\n if item.root.tag == 'h3':\n year_str = item.xpath('./text()').extract_first()\n continu... | <|body_start_0|>
title = 'Commission'
date_str = ''
year_str = ''
for item in response.css('.ms-rtestate-field > *'):
if item.root.tag == 'h2':
title = item.xpath('./text()').extract_first()
continue
if item.root.tag == 'h3':
... | IlEnvironmentalJusticeSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IlEnvironmentalJusticeSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_classification(self, title):
"""Parse or generate clas... | stack_v2_sparse_classes_75kplus_train_001632 | 4,301 | permissive | [
{
"docstring": "`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Parse or generate classification from allowed options.",
"name": "_pa... | 4 | stack_v2_sparse_classes_30k_train_000700 | Implement the Python class `IlEnvironmentalJusticeSpider` described below.
Class description:
Implement the IlEnvironmentalJusticeSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your... | Implement the Python class `IlEnvironmentalJusticeSpider` described below.
Class description:
Implement the IlEnvironmentalJusticeSpider class.
Method signatures and docstrings:
- def parse(self, response): `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your... | 611fce6a2705446e25a2fc33e32090a571eb35d1 | <|skeleton|>
class IlEnvironmentalJusticeSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
<|body_0|>
def _parse_classification(self, title):
"""Parse or generate clas... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IlEnvironmentalJusticeSpider:
def parse(self, response):
"""`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs."""
title = 'Commission'
date_str = ''
year_str = ''
for item in response.css('.ms-... | the_stack_v2_python_sparse | city_scrapers/spiders/il_environmental_justice.py | City-Bureau/city-scrapers | train | 308 | |
10b90d3a609ebc9e366b286bc7946afadb8b97c0 | [
"if member_id < 1 or not items:\n return False\nfor item in items:\n Cart.query.filter_by(product_id=item['id'], member_id=member_id).delete()\ndb.session.commit()\nreturn True",
"if member_id < 1 or product_id < 1 or number < 1:\n return False\ncart_info = Cart.query.filter_by(product_id=product_id, mem... | <|body_start_0|>
if member_id < 1 or not items:
return False
for item in items:
Cart.query.filter_by(product_id=item['id'], member_id=member_id).delete()
db.session.commit()
return True
<|end_body_0|>
<|body_start_1|>
if member_id < 1 or product_id < 1 or... | CartService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartService:
def deleteItem(member_id=0, items=None):
""":param member_id: :param items: :return: 会员是否存在"""
<|body_0|>
def setItems(member_id=0, product_id=0, number=0):
""":param member_id: :param product_id: :param number: :return:向购物车添加/更新数量成功与否"""
<|body_... | stack_v2_sparse_classes_75kplus_train_001633 | 2,346 | no_license | [
{
"docstring": ":param member_id: :param items: :return: 会员是否存在",
"name": "deleteItem",
"signature": "def deleteItem(member_id=0, items=None)"
},
{
"docstring": ":param member_id: :param product_id: :param number: :return:向购物车添加/更新数量成功与否",
"name": "setItems",
"signature": "def setItems(m... | 3 | stack_v2_sparse_classes_30k_train_008097 | Implement the Python class `CartService` described below.
Class description:
Implement the CartService class.
Method signatures and docstrings:
- def deleteItem(member_id=0, items=None): :param member_id: :param items: :return: 会员是否存在
- def setItems(member_id=0, product_id=0, number=0): :param member_id: :param produ... | Implement the Python class `CartService` described below.
Class description:
Implement the CartService class.
Method signatures and docstrings:
- def deleteItem(member_id=0, items=None): :param member_id: :param items: :return: 会员是否存在
- def setItems(member_id=0, product_id=0, number=0): :param member_id: :param produ... | 16e7110474fa24f1c05e16d13b0bca55e57c58e4 | <|skeleton|>
class CartService:
def deleteItem(member_id=0, items=None):
""":param member_id: :param items: :return: 会员是否存在"""
<|body_0|>
def setItems(member_id=0, product_id=0, number=0):
""":param member_id: :param product_id: :param number: :return:向购物车添加/更新数量成功与否"""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CartService:
def deleteItem(member_id=0, items=None):
""":param member_id: :param items: :return: 会员是否存在"""
if member_id < 1 or not items:
return False
for item in items:
Cart.query.filter_by(product_id=item['id'], member_id=member_id).delete()
db.sessio... | the_stack_v2_python_sparse | backend/ciwei/common/libs/mall/CartService.py | 100101001/HedgehogHunt | train | 1 | |
b714c3247b933c2fa89baa6f1fd760251ed67d61 | [
"self.Cache = {}\nself.capacity = capacity\nself.orderlist = []",
"if self.Cache.has_key(str(key)):\n self.orderlist.remove(key)\n self.orderlist.append(key)\n return self.Cache[str(key)]\nelse:\n return -1",
"if self.Cache.has_key(str(key)):\n self.Cache[str(key)] = value\n self.orderlist.rem... | <|body_start_0|>
self.Cache = {}
self.capacity = capacity
self.orderlist = []
<|end_body_0|>
<|body_start_1|>
if self.Cache.has_key(str(key)):
self.orderlist.remove(key)
self.orderlist.append(key)
return self.Cache[str(key)]
else:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_001634 | 1,228 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_019071 | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | 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): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | cd0341341a0216ac39850727804411e4cf5e4a67 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.Cache = {}
self.capacity = capacity
self.orderlist = []
def get(self, key):
""":rtype: int"""
if self.Cache.has_key(str(key)):
self.orderlist.remove(key)
self.ord... | the_stack_v2_python_sparse | 146. LRU Cache.py | cclain/LeetCode-Problem-Solution | train | 0 | |
a970ea305c8058bd4e71175c46904b104992c4f4 | [
"self.find(By.ID, 'username').send_keys(username)\nself.find(By.ID, 'memberAdd_acctid').send_keys(account)\nself.find(By.ID, 'memberAdd_phone').send_keys(phonenum)\nself.find(By.CSS_SELECTOR, '.js_btn_save').click()\nreturn True",
"self.wait((By.CSS_SELECTOR, '.member_colRight_memberTable_td:nth-child(2)'))\neles... | <|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_SELECTOR, '.js_btn_save').click()
return True
<|end_body_0|>
<|body_start_1|>
... | AddMemberPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有联系人姓名"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.find(By.ID, 'username').send_keys(username)
self.f... | stack_v2_sparse_classes_75kplus_train_001635 | 1,403 | no_license | [
{
"docstring": "添加联系人,详细信息 :return:",
"name": "add_member",
"signature": "def add_member(self, username, account, phonenum)"
},
{
"docstring": "获取所有联系人姓名",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_050736 | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有联系人姓名 | Implement the Python class `AddMemberPage` described below.
Class description:
Implement the AddMemberPage class.
Method signatures and docstrings:
- def add_member(self, username, account, phonenum): 添加联系人,详细信息 :return:
- def get_member(self): 获取所有联系人姓名
<|skeleton|>
class AddMemberPage:
def add_member(self, us... | bf5a94321c4f2d28a0de2413760e6d517bfba0b8 | <|skeleton|>
class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
<|body_0|>
def get_member(self):
"""获取所有联系人姓名"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddMemberPage:
def add_member(self, username, account, phonenum):
"""添加联系人,详细信息 :return:"""
self.find(By.ID, 'username').send_keys(username)
self.find(By.ID, 'memberAdd_acctid').send_keys(account)
self.find(By.ID, 'memberAdd_phone').send_keys(phonenum)
self.find(By.CSS_... | the_stack_v2_python_sparse | pratice_lesson5_selenium/po_wework/PO_add_contactor/page/add_member_page.py | testdemo11/test2_pratice | train | 1 | |
837dd953513047a9bde9f82172f8c4e6d4db4e8c | [
"super().__init__(name, nA, alpha, gamma, epsilon_init, epsilon_decay, epsilon_limit, sarsa)\nmover = MoveAgent()\nself.pickup = PickupAgent(mover)\nself.deliver = DeliverAgent(mover)",
"state = env.reset()\nsamp_reward = 0\ncounter = 0\nwhile True:\n action = self.select_action(state)\n action = counter\n ... | <|body_start_0|>
super().__init__(name, nA, alpha, gamma, epsilon_init, epsilon_decay, epsilon_limit, sarsa)
mover = MoveAgent()
self.pickup = PickupAgent(mover)
self.deliver = DeliverAgent(mover)
<|end_body_0|>
<|body_start_1|>
state = env.reset()
samp_reward = 0
... | RootAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootAgent:
def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED'):
"""Initialize agent. Params ====== - nA: number of actions available to the agent"""
<|body_0|>
def play_episode(self, env):
... | stack_v2_sparse_classes_75kplus_train_001636 | 2,198 | no_license | [
{
"docstring": "Initialize agent. Params ====== - nA: number of actions available to the agent",
"name": "__init__",
"signature": "def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED')"
},
{
"docstring": "apparentl... | 3 | null | Implement the Python class `RootAgent` described below.
Class description:
Implement the RootAgent class.
Method signatures and docstrings:
- def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED'): Initialize agent. Params ====== - nA: n... | Implement the Python class `RootAgent` described below.
Class description:
Implement the RootAgent class.
Method signatures and docstrings:
- def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED'): Initialize agent. Params ====== - nA: n... | 8c9868aec118e86c854735d85e990123d256a7f2 | <|skeleton|>
class RootAgent:
def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED'):
"""Initialize agent. Params ====== - nA: number of actions available to the agent"""
<|body_0|>
def play_episode(self, env):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RootAgent:
def __init__(self, name='Root', nA=2, alpha=0.5, gamma=1, epsilon_init=0.5, epsilon_decay=0.999, epsilon_limit=0.001, sarsa='EXPECTED'):
"""Initialize agent. Params ====== - nA: number of actions available to the agent"""
super().__init__(name, nA, alpha, gamma, epsilon_init, epsilo... | the_stack_v2_python_sparse | DRL-course/lab-taxi/agents/root_agent.py | Zartris/DRL-project | train | 3 | |
65df2dfd2ceab372b1d9bac26a6cd877f02734d9 | [
"mock_result = mocker.patch('OracleIAM.CommandResults')\nargs = {'scim': '{\"displayName\": \"The group name\"}'}\nwith requests_mock.Mocker() as m:\n m.post('https://test.com/oauth2/v1/token', json={})\n m.post('https://test.com/admin/v1/Groups', status_code=201, json=APP_GROUP_OUTPUT)\n client = mock_cli... | <|body_start_0|>
mock_result = mocker.patch('OracleIAM.CommandResults')
args = {'scim': '{"displayName": "The group name"}'}
with requests_mock.Mocker() as m:
m.post('https://test.com/oauth2/v1/token', json={})
m.post('https://test.com/admin/v1/Groups', status_code=201, j... | TestCreateGroupCommand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCreateGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application When: - Calling the main function with 'iam-create-group' command Then: - Ensure the resulted 'CommandResults'... | stack_v2_sparse_classes_75kplus_train_001637 | 25,823 | permissive | [
{
"docstring": "Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application When: - Calling the main function with 'iam-create-group' command Then: - Ensure the resulted 'CommandResults' object holds information about the created group.",
"name": "t... | 3 | stack_v2_sparse_classes_30k_train_032939 | Implement the Python class `TestCreateGroupCommand` described below.
Class description:
Implement the TestCreateGroupCommand class.
Method signatures and docstrings:
- def test_success(self, mocker): Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application... | Implement the Python class `TestCreateGroupCommand` described below.
Class description:
Implement the TestCreateGroupCommand class.
Method signatures and docstrings:
- def test_success(self, mocker): Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestCreateGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application When: - Calling the main function with 'iam-create-group' command Then: - Ensure the resulted 'CommandResults'... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCreateGroupCommand:
def test_success(self, mocker):
"""Given: - An app client object - A scim argument that contains a displayName of a non-existing group in the application When: - Calling the main function with 'iam-create-group' command Then: - Ensure the resulted 'CommandResults' object holds ... | the_stack_v2_python_sparse | Packs/Oracle_IAM/Integrations/OracleIAM/OracleIAM_test.py | demisto/content | train | 1,023 | |
5a34054f3dd8093277b9b9da4fa7e2a94c2670ab | [
"props = [prop for prop in dir(self) if len(re.split(f'_{self.__class__.__name__}__(\\\\w+)', prop)) == 3]\nresult = ''\nfor prop in props:\n prop_name = re.split(f'_{self.__class__.__name__}__(\\\\w+)', prop)[1]\n prop_type = type(eval(f'self.{prop}'))\n prop_value = eval(f'self.{prop}')\n if prop_type... | <|body_start_0|>
props = [prop for prop in dir(self) if len(re.split(f'_{self.__class__.__name__}__(\\w+)', prop)) == 3]
result = ''
for prop in props:
prop_name = re.split(f'_{self.__class__.__name__}__(\\w+)', prop)[1]
prop_type = type(eval(f'self.{prop}'))
... | class: Serializador Serializa y deserializa a string. | Serializador | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Serializador:
"""class: Serializador Serializa y deserializa a string."""
def serializar(self):
"""Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propiedades separadas por `;`, el nombre de la propiedad y el val... | stack_v2_sparse_classes_75kplus_train_001638 | 2,560 | permissive | [
{
"docstring": "Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propiedades separadas por `;`, el nombre de la propiedad y el valor de la dicha van separados por `:` y los elementos de los valores de las listas separadas por `,`.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_009901 | Implement the Python class `Serializador` described below.
Class description:
class: Serializador Serializa y deserializa a string.
Method signatures and docstrings:
- def serializar(self): Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propieda... | Implement the Python class `Serializador` described below.
Class description:
class: Serializador Serializa y deserializa a string.
Method signatures and docstrings:
- def serializar(self): Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propieda... | c9179af16278ed8c98417ffb723e7ba67645aeef | <|skeleton|>
class Serializador:
"""class: Serializador Serializa y deserializa a string."""
def serializar(self):
"""Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propiedades separadas por `;`, el nombre de la propiedad y el val... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Serializador:
"""class: Serializador Serializa y deserializa a string."""
def serializar(self):
"""Serializa el objecto i.e.: `prop1:value1;prop2:val2,val3;prop3:val4` :return: Una string con el objeto serializado. Las propiedades separadas por `;`, el nombre de la propiedad y el valor de la dich... | the_stack_v2_python_sparse | Plataforma/Utils.py | raulfernandez/curso-python | train | 0 |
2bae4dceb5c36e62c7708b93349b2df6f081d0bf | [
"self.img_bytes = img_bytes\nself.img_ext = img_ext\nself.file_name = None\nself.img_size = None\nself.repository = AWSS3(self.env.THUMBNAIL_BUCKET_NAME)\nsuper(SaveImage, self).__init__(prefix='SI', phase_name='Save image', invocation_id=invocation_id)",
"self.file_name = f'{self.invocation_id}-{self.env.SMALL_T... | <|body_start_0|>
self.img_bytes = img_bytes
self.img_ext = img_ext
self.file_name = None
self.img_size = None
self.repository = AWSS3(self.env.THUMBNAIL_BUCKET_NAME)
super(SaveImage, self).__init__(prefix='SI', phase_name='Save image', invocation_id=invocation_id)
<|end_b... | Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response. | SaveImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaveImage:
"""Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, img_bytes: bytes, img_ext: str, invocation_id: str):
"""Constructor of the save image object, stores provided an... | stack_v2_sparse_classes_75kplus_train_001639 | 2,728 | no_license | [
{
"docstring": "Constructor of the save image object, stores provided and locally generated data, runs main object procedure. :param img_bytes: pre-processed image in bytes form. :param img_ext: string containing image extension (type). :param invocation_id: string containing id of current cloud function invoca... | 3 | stack_v2_sparse_classes_30k_train_043465 | Implement the Python class `SaveImage` described below.
Class description:
Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response.
Method signatures and docstrings:
- def __init__(self, img_bytes: bytes, img_ext: str, invocation_id: str):... | Implement the Python class `SaveImage` described below.
Class description:
Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response.
Method signatures and docstrings:
- def __init__(self, img_bytes: bytes, img_ext: str, invocation_id: str):... | 8f1b94518303c4e0a38df1ff6caa0e7326451d67 | <|skeleton|>
class SaveImage:
"""Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, img_bytes: bytes, img_ext: str, invocation_id: str):
"""Constructor of the save image object, stores provided an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SaveImage:
"""Image saving object, responsible for preparing the file storage structure, accessing the blob storage API, and evaluating the response."""
def __init__(self, img_bytes: bytes, img_ext: str, invocation_id: str):
"""Constructor of the save image object, stores provided and locally gen... | the_stack_v2_python_sparse | Serverless/handlers/s3_generate_thumbnail/save_image.py | RogerVFbr/MyCelebs | train | 0 |
420fabc4c13777bf3a4a7a4796063b42e8a8e741 | [
"self.num_elem = self.kwargs['num_elem']\nnum_pts = self.num_elem + 1\nind_pts = range(num_pts)\nself._declare_variable('Temp', size=num_pts, lower=0.001)\nself._declare_argument('h', indices=ind_pts)",
"pvec = self.vec['p']\nuvec = self.vec['u']\nalt = pvec('h') * 1000.0\ntemp = uvec('Temp')\ntemp[:] = (288.16 -... | <|body_start_0|>
self.num_elem = self.kwargs['num_elem']
num_pts = self.num_elem + 1
ind_pts = range(num_pts)
self._declare_variable('Temp', size=num_pts, lower=0.001)
self._declare_argument('h', indices=ind_pts)
<|end_body_0|>
<|body_start_1|>
pvec = self.vec['p']
... | linear temperature model using the standard atmosphere | SysTempOld | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
<|body_0|>
def apply_G(self):
"""temperature model extracted from linear portion of the standard atmos... | stack_v2_sparse_classes_75kplus_train_001640 | 17,488 | no_license | [
{
"docstring": "owned variable: Temp (temperature) dependencies: h (altitude)",
"name": "_declare",
"signature": "def _declare(self)"
},
{
"docstring": "temperature model extracted from linear portion of the standard atmosphere",
"name": "apply_G",
"signature": "def apply_G(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_015756 | Implement the Python class `SysTempOld` described below.
Class description:
linear temperature model using the standard atmosphere
Method signatures and docstrings:
- def _declare(self): owned variable: Temp (temperature) dependencies: h (altitude)
- def apply_G(self): temperature model extracted from linear portion ... | Implement the Python class `SysTempOld` described below.
Class description:
linear temperature model using the standard atmosphere
Method signatures and docstrings:
- def _declare(self): owned variable: Temp (temperature) dependencies: h (altitude)
- def apply_G(self): temperature model extracted from linear portion ... | f5b1ce287c6692540b738a7e9ec85be645f4947a | <|skeleton|>
class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
<|body_0|>
def apply_G(self):
"""temperature model extracted from linear portion of the standard atmos... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SysTempOld:
"""linear temperature model using the standard atmosphere"""
def _declare(self):
"""owned variable: Temp (temperature) dependencies: h (altitude)"""
self.num_elem = self.kwargs['num_elem']
num_pts = self.num_elem + 1
ind_pts = range(num_pts)
self._decla... | the_stack_v2_python_sparse | cmf_original_code/atmospherics.py | naylor-b/pyMission | train | 0 |
90b62be6c726adc6d682f43d5804c814cb5cb0ea | [
"print('trigger gpio ', gpio_func_trig)\nprint('echo gpio ', gpio_func_echo)\nself.echo_timeout_us = echo_timeout_us\nself.trigger = GPIO(gpio_func_trig, GPIO.OUT)\nself.trigger.value(0)\nself.echo = GPIO(gpio_func_echo, GPIO.IN)",
"self.trigger.value(0)\ntime.sleep_us(5)\nself.trigger.value(1)\ntime.sleep_us(10)... | <|body_start_0|>
print('trigger gpio ', gpio_func_trig)
print('echo gpio ', gpio_func_echo)
self.echo_timeout_us = echo_timeout_us
self.trigger = GPIO(gpio_func_trig, GPIO.OUT)
self.trigger.value(0)
self.echo = GPIO(gpio_func_echo, GPIO.IN)
<|end_body_0|>
<|body_start_1|... | Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range') | HCSR04 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HCSR04:
"""Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range')"""
def __init__(self, gpio_func_trig, gpio_func_echo, echo_timeout_us=500 * 2 * 30):
"""gpio_func_trig:... | stack_v2_sparse_classes_75kplus_train_001641 | 3,796 | no_license | [
{
"docstring": "gpio_func_trig: Output pin to send pulses of type GPIO.**** gpio_func_echo: Readonly pin to measure the distance. The pin should be protected with 1k resistor. type: GPIO.*** echo_timeout_us: Timeout in microseconds to listen to echo pin. By default is based in sensor limit range (4m)",
"nam... | 4 | stack_v2_sparse_classes_30k_train_047470 | Implement the Python class `HCSR04` described below.
Class description:
Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range')
Method signatures and docstrings:
- def __init__(self, gpio_func_trig, gpio_... | Implement the Python class `HCSR04` described below.
Class description:
Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range')
Method signatures and docstrings:
- def __init__(self, gpio_func_trig, gpio_... | bc0b61651657c8ee47e192de7e0bdf590e6bc917 | <|skeleton|>
class HCSR04:
"""Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range')"""
def __init__(self, gpio_func_trig, gpio_func_echo, echo_timeout_us=500 * 2 * 30):
"""gpio_func_trig:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HCSR04:
"""Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range')"""
def __init__(self, gpio_func_trig, gpio_func_echo, echo_timeout_us=500 * 2 * 30):
"""gpio_func_trig: Output pin t... | the_stack_v2_python_sparse | hcsr04.py | pritamghanghas/sipeed_playground | train | 0 |
4c308c06c751e5f143037c31c71b45ff8c37d022 | [
"array = self.format_and_eval_string(self.target_array)\nif self.column_name:\n array = array[self.column_name]\nval = self.format_and_eval_string(self.value)\ntry:\n ind = np.where(np.abs(array - val) < 1e-12)[0][0]\nexcept IndexError as e:\n msg = 'Could not find {} in array {} ({})'\n raise ValueErro... | <|body_start_0|>
array = self.format_and_eval_string(self.target_array)
if self.column_name:
array = array[self.column_name]
val = self.format_and_eval_string(self.value)
try:
ind = np.where(np.abs(array - val) < 1e-12)[0][0]
except IndexError as e:
... | Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution. | ArrayFindValueTask | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus_train_001642 | 6,289 | permissive | [
{
"docstring": "Find index of value array and store index in database.",
"name": "perform",
"signature": "def perform(self)"
},
{
"docstring": "Check the target array can be found and has the right column.",
"name": "check",
"signature": "def check(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_040639 | Implement the Python class `ArrayFindValueTask` described below.
Class description:
Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find index of value array and store index in database.
- def check... | Implement the Python class `ArrayFindValueTask` described below.
Class description:
Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution.
Method signatures and docstrings:
- def perform(self): Find index of value array and store index in database.
- def check... | b6f1f5b236c7a4e28d9a3bc8da9820c52d789309 | <|skeleton|>
class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
<|body_0|>
def check(self, *args, **kwargs):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArrayFindValueTask:
"""Store the index of the first occurence of a value in an array. Wait for any parallel operation before execution."""
def perform(self):
"""Find index of value array and store index in database."""
array = self.format_and_eval_string(self.target_array)
if self... | the_stack_v2_python_sparse | exopy_hqc_legacy/tasks/tasks/util/array_tasks.py | Exopy/exopy_hqc_legacy | train | 0 |
c27ed9954d6fe65a5b6744be342aa351e8c941dd | [
"index1 = index2 = -1\nmin_distance = len(words)\nfor idx in range(len(words)):\n if words[idx] == word1:\n index1 = idx\n elif words[idx] == word2:\n index2 = idx\n if index1 != -1 and index2 != -1:\n min_distance = min(min_distance, abs(index1 - index2))\nreturn min_distance",
"min... | <|body_start_0|>
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(words)):
if words[idx] == word1:
index1 = idx
elif words[idx] == word2:
index2 = idx
if index1 != -1 and index2 != -1:
min_dist... | Words | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_75kplus_train_001643 | 1,554 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:",
"name": "shortest_distance",
"signature": "def shortest_distance(self, words: List[str], word1: str, word2: str) -> int"
},
{
"docstring": "Approach: Brute For... | 2 | stack_v2_sparse_classes_30k_train_031386 | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(... | the_stack_v2_python_sparse | revisited_2021/arrays/shortest_word_distance.py | Shiv2157k/leet_code | train | 1 | |
5f6ea125c79b14870f26370f2e18d18905d3eec2 | [
"self.driver.find_element_by_xpath('//a[text() = \"登录\"]').click()\nlogger.info('点击登录按钮')\nself.driver.find_element_by_id('tab-register').click()\nlogger.info('点击免费注册')\nself.driver.find_element_by_xpath('//*[@id=\"pane-register\"]/form/div[1]/div/div/input').send_keys(random)\nlogger.info('输入手机号码')\nself.driver.fi... | <|body_start_0|>
self.driver.find_element_by_xpath('//a[text() = "登录"]').click()
logger.info('点击登录按钮')
self.driver.find_element_by_id('tab-register').click()
logger.info('点击免费注册')
self.driver.find_element_by_xpath('//*[@id="pane-register"]/form/div[1]/div/div/input').send_keys(ra... | Test_Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_Login:
def test_case01(self):
"""注册直客账号"""
<|body_0|>
def test_case02(self):
"""直客登录"""
<|body_1|>
def test_case03(self):
"""合作商登录"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.driver.find_element_by_xpath('//a[text(... | stack_v2_sparse_classes_75kplus_train_001644 | 5,621 | no_license | [
{
"docstring": "注册直客账号",
"name": "test_case01",
"signature": "def test_case01(self)"
},
{
"docstring": "直客登录",
"name": "test_case02",
"signature": "def test_case02(self)"
},
{
"docstring": "合作商登录",
"name": "test_case03",
"signature": "def test_case03(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_007814 | Implement the Python class `Test_Login` described below.
Class description:
Implement the Test_Login class.
Method signatures and docstrings:
- def test_case01(self): 注册直客账号
- def test_case02(self): 直客登录
- def test_case03(self): 合作商登录 | Implement the Python class `Test_Login` described below.
Class description:
Implement the Test_Login class.
Method signatures and docstrings:
- def test_case01(self): 注册直客账号
- def test_case02(self): 直客登录
- def test_case03(self): 合作商登录
<|skeleton|>
class Test_Login:
def test_case01(self):
"""注册直客账号"""
... | cf92e8e81ceb5cb67217bf36993cf94fe470fd0b | <|skeleton|>
class Test_Login:
def test_case01(self):
"""注册直客账号"""
<|body_0|>
def test_case02(self):
"""直客登录"""
<|body_1|>
def test_case03(self):
"""合作商登录"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_Login:
def test_case01(self):
"""注册直客账号"""
self.driver.find_element_by_xpath('//a[text() = "登录"]').click()
logger.info('点击登录按钮')
self.driver.find_element_by_id('tab-register').click()
logger.info('点击免费注册')
self.driver.find_element_by_xpath('//*[@id="pane-re... | the_stack_v2_python_sparse | hhr/case/qiantai/test_login.py | aixin2000/Test_Scripts | train | 0 | |
fea4fa13cc7504695eb80870df399e2609bf7c82 | [
"if gradeid:\n params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}\nelse:\n params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade'}\nrespDict = requests.get(URL, params=params).json()\npprint(respDict)\nreturn respDict",
"payload = {'vcode': vcode, 'action': 'ad... | <|body_start_0|>
if gradeid:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}
else:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade'}
respDict = requests.get(URL, params=params).json()
pprint(respDict)
... | ClassManageResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
<|body_0|>
def add_class(self, gradeid, name, studentlimit):
"""添加班级 :param gradeid:年级id :param name: 班级名次 :param studen... | stack_v2_sparse_classes_75kplus_train_001645 | 2,735 | no_license | [
{
"docstring": "根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据",
"name": "list_classes_by_schoolgrade",
"signature": "def list_classes_by_schoolgrade(self, gradeid=None)"
},
{
"docstring": "添加班级 :param gradeid:年级id :param name: 班级名次 :param studentlimit: 班级人数限制 :return: 返回dict... | 5 | stack_v2_sparse_classes_30k_train_022116 | Implement the Python class `ClassManageResource` described below.
Class description:
Implement the ClassManageResource class.
Method signatures and docstrings:
- def list_classes_by_schoolgrade(self, gradeid=None): 根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据
- def add_class(self, gradeid, name,... | Implement the Python class `ClassManageResource` described below.
Class description:
Implement the ClassManageResource class.
Method signatures and docstrings:
- def list_classes_by_schoolgrade(self, gradeid=None): 根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据
- def add_class(self, gradeid, name,... | 2c7049f0a70e2de922effc23d03e8b8fd995c67f | <|skeleton|>
class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
<|body_0|>
def add_class(self, gradeid, name, studentlimit):
"""添加班级 :param gradeid:年级id :param name: 班级名次 :param studen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClassManageResource:
def list_classes_by_schoolgrade(self, gradeid=None):
"""根据年级id列出班级,若年级id未传入,则列出所有 :param gradeid:年级id :return: 返回dict形式的数据"""
if gradeid:
params = {'vcode': vcode, 'action': 'list_classes_by_schoolgrade', 'gradeid': gradeid}
else:
params = {... | the_stack_v2_python_sparse | ActualCombat/pylib/ClassManageResource.py | tangshenhong/PycharmProjects | train | 0 | |
38203bb237001b05cd377beba79715862aa658bf | [
"self._alpha = alpha\nself._beta = beta\nself._sigmoid_clip_value = sigmoid_clip_value\nsuper(PenaltyReducedLogisticFocalLoss, self).__init__()",
"with tf.name_scope('prlf_loss'):\n is_present_tensor = tf.math.equal(target_tensor, 1.0)\n prediction_tensor = tf.clip_by_value(tf.sigmoid(prediction_tensor), se... | <|body_start_0|>
self._alpha = alpha
self._beta = beta
self._sigmoid_clip_value = sigmoid_clip_value
super(PenaltyReducedLogisticFocalLoss, self).__init__()
<|end_body_0|>
<|body_start_1|>
with tf.name_scope('prlf_loss'):
is_present_tensor = tf.math.equal(target_tens... | Penalty-reduced pixelwise logistic regression with focal loss. | PenaltyReducedLogisticFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PenaltyReducedLogisticFocalLoss:
"""Penalty-reduced pixelwise logistic regression with focal loss."""
def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=0.0001):
"""Constructor. The loss is defined in Equation (1) of the Objects as Points[1] paper. Although the loss is define... | stack_v2_sparse_classes_75kplus_train_001646 | 4,548 | permissive | [
{
"docstring": "Constructor. The loss is defined in Equation (1) of the Objects as Points[1] paper. Although the loss is defined per-pixel in the output space, this class assumes that each pixel is an anchor to be compatible with the base class. [1]: https://arxiv.org/abs/1904.07850 Args: alpha: Focussing param... | 2 | null | Implement the Python class `PenaltyReducedLogisticFocalLoss` described below.
Class description:
Penalty-reduced pixelwise logistic regression with focal loss.
Method signatures and docstrings:
- def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=0.0001): Constructor. The loss is defined in Equation (1) of th... | Implement the Python class `PenaltyReducedLogisticFocalLoss` described below.
Class description:
Penalty-reduced pixelwise logistic regression with focal loss.
Method signatures and docstrings:
- def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=0.0001): Constructor. The loss is defined in Equation (1) of th... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class PenaltyReducedLogisticFocalLoss:
"""Penalty-reduced pixelwise logistic regression with focal loss."""
def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=0.0001):
"""Constructor. The loss is defined in Equation (1) of the Objects as Points[1] paper. Although the loss is define... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PenaltyReducedLogisticFocalLoss:
"""Penalty-reduced pixelwise logistic regression with focal loss."""
def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=0.0001):
"""Constructor. The loss is defined in Equation (1) of the Objects as Points[1] paper. Although the loss is defined per-pixel i... | the_stack_v2_python_sparse | official/projects/centernet/losses/centernet_losses.py | jianzhnie/models | train | 2 |
96e66221ceebd0b1653fce8eb8931d29ab48d9a5 | [
"if not nodes_encountered:\n nodes_encountered = set()\nnodes = network.nodes()\nif not source:\n source = nodes[0]\nnodes_encountered.add(source)\nif len(nodes_encountered) != len(nodes):\n for node in network.network_dict[source].get_adjacents():\n if node not in nodes_encountered:\n if... | <|body_start_0|>
if not nodes_encountered:
nodes_encountered = set()
nodes = network.nodes()
if not source:
source = nodes[0]
nodes_encountered.add(source)
if len(nodes_encountered) != len(nodes):
for node in network.network_dict[source].get_ad... | This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached) | ConnectivityChecker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectivityChecker:
"""This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached)"""
def is_connected(network: Network, nodes_encountered: Set[Optional[int]... | stack_v2_sparse_classes_75kplus_train_001647 | 4,071 | permissive | [
{
"docstring": "Returns bool indicating graph connectivity (path between all nodes). This is a recursive DFS. :param network: object representing a graph (network) :param Set[int] nodes_encountered: set of node_id's encountered (None by default) :param int source: node_id of start of search (None by default) :r... | 3 | stack_v2_sparse_classes_30k_train_000304 | Implement the Python class `ConnectivityChecker` described below.
Class description:
This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached)
Method signatures and docstrings:
- def... | Implement the Python class `ConnectivityChecker` described below.
Class description:
This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached)
Method signatures and docstrings:
- def... | 1a07acbe7b039e04d40cceb790a95fe0421dfea5 | <|skeleton|>
class ConnectivityChecker:
"""This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached)"""
def is_connected(network: Network, nodes_encountered: Set[Optional[int]... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ConnectivityChecker:
"""This class determines whether a given network is connected or not. In a connected network, there exists a path between any given node and all other nodes (no nodes exist that cannot be reached)"""
def is_connected(network: Network, nodes_encountered: Set[Optional[int]]=None, sourc... | the_stack_v2_python_sparse | network_simulator/ConnectivityChecker.py | zspatter/network-simulation | train | 0 |
d77c03a97e5f3564bb653891ddf9bc04ec4883c7 | [
"super().__init__()\nself._username = username\nself._password = password",
"byte_user_pass = bytes('{u}:{pw}'.format(u=self._username, pw=self._password), 'utf-8')\nb64_str_userpass = base64.standard_b64encode(byte_user_pass).decode('utf-8')\nreturn {'Authorization': 'Basic {}'.format(b64_str_userpass)}"
] | <|body_start_0|>
super().__init__()
self._username = username
self._password = password
<|end_body_0|>
<|body_start_1|>
byte_user_pass = bytes('{u}:{pw}'.format(u=self._username, pw=self._password), 'utf-8')
b64_str_userpass = base64.standard_b64encode(byte_user_pass).decode('ut... | Authenticates using basic authentication. Primarily used for testing on local | BasicAuthentication | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuthentication:
"""Authenticates using basic authentication. Primarily used for testing on local"""
def __init__(self, username, password):
""":param str username: The basic auth username. :param str username: The basic auth password."""
<|body_0|>
def get_authentic... | stack_v2_sparse_classes_75kplus_train_001648 | 947 | permissive | [
{
"docstring": ":param str username: The basic auth username. :param str username: The basic auth password.",
"name": "__init__",
"signature": "def __init__(self, username, password)"
},
{
"docstring": "Provide the authentication headers for HTTP requests. :return: The authorization headers. :rt... | 2 | stack_v2_sparse_classes_30k_train_040651 | Implement the Python class `BasicAuthentication` described below.
Class description:
Authenticates using basic authentication. Primarily used for testing on local
Method signatures and docstrings:
- def __init__(self, username, password): :param str username: The basic auth username. :param str username: The basic au... | Implement the Python class `BasicAuthentication` described below.
Class description:
Authenticates using basic authentication. Primarily used for testing on local
Method signatures and docstrings:
- def __init__(self, username, password): :param str username: The basic auth username. :param str username: The basic au... | 3097aac3f3fd503b8639bf86ce534eda15230bf4 | <|skeleton|>
class BasicAuthentication:
"""Authenticates using basic authentication. Primarily used for testing on local"""
def __init__(self, username, password):
""":param str username: The basic auth username. :param str username: The basic auth password."""
<|body_0|>
def get_authentic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BasicAuthentication:
"""Authenticates using basic authentication. Primarily used for testing on local"""
def __init__(self, username, password):
""":param str username: The basic auth username. :param str username: The basic auth password."""
super().__init__()
self._username = us... | the_stack_v2_python_sparse | pyapacheatlas/auth/basic.py | kfengmsft/pyapacheatlas | train | 0 |
5acf30ec5cff33f066f2cce21d30e05e774fac62 | [
"self.n_frames = n_frames\nself.camera = camera\nself.line_segments = line_segments\nself.warp_offset = warp_offset\nself.y_cutoff = y_cutoff\nself.left_line = None\nself.right_line = None\nself.center_poly = None\nself.curvature = 0.0\nself.desiredSpeed = 0.0\nself.offset = 0.0\nself.perspective_src = perspective_... | <|body_start_0|>
self.n_frames = n_frames
self.camera = camera
self.line_segments = line_segments
self.warp_offset = warp_offset
self.y_cutoff = y_cutoff
self.left_line = None
self.right_line = None
self.center_poly = None
self.curvature = 0.0
... | LaneFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaneFinder:
def __init__(self, perspective_src, perspective_dst, n_frames=1, camera=None, line_segments=10, warp_offset=0, y_cutoff=400):
"""Tracks lane lines on images or a video stream using techniques like Sobel operation, color thresholding and sliding histogram discussed deeply on "... | stack_v2_sparse_classes_75kplus_train_001649 | 6,933 | no_license | [
{
"docstring": "Tracks lane lines on images or a video stream using techniques like Sobel operation, color thresholding and sliding histogram discussed deeply on \"Advanced-Lane-Finding-Submission\" notebook. Input Parameters: perspective_src: Source coordinates for perspective warp perspective_dst: Destination... | 5 | stack_v2_sparse_classes_30k_train_031071 | Implement the Python class `LaneFinder` described below.
Class description:
Implement the LaneFinder class.
Method signatures and docstrings:
- def __init__(self, perspective_src, perspective_dst, n_frames=1, camera=None, line_segments=10, warp_offset=0, y_cutoff=400): Tracks lane lines on images or a video stream us... | Implement the Python class `LaneFinder` described below.
Class description:
Implement the LaneFinder class.
Method signatures and docstrings:
- def __init__(self, perspective_src, perspective_dst, n_frames=1, camera=None, line_segments=10, warp_offset=0, y_cutoff=400): Tracks lane lines on images or a video stream us... | 57c24275d0717bb24082c0940f4eadcaf7438c6e | <|skeleton|>
class LaneFinder:
def __init__(self, perspective_src, perspective_dst, n_frames=1, camera=None, line_segments=10, warp_offset=0, y_cutoff=400):
"""Tracks lane lines on images or a video stream using techniques like Sobel operation, color thresholding and sliding histogram discussed deeply on "... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LaneFinder:
def __init__(self, perspective_src, perspective_dst, n_frames=1, camera=None, line_segments=10, warp_offset=0, y_cutoff=400):
"""Tracks lane lines on images or a video stream using techniques like Sobel operation, color thresholding and sliding histogram discussed deeply on "Advanced-Lane-... | the_stack_v2_python_sparse | LaneCarDetection/LaneFinder.py | munirjojoverge/Autonomous-Driving-05---Vehicle-Detection-and-Tracking | train | 1 | |
2fbdaaec9a651362605d43f2614e4ef57d08f80f | [
"self.client = Client()\nself.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')\nself.test_user.is_superuser = True\nself.test_user.is_active = True\nself.test_user.save()\nself.assertEqual(self.test_user.is_superuser, True)\nlogin = self.client.login(username='testuser', password='t... | <|body_start_0|>
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
self.test_user.is_superuser = True
self.test_user.is_active = True
self.test_user.save()
self.assertEqual(self.test_user.is_superuser, True)
... | Tests the model attributes of Strain objects contained in the animal app. | StrainModelTests | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StrainModelTests:
"""Tests the model attributes of Strain objects contained in the animal app."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
... | stack_v2_sparse_classes_75kplus_train_001650 | 48,499 | permissive | [
{
"docstring": "Instantiate the test client. Creates a test user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Depopulate created model instances from test database.",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "This is a test ... | 6 | stack_v2_sparse_classes_30k_train_035368 | Implement the Python class `StrainModelTests` described below.
Class description:
Tests the model attributes of Strain objects contained in the animal app.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances fr... | Implement the Python class `StrainModelTests` described below.
Class description:
Tests the model attributes of Strain objects contained in the animal app.
Method signatures and docstrings:
- def setUp(self): Instantiate the test client. Creates a test user.
- def tearDown(self): Depopulate created model instances fr... | 7e423991f72c89468010c99865e3c70c22044df3 | <|skeleton|>
class StrainModelTests:
"""Tests the model attributes of Strain objects contained in the animal app."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
<|body_0|>
def tearDown(self):
"""Depopulate created model instances from test database."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StrainModelTests:
"""Tests the model attributes of Strain objects contained in the animal app."""
def setUp(self):
"""Instantiate the test client. Creates a test user."""
self.client = Client()
self.test_user = User.objects.create_user('testuser', 'blah@blah.com', 'testpassword')
... | the_stack_v2_python_sparse | mousedb/animal/tests.py | BridgesLab/mousedb | train | 0 |
89766a7a63f65861a618bd2617dab872eb23c16c | [
"dp = defaultdict(int, {1: 1})\nfor pre in range(1, n + 1):\n for cur in range(pre + delay, pre + forget):\n dp[cur] += dp[pre]\nres = 0\nfor cur in range(n - forget + 1, n + 1):\n res += dp[cur]\n res %= MOD\nreturn res",
"dp = defaultdict(int, {1: 1})\ndpSum = defaultdict(int, {1: 1})\nfor day i... | <|body_start_0|>
dp = defaultdict(int, {1: 1})
for pre in range(1, n + 1):
for cur in range(pre + delay, pre + forget):
dp[cur] += dp[pre]
res = 0
for cur in range(n - forget + 1, n + 1):
res += dp[cur]
res %= MOD
return res
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int:
"""dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和"""
<|body_0|>
def peopleAwareOfSecret2(self, n: int, delay: int, forget: int) -> int:
... | stack_v2_sparse_classes_75kplus_train_001651 | 2,121 | no_license | [
{
"docstring": "dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和",
"name": "peopleAwareOfSecret1",
"signature": "def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int"
},
{
"docstring": "前缀和优化dp 思路sum(dp[pre+delay:pre+forget])])... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int: dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和
- def ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int: dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和
- def ... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int:
"""dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和"""
<|body_0|>
def peopleAwareOfSecret2(self, n: int, delay: int, forget: int) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def peopleAwareOfSecret1(self, n: int, delay: int, forget: int) -> int:
"""dp 怎么定义状态 dp[i] 表示 第i天新增的传播人数 不要定义成知道秘密的总人数 转移:第i天的新增人数来源于(i-forget,i-delay]区间的新增人数 答案:最后-forget天之和"""
dp = defaultdict(int, {1: 1})
for pre in range(1, n + 1):
for cur in range(pre + delay... | the_stack_v2_python_sparse | 11_动态规划/dp优化/前缀和优化/6109. 知道秘密的人数-前缀和优化dp.py | 981377660LMT/algorithm-study | train | 225 | |
374f6e3395483fd727bcf59886d7c8eb39383e9d | [
"if self.fill is not None:\n doc.context.stroke(None)\n doc.context.fill(self.fill)\n if self.w is not None and self.h is not None:\n doc.context.oval(ox, oy, self.w, self.h)",
"if self.stroke is not None and self.strokeWidth:\n doc.context.fill(None)\n doc.context.stroke(self.stroke, self.s... | <|body_start_0|>
if self.fill is not None:
doc.context.stroke(None)
doc.context.fill(self.fill)
if self.w is not None and self.h is not None:
doc.context.oval(ox, oy, self.w, self.h)
<|end_body_0|>
<|body_start_1|>
if self.stroke is not None and self.... | This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2, 1)) >>> doc.export('_export/Rect.pdf') # Build and export. | Oval | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Oval:
"""This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2, 1)) >>> doc.export('_export/Rect.pdf')... | stack_v2_sparse_classes_75kplus_train_001652 | 27,711 | permissive | [
{
"docstring": "Draw the background of the element. Default is to just draw the oval with the fill color, if it is defined. This method should be redefined by inheriting subclasses that need different foreground drawing.",
"name": "drawBackground",
"signature": "def drawBackground(self, ox, oy, doc, par... | 2 | stack_v2_sparse_classes_30k_test_000606 | Implement the Python class `Oval` described below.
Class description:
This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2,... | Implement the Python class `Oval` described below.
Class description:
This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2,... | 7bfd7196d23fa764638a3f94621d316446cbd6ac | <|skeleton|>
class Oval:
"""This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2, 1)) >>> doc.export('_export/Rect.pdf')... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Oval:
"""This element draws a simple oval. >>> from pagebotnano.document import Document >>> doc = Document() >>> page = doc.newPage() >>> padding = 40 >>> e = Oval(parent=page, x=padding, y=padding, w=page.w-2*padding, h=page.h-2*padding, fill=color(1, 0.2, 1)) >>> doc.export('_export/Rect.pdf') # Build and ... | the_stack_v2_python_sparse | PageBotNano/pagebotnano/elements/element.py | PageBot/PageBotNano | train | 6 |
dc4a7362cfdf2824ed20c3b7b15833817eea566e | [
"def traversal(node):\n if node is None:\n self.res += '-,'\n return\n self.res += str(node.val) + ','\n traversal(node.left)\n traversal(node.right)\nself.res = ''\ntraversal(root)\nreturn self.res[0:len(self.res) - 1]",
"def traversal():\n if self.data[self.index] == '-':\n s... | <|body_start_0|>
def traversal(node):
if node is None:
self.res += '-,'
return
self.res += str(node.val) + ','
traversal(node.left)
traversal(node.right)
self.res = ''
traversal(root)
return self.res[0:len(se... | 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 traversal(... | stack_v2_sparse_classes_75kplus_train_001653 | 2,589 | 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_037539 | 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... | 9b5e431773a9d50d073d7555472970cc06e6ca4d | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def traversal(node):
if node is None:
self.res += '-,'
return
self.res += str(node.val) + ','
traversal(node.left)
travers... | the_stack_v2_python_sparse | design/449_serialize_deserialize_bt.py | maximelearning/My-Leetcode-Solutions | train | 0 | |
f573312c2415968fb8c67a3b5f979d0913775d68 | [
"if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):\n pass\nelse:\n user_id = request.COOKIES.get('emulate_user_id')\n username = request.COOKIES.get('emulate_user_username')\n request_emulate_user(request, user_id=user_id, username=... | <|body_start_0|>
if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):
pass
else:
user_id = request.COOKIES.get('emulate_user_id')
username = request.COOKIES.get('emulate_user_username')
r... | HtkEmulateUserMiddleware | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
<|body_0|>
def process_response(self, request, response):
"""Delete user emulation cookies if they should not be set"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_001654 | 1,446 | permissive | [
{
"docstring": "Replace the authenticated `request.user` if properly emulating",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Delete user emulation cookies if they should not be set",
"name": "process_response",
"signature": "def process... | 2 | stack_v2_sparse_classes_30k_train_014970 | Implement the Python class `HtkEmulateUserMiddleware` described below.
Class description:
Implement the HtkEmulateUserMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Replace the authenticated `request.user` if properly emulating
- def process_response(self, request, response)... | Implement the Python class `HtkEmulateUserMiddleware` described below.
Class description:
Implement the HtkEmulateUserMiddleware class.
Method signatures and docstrings:
- def process_request(self, request): Replace the authenticated `request.user` if properly emulating
- def process_response(self, request, response)... | 935c4913e33d959f8c29583825f72b238f85b380 | <|skeleton|>
class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
<|body_0|>
def process_response(self, request, response):
"""Delete user emulation cookies if they should not be set"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HtkEmulateUserMiddleware:
def process_request(self, request):
"""Replace the authenticated `request.user` if properly emulating"""
if request.path.startswith(htk_setting('HTK_PATH_ADMIN')) or request.path.startswith(htk_setting('HTK_PATH_ADMINTOOLS')):
pass
else:
... | the_stack_v2_python_sparse | admintools/middleware.py | hacktoolkit/django-htk | train | 210 | |
ce93973ab1a7250ee1f45e7d76731bae1d1fdd83 | [
"type_str = self.cleaned_data['type']\ntry:\n Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])\nexcept Cvterm.DoesNotExist:\n raise ValidationError('This type does not exist in the database')\nreturn type_str",
"vector = self.cleaned_data['vector']\nerror_in_type = self.errors.get('type', Fa... | <|body_start_0|>
type_str = self.cleaned_data['type']
try:
Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])
except Cvterm.DoesNotExist:
raise ValidationError('This type does not exist in the database')
return type_str
<|end_body_0|>
<|body_start_1... | Form to add features to db | FeatureForm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
<|body_0|>
def clean_vector(self):
"""It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates t... | stack_v2_sparse_classes_75kplus_train_001655 | 7,506 | permissive | [
{
"docstring": "It validates the type field",
"name": "clean_type",
"signature": "def clean_type(self)"
},
{
"docstring": "It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates that the vector is in the database",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_025946 | Implement the Python class `FeatureForm` described below.
Class description:
Form to add features to db
Method signatures and docstrings:
- def clean_type(self): It validates the type field
- def clean_vector(self): It validates the vector. If the feature is a vector it does not validate anything if feature is not a ... | Implement the Python class `FeatureForm` described below.
Class description:
Form to add features to db
Method signatures and docstrings:
- def clean_type(self): It validates the type field
- def clean_vector(self): It validates the vector. If the feature is a vector it does not validate anything if feature is not a ... | 7a50c9c4e65308fb51abf4f236457d12e9d028d6 | <|skeleton|>
class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
<|body_0|>
def clean_vector(self):
"""It validates the vector. If the feature is a vector it does not validate anything if feature is not a vector if validates t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureForm:
"""Form to add features to db"""
def clean_type(self):
"""It validates the type field"""
type_str = self.cleaned_data['type']
try:
Cvterm.objects.get(name=self.cleaned_data['type'].split(',')[0])
except Cvterm.DoesNotExist:
raise Valida... | the_stack_v2_python_sparse | goldenbraid/forms/feature.py | bioinfcomav/goldebraid | train | 0 |
49f3aa4fbeec448e903a0b38d9aa41eef5a68768 | [
"if not value:\n raise ValueError('need value to verify time literal')\nif not isinstance(value, str):\n raise ValueError('type of the value for time literal check is not str')\nif re.match('^(\\\\d+(?:[uµsmhdw]|(?:ns)|(?:ms)))+$', value):\n return True\nreturn False",
"if not value:\n raise ValueErro... | <|body_start_0|>
if not value:
raise ValueError('need value to verify time literal')
if not isinstance(value, str):
raise ValueError('type of the value for time literal check is not str')
if re.match('^(\\d+(?:[uµsmhdw]|(?:ns)|(?:ms)))+$', value):
return True
... | Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape signs. check_time_literal - Checks wheather the str is consistend as influxdb t... | InfluxUtils | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfluxUtils:
"""Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape signs. check_time_literal - Checks wheat... | stack_v2_sparse_classes_75kplus_train_001656 | 7,480 | permissive | [
{
"docstring": "Checks wheather the str is consistend as influxdb time literal Args: value (str): time literal to be checked Raises: ValueError: No value given ValueError: Not a string given Returns: bool: true if it is consistend",
"name": "check_time_literal",
"signature": "def check_time_literal(valu... | 4 | stack_v2_sparse_classes_30k_train_031874 | Implement the Python class `InfluxUtils` described below.
Class description:
Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape s... | Implement the Python class `InfluxUtils` described below.
Class description:
Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape s... | 5b3ea9f1a853be0187e17c3a3f6e98091f95434f | <|skeleton|>
class InfluxUtils:
"""Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape signs. check_time_literal - Checks wheat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InfluxUtils:
"""Influx related util methods. Those can be reused, placed here to make them easier to use/find. Attributes: time_key_names - default used time_key names Methods: escape_chars - Escapes chars to a even number of escape signs. Only adds escape signs. check_time_literal - Checks wheather the str i... | the_stack_v2_python_sparse | python/utils/influx_utils.py | daytoju/spectrum-protect-sppmon | train | 0 |
680e6ab62ac50c4aa3aa59468943be2cb7eff6f8 | [
"self.sequences = sequences\nif similarity_score in dir(pah) and callable(getattr(pah, similarity_score)):\n similarity_score_obj = eval('pah().' + similarity_score)\nelse:\n print('Score function not found!')\n sys.exit()\nself.score_function = similarity_score_obj",
"score_value = 0\nfor i in range(0, ... | <|body_start_0|>
self.sequences = sequences
if similarity_score in dir(pah) and callable(getattr(pah, similarity_score)):
similarity_score_obj = eval('pah().' + similarity_score)
else:
print('Score function not found!')
sys.exit()
self.score_function =... | This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.edu/download/30855770/Articulo03.pdf | SumOfPairs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumOfPairs:
"""This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.edu/download/30855770/Articulo03.pdf"""
... | stack_v2_sparse_classes_75kplus_train_001657 | 2,443 | no_license | [
{
"docstring": "To initialize a object of the SumOfPairs class please define a list with the multiple sequence alignment and a similarity score method which is defined in class PairwiseAlignmentHelper of package helper. sequences: The multiple alginment as a list. similarity_score: The scoring functions name as... | 3 | null | Implement the Python class `SumOfPairs` described below.
Class description:
This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.e... | Implement the Python class `SumOfPairs` described below.
Class description:
This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.e... | 20d8df6172906337f81583dabb841d66b8f31857 | <|skeleton|>
class SumOfPairs:
"""This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.edu/download/30855770/Articulo03.pdf"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SumOfPairs:
"""This class computes the Sum-of-pairs algorithm by Carillo and Lipman: Carrillo, Humberto, and David Lipman. "The multiple sequence alignment problem in biology." SIAM Journal on Applied Mathematics 48.5 (1988): 1073-1082. http://www.academia.edu/download/30855770/Articulo03.pdf"""
def __in... | the_stack_v2_python_sparse | new_algs/Sequence+algorithms/Needleman-Wunsch+algorithm/sumOfPairs.py | coolsnake/JupyterNotebook | train | 0 |
864f99b7e6d6712f1d9c4bc9a8f873039f26fe7a | [
"super().__init__()\nself.bert_model = BertModel.from_pretrained('bert-base-cased', output_hidden_states=True)\nself.encoder = SGDEncoder(hidden_size=768, dropout=0.1)\nself.decoder = SGDDecoder(embedding_dim=768, num_classes=1)",
"token_embedding = self.bert_model(input_ids=input_ids, token_type_ids=token_type_i... | <|body_start_0|>
super().__init__()
self.bert_model = BertModel.from_pretrained('bert-base-cased', output_hidden_states=True)
self.encoder = SGDEncoder(hidden_size=768, dropout=0.1)
self.decoder = SGDDecoder(embedding_dim=768, num_classes=1)
<|end_body_0|>
<|body_start_1|>
token... | serviceModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class serviceModel:
def __init__(self):
"""Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be generated. embedding_dim: hidden size of the BERT Returns: A tensor of shape (batch_size, num_classes) co... | stack_v2_sparse_classes_75kplus_train_001658 | 2,943 | no_license | [
{
"docstring": "Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be generated. embedding_dim: hidden size of the BERT Returns: A tensor of shape (batch_size, num_classes) containing the logits.",
"name": "__init__"... | 2 | null | Implement the Python class `serviceModel` described below.
Class description:
Implement the serviceModel class.
Method signatures and docstrings:
- def __init__(self): Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be gene... | Implement the Python class `serviceModel` described below.
Class description:
Implement the serviceModel class.
Method signatures and docstrings:
- def __init__(self): Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be gene... | d5742c5bfb43d08257e2c6de1f16bdb90b0523f1 | <|skeleton|>
class serviceModel:
def __init__(self):
"""Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be generated. embedding_dim: hidden size of the BERT Returns: A tensor of shape (batch_size, num_classes) co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class serviceModel:
def __init__(self):
"""Get logits for elements by conditioning on input embedding. Args: num_classes: An int containing the number of classes for which logits are to be generated. embedding_dim: hidden size of the BERT Returns: A tensor of shape (batch_size, num_classes) containing the l... | the_stack_v2_python_sparse | Final/DST/model_clf.py | ericdddddd/NTU_ADL2021 | train | 1 | |
911e89e6d247ffe47e863a23545143ffcba8890b | [
"if options.numbers:\n return esc(n) + '%3d ' % n\nelif options.hex:\n return esc(n) + ' %2x ' % n\nreturn esc(n) + ' '",
"if options.foreground:\n esc = lambda n: fg_escape % n\nelse:\n esc = lambda n: bg_escape % n + fg_escape % (15 if n < 9 else 0)\nreturn [[term16.label(n, esc) + clear for n in r... | <|body_start_0|>
if options.numbers:
return esc(n) + '%3d ' % n
elif options.hex:
return esc(n) + ' %2x ' % n
return esc(n) + ' '
<|end_body_0|>
<|body_start_1|>
if options.foreground:
esc = lambda n: fg_escape % n
else:
esc = lam... | Basic 16 color terminal. | term16 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus_train_001659 | 20,144 | permissive | [
{
"docstring": "color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '",
"name": "label",
"signature": "def label(n, esc)"
},
{
"docstring": "16 color info ... | 5 | stack_v2_sparse_classes_30k_train_048440 | Implement the Python class `term16` described below.
Class description:
Basic 16 color terminal.
Method signatures and docstrings:
- def label(n, esc): color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.la... | Implement the Python class `term16` described below.
Class description:
Basic 16 color terminal.
Method signatures and docstrings:
- def label(n, esc): color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.la... | 03925ab9701d70850e0621bc7857e154551a03a6 | <|skeleton|>
class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
<|body_0|>
d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class term16:
"""Basic 16 color terminal."""
def label(n, esc):
"""color label for 256 color values >>> options.numbers = True >>> term16.label(95, lambda n: '') ' 95 ' >>> options.numbers = False >>> options.hex = True >>> term16.label(95, lambda n: '') ' 5f '"""
if options.numbers:
... | the_stack_v2_python_sparse | dot_bin/executable_colors | benmezger/dotfiles | train | 95 |
0029fe2deafa5cbdf2ac22700c0a8b91bfffdfa4 | [
"self.fields_were_on_gpu = simulation.fld.data_is_on_gpu\nself.species_were_on_gpu = [species.data_is_on_gpu for species in simulation.ptcl]\nself.sim = simulation",
"if self.sim.use_cuda:\n if not self.fields_were_on_gpu:\n self.sim.fld.send_fields_to_gpu()\n for i, species in enumerate(self.sim.ptc... | <|body_start_0|>
self.fields_were_on_gpu = simulation.fld.data_is_on_gpu
self.species_were_on_gpu = [species.data_is_on_gpu for species in simulation.ptcl]
self.sim = simulation
<|end_body_0|>
<|body_start_1|>
if self.sim.use_cuda:
if not self.fields_were_on_gpu:
... | Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager | GpuMemoryManager | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GpuMemoryManager:
"""Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager"""
def __init__(self, simulation):
"""Initialize the context manager Parameters: ----------- simulation: object A simulat... | stack_v2_sparse_classes_75kplus_train_001660 | 19,517 | permissive | [
{
"docstring": "Initialize the context manager Parameters: ----------- simulation: object A simulation object that contains the particle (ptcl) and field object (fld)",
"name": "__init__",
"signature": "def __init__(self, simulation)"
},
{
"docstring": "Move the data to the GPU (if it was origin... | 3 | null | Implement the Python class `GpuMemoryManager` described below.
Class description:
Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager
Method signatures and docstrings:
- def __init__(self, simulation): Initialize the context man... | Implement the Python class `GpuMemoryManager` described below.
Class description:
Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager
Method signatures and docstrings:
- def __init__(self, simulation): Initialize the context man... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class GpuMemoryManager:
"""Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager"""
def __init__(self, simulation):
"""Initialize the context manager Parameters: ----------- simulation: object A simulat... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GpuMemoryManager:
"""Context manager that temporarily moves the simulation data to the GPU, if the data is originally on the CPU when entering the context manager"""
def __init__(self, simulation):
"""Initialize the context manager Parameters: ----------- simulation: object A simulation object th... | the_stack_v2_python_sparse | fbpic/utils/cuda.py | fbpic/fbpic | train | 163 |
e66c28274145c71012c3edc7135ef79ecb5adf4a | [
"self.subscription_id, self.credentials = common.GetCredentials(profile_name)\nself.default_region = default_region\nself._compute = None\nself._monitoring = None\nself._network = None\nself._resource = None\nself._storage = None\nself.default_resource_group_name = self.resource.GetOrCreateResourceGroup(default_res... | <|body_start_0|>
self.subscription_id, self.credentials = common.GetCredentials(profile_name)
self.default_region = default_region
self._compute = None
self._monitoring = None
self._network = None
self._resource = None
self._storage = None
self.default_res... | Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resources in. default_resource_group_name (str): The default resource group in which... | AZAccount | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AZAccount:
"""Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resources in. default_resource_group_name (str)... | stack_v2_sparse_classes_75kplus_train_001661 | 4,772 | permissive | [
{
"docstring": "Initialize the AZAccount class. Args: default_resource_group_name (str): The default resource group in which to create new resources in. If the resource group does not exists, it will be automatically created. default_region (str): Optional. The default region to create new resources in. Default... | 6 | null | Implement the Python class `AZAccount` described below.
Class description:
Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resource... | Implement the Python class `AZAccount` described below.
Class description:
Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resource... | 38926ef5d075696b2b0f6714f3758be1e6ea1658 | <|skeleton|>
class AZAccount:
"""Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resources in. default_resource_group_name (str)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AZAccount:
"""Class that represents an Azure Account. Attributes: subscription_id (str): The Azure subscription ID to use. credentials (ServicePrincipalCredentials): An Azure credentials object. default_region (str): The default region to create new resources in. default_resource_group_name (str): The default... | the_stack_v2_python_sparse | libcloudforensics/providers/azure/internal/account.py | google/cloud-forensics-utils | train | 418 |
05937e0c5386f3fda8d255f41100d72cadfa9b5a | [
"this.he = he\nthis.h = h\nthis.gdl = gdl\nthis.xa = xa",
"this.Ue = U[this.gdl]\nthis.Qe = np.dot(this.Ke, this.Ue) - this.Fe\nreturn this.Qe"
] | <|body_start_0|>
this.he = he
this.h = h
this.gdl = gdl
this.xa = xa
<|end_body_0|>
<|body_start_1|>
this.Ue = U[this.gdl]
this.Qe = np.dot(this.Ke, this.Ue) - this.Fe
return this.Qe
<|end_body_1|>
| # Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc | Elemento | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Elemento:
"""# Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc"""
def __init__(this, he, gdl, xa, h):
"""## Constructor *** Constructor de la clase Elemento, crea un nuevo elemento Parameters ---------- he: fl... | stack_v2_sparse_classes_75kplus_train_001662 | 1,362 | permissive | [
{
"docstring": "## Constructor *** Constructor de la clase Elemento, crea un nuevo elemento Parameters ---------- he: float Longitud del elemento gdl: list Grados de libertad (nodos) en los que se encuentra el elemento xa: float xa: Coordenada incial del elemento h: float Presicion para calculos iterativos, por... | 2 | stack_v2_sparse_classes_30k_train_005963 | Implement the Python class `Elemento` described below.
Class description:
# Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc
Method signatures and docstrings:
- def __init__(this, he, gdl, xa, h): ## Constructor *** Constructor de la clase Elem... | Implement the Python class `Elemento` described below.
Class description:
# Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc
Method signatures and docstrings:
- def __init__(this, he, gdl, xa, h): ## Constructor *** Constructor de la clase Elem... | 77d47ff392d04594d8f421948cf544351bb34fd5 | <|skeleton|>
class Elemento:
"""# Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc"""
def __init__(this, he, gdl, xa, h):
"""## Constructor *** Constructor de la clase Elemento, crea un nuevo elemento Parameters ---------- he: fl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Elemento:
"""# Clase Elemento *** Define un elemento con porpia longitud, coordeandas, matrices de coeficientes, vectores de fuerzas, etc"""
def __init__(this, he, gdl, xa, h):
"""## Constructor *** Constructor de la clase Elemento, crea un nuevo elemento Parameters ---------- he: float Longitud ... | the_stack_v2_python_sparse | FEMSections/FEM1D/Elemento.py | ZibraMax/FEMSections | train | 1 |
9e398f3f07fff8a207c57595bd1c708a9f49a06e | [
"try:\n if not data['name'] or not data['version'] or (not data['type']):\n return JsonResponse(code='999996', msg='参数有误!')\n if data['type'] not in ['手动', '自动']:\n return JsonResponse(code='999996', msg='参数有误!')\nexcept KeyError:\n return JsonResponse(code='999996', msg='参数有误!')",
"caseMem... | <|body_start_0|>
try:
if not data['name'] or not data['version'] or (not data['type']):
return JsonResponse(code='999996', msg='参数有误!')
if data['type'] not in ['手动', '自动']:
return JsonResponse(code='999996', msg='参数有误!')
except KeyError:
... | AddCaseProject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddCaseProject:
def parameter_check(self, data):
"""验证参数 :param data: :return:"""
<|body_0|>
def add_project_member(self, caseProject, user):
"""添加项目创建人员 :param project: 项目ID :param user: 用户ID :return:"""
<|body_1|>
def post(self, request):
"""新增... | stack_v2_sparse_classes_75kplus_train_001663 | 11,764 | no_license | [
{
"docstring": "验证参数 :param data: :return:",
"name": "parameter_check",
"signature": "def parameter_check(self, data)"
},
{
"docstring": "添加项目创建人员 :param project: 项目ID :param user: 用户ID :return:",
"name": "add_project_member",
"signature": "def add_project_member(self, caseProject, user)... | 3 | null | Implement the Python class `AddCaseProject` described below.
Class description:
Implement the AddCaseProject class.
Method signatures and docstrings:
- def parameter_check(self, data): 验证参数 :param data: :return:
- def add_project_member(self, caseProject, user): 添加项目创建人员 :param project: 项目ID :param user: 用户ID :return... | Implement the Python class `AddCaseProject` described below.
Class description:
Implement the AddCaseProject class.
Method signatures and docstrings:
- def parameter_check(self, data): 验证参数 :param data: :return:
- def add_project_member(self, caseProject, user): 添加项目创建人员 :param project: 项目ID :param user: 用户ID :return... | d65297b71ac9f759d508985ee15564162c285e11 | <|skeleton|>
class AddCaseProject:
def parameter_check(self, data):
"""验证参数 :param data: :return:"""
<|body_0|>
def add_project_member(self, caseProject, user):
"""添加项目创建人员 :param project: 项目ID :param user: 用户ID :return:"""
<|body_1|>
def post(self, request):
"""新增... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddCaseProject:
def parameter_check(self, data):
"""验证参数 :param data: :return:"""
try:
if not data['name'] or not data['version'] or (not data['type']):
return JsonResponse(code='999996', msg='参数有误!')
if data['type'] not in ['手动', '自动']:
... | the_stack_v2_python_sparse | automation-test_new/api_test/case/caseProjectList.py | beitou/django_api_test | train | 0 | |
1cddffceea8ffd47f4e54535f5127b72d5be3442 | [
"shutil.copy('build/MakePAR', 'source/Makefile')\nos.chdir('source')\nself.cfg.update('makeopts', 'LD=\"$MPIF90 -o\" FC=\"$MPIF90 -c\" par')",
"self.log.debug('copying %s/execute to %s, (from %s)', self.cfg['start_dir'], self.installdir, os.getcwd())\nbin_path = os.path.join(self.installdir, 'bin')\ninstall_path ... | <|body_start_0|>
shutil.copy('build/MakePAR', 'source/Makefile')
os.chdir('source')
self.cfg.update('makeopts', 'LD="$MPIF90 -o" FC="$MPIF90 -c" par')
<|end_body_0|>
<|body_start_1|>
self.log.debug('copying %s/execute to %s, (from %s)', self.cfg['start_dir'], self.installdir, os.getcwd(... | Support for building and installing DL_POLY Classic. | EB_DL_underscore_POLY_underscore_Classic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EB_DL_underscore_POLY_underscore_Classic:
"""Support for building and installing DL_POLY Classic."""
def configure_step(self):
"""Copy the makefile to the source directory and use MPIF90 to do a parrallel build"""
<|body_0|>
def install_step(self):
"""Copy the ex... | stack_v2_sparse_classes_75kplus_train_001664 | 2,190 | no_license | [
{
"docstring": "Copy the makefile to the source directory and use MPIF90 to do a parrallel build",
"name": "configure_step",
"signature": "def configure_step(self)"
},
{
"docstring": "Copy the executables to the installation directory",
"name": "install_step",
"signature": "def install_s... | 2 | stack_v2_sparse_classes_30k_train_046999 | Implement the Python class `EB_DL_underscore_POLY_underscore_Classic` described below.
Class description:
Support for building and installing DL_POLY Classic.
Method signatures and docstrings:
- def configure_step(self): Copy the makefile to the source directory and use MPIF90 to do a parrallel build
- def install_st... | Implement the Python class `EB_DL_underscore_POLY_underscore_Classic` described below.
Class description:
Support for building and installing DL_POLY Classic.
Method signatures and docstrings:
- def configure_step(self): Copy the makefile to the source directory and use MPIF90 to do a parrallel build
- def install_st... | 3c5434f9a4193fbe4cf8107327faadda83d798ae | <|skeleton|>
class EB_DL_underscore_POLY_underscore_Classic:
"""Support for building and installing DL_POLY Classic."""
def configure_step(self):
"""Copy the makefile to the source directory and use MPIF90 to do a parrallel build"""
<|body_0|>
def install_step(self):
"""Copy the ex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EB_DL_underscore_POLY_underscore_Classic:
"""Support for building and installing DL_POLY Classic."""
def configure_step(self):
"""Copy the makefile to the source directory and use MPIF90 to do a parrallel build"""
shutil.copy('build/MakePAR', 'source/Makefile')
os.chdir('source')
... | the_stack_v2_python_sparse | 1.11.1/easyblock/easyblocks/d/dl_poly_classic.py | lsuhpchelp/easybuild_smic | train | 0 |
57d7da873a49ce2fbb00ab4bccd391c34373647b | [
"sign = -1 if x < 0 else 1\nx *= sign\nres = 0\nwhile x:\n t = x % 10\n x //= 10\n res = res * 10 + t\nif not -2 ** 31 <= res <= 2 ** 31 - 1:\n return 0\nreturn res * sign",
"sign = -1 if x < 0 else 1\nx *= sign\ns = str(x)\nres = 0\nfor i in s[::-1]:\n res = res * 10 + (ord(i) - ord('0'))\nres *= ... | <|body_start_0|>
sign = -1 if x < 0 else 1
x *= sign
res = 0
while x:
t = x % 10
x //= 10
res = res * 10 + t
if not -2 ** 31 <= res <= 2 ** 31 - 1:
return 0
return res * sign
<|end_body_0|>
<|body_start_1|>
sign = -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse(self, x: int) -> int:
"""反转整型变量的数字"""
<|body_0|>
def reverse2(self, x):
"""反转整型变量的数字, 通过转换为字符串再反转实现"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sign = -1 if x < 0 else 1
x *= sign
res = 0
while x:
... | stack_v2_sparse_classes_75kplus_train_001665 | 2,009 | no_license | [
{
"docstring": "反转整型变量的数字",
"name": "reverse",
"signature": "def reverse(self, x: int) -> int"
},
{
"docstring": "反转整型变量的数字, 通过转换为字符串再反转实现",
"name": "reverse2",
"signature": "def reverse2(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027945 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x: int) -> int: 反转整型变量的数字
- def reverse2(self, x): 反转整型变量的数字, 通过转换为字符串再反转实现 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse(self, x: int) -> int: 反转整型变量的数字
- def reverse2(self, x): 反转整型变量的数字, 通过转换为字符串再反转实现
<|skeleton|>
class Solution:
def reverse(self, x: int) -> int:
"""反转整型... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def reverse(self, x: int) -> int:
"""反转整型变量的数字"""
<|body_0|>
def reverse2(self, x):
"""反转整型变量的数字, 通过转换为字符串再反转实现"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverse(self, x: int) -> int:
"""反转整型变量的数字"""
sign = -1 if x < 0 else 1
x *= sign
res = 0
while x:
t = x % 10
x //= 10
res = res * 10 + t
if not -2 ** 31 <= res <= 2 ** 31 - 1:
return 0
return... | the_stack_v2_python_sparse | math/007 Reverse Integer.py | mofei952/leetcode_python | train | 0 | |
dfb7731c9054940e42053b58d8e62477283bf941 | [
"response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))\ninstance = MockHttpProvider.return_value\ninstance.send.return_value = response\ninstance = MockAuthProvider.return_value\ninstance.authenticate.return_value = 'blah'\ninstance.authenticate_request.retu... | <|body_start_0|>
response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))
instance = MockHttpProvider.return_value
instance.send.return_value = response
instance = MockAuthProvider.return_value
instance.authenticate.return_va... | TestCollections | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
<|body_0|>
def test_paging(self, MockHttpProvider, MockAuthProvider):
"""Test paging of a file in situatio... | stack_v2_sparse_classes_75kplus_train_001666 | 2,797 | permissive | [
{
"docstring": "Test page creation when there is no nextLink attached to the collection",
"name": "test_page_creation",
"signature": "def test_page_creation(self, MockHttpProvider, MockAuthProvider)"
},
{
"docstring": "Test paging of a file in situations where more than one page is available",
... | 2 | stack_v2_sparse_classes_30k_train_018155 | Implement the Python class `TestCollections` described below.
Class description:
Implement the TestCollections class.
Method signatures and docstrings:
- def test_page_creation(self, MockHttpProvider, MockAuthProvider): Test page creation when there is no nextLink attached to the collection
- def test_paging(self, Mo... | Implement the Python class `TestCollections` described below.
Class description:
Implement the TestCollections class.
Method signatures and docstrings:
- def test_page_creation(self, MockHttpProvider, MockAuthProvider): Test page creation when there is no nextLink attached to the collection
- def test_paging(self, Mo... | a5151a43c44acf61c513efdf286d40234c0795f0 | <|skeleton|>
class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
<|body_0|>
def test_paging(self, MockHttpProvider, MockAuthProvider):
"""Test paging of a file in situatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCollections:
def test_page_creation(self, MockHttpProvider, MockAuthProvider):
"""Test page creation when there is no nextLink attached to the collection"""
response = HttpResponse(200, None, json.dumps({'value': [{'name': 'test1', 'folder': {}}, {'name': 'test2'}]}))
instance = Mo... | the_stack_v2_python_sparse | testonedrivesdk/test_collections.py | AtakamaLLC/onedrive-sdk-python | train | 20 | |
ac7070f701a0cfa5199b92e0e333614fb76fcec2 | [
"data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}\npost_to_update = self.post1\nresponse = self.client.put('/1.0/posts/{0}/'.format(post_to_update.id), data)\nself.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)",
... | <|body_start_0|>
data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}
post_to_update = self.post1
response = self.client.put('/1.0/posts/{0}/'.format(post_to_update.id), data)
self.assertEqual(response.sta... | PostUpdateAPITest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostUpdateAPITest:
def test_post_cannot_be_updated_by_anonymous(self):
"""Ensures that a post cannot be updated by anonymous user"""
<|body_0|>
def test_post_cannot_be_updated_by_other(self):
"""Ensures that a post cannot be updated by other"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_001667 | 20,627 | no_license | [
{
"docstring": "Ensures that a post cannot be updated by anonymous user",
"name": "test_post_cannot_be_updated_by_anonymous",
"signature": "def test_post_cannot_be_updated_by_anonymous(self)"
},
{
"docstring": "Ensures that a post cannot be updated by other",
"name": "test_post_cannot_be_upd... | 4 | stack_v2_sparse_classes_30k_train_036668 | Implement the Python class `PostUpdateAPITest` described below.
Class description:
Implement the PostUpdateAPITest class.
Method signatures and docstrings:
- def test_post_cannot_be_updated_by_anonymous(self): Ensures that a post cannot be updated by anonymous user
- def test_post_cannot_be_updated_by_other(self): En... | Implement the Python class `PostUpdateAPITest` described below.
Class description:
Implement the PostUpdateAPITest class.
Method signatures and docstrings:
- def test_post_cannot_be_updated_by_anonymous(self): Ensures that a post cannot be updated by anonymous user
- def test_post_cannot_be_updated_by_other(self): En... | 56bfe19853bfec4581870a0075d0f21ee4d4bfda | <|skeleton|>
class PostUpdateAPITest:
def test_post_cannot_be_updated_by_anonymous(self):
"""Ensures that a post cannot be updated by anonymous user"""
<|body_0|>
def test_post_cannot_be_updated_by_other(self):
"""Ensures that a post cannot be updated by other"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PostUpdateAPITest:
def test_post_cannot_be_updated_by_anonymous(self):
"""Ensures that a post cannot be updated by anonymous user"""
data = {'title': 'Lorem ipsum', 'intro': 'Lorem ipsum dolor', 'body': 'Lorem ipsum dolor sit amet', 'image_url': 'http://example.com/'}
post_to_update = ... | the_stack_v2_python_sparse | blogs/tests.py | dmpinero/practica_Python_Django_Avanzado | train | 0 | |
0d9f07aa20d75d71006c1cbc362b81fec3035a78 | [
"super(NextSentenceExtension, self).__init__(**kwargs)\nself.init_matrix = None\nself.align_stream = align_stream",
"params = self.main_loop.model.get_parameter_dict()\nfor name in params:\n if 'alignment_matrix' in name:\n self.align_matrix = params[name]\n self.init_matrix = self.align_matrix.g... | <|body_start_0|>
super(NextSentenceExtension, self).__init__(**kwargs)
self.init_matrix = None
self.align_stream = align_stream
<|end_body_0|>
<|body_start_1|>
params = self.main_loop.model.get_parameter_dict()
for name in params:
if 'alignment_matrix' in name:
... | This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair. | NextSentenceExtension | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NextSentenceExtension:
"""This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair."""
def __init__(self, align_stream, **kwargs):
"""Constructor of ``Nex... | stack_v2_sparse_classes_75kplus_train_001668 | 8,812 | permissive | [
{
"docstring": "Constructor of ``NextSentenceExtension``. Args: align_stream (ExplicitNext): DataStream which supports explicitly switching to the next sentence pair",
"name": "__init__",
"signature": "def __init__(self, align_stream, **kwargs)"
},
{
"docstring": "Fetches the alignment matrix pa... | 3 | stack_v2_sparse_classes_30k_train_026876 | Implement the Python class `NextSentenceExtension` described below.
Class description:
This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair.
Method signatures and docstrings:
- def __i... | Implement the Python class `NextSentenceExtension` described below.
Class description:
This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair.
Method signatures and docstrings:
- def __i... | 533b0e5627d8dcef3adccf76e776d3dea5c24a3c | <|skeleton|>
class NextSentenceExtension:
"""This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair."""
def __init__(self, align_stream, **kwargs):
"""Constructor of ``Nex... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NextSentenceExtension:
"""This Blocks extension is invoked each ``--iterations`` batches. It saves the previous alignment matrix, resets the matrix in the computation graph, and iterates to the next sentence pair."""
def __init__(self, align_stream, **kwargs):
"""Constructor of ``NextSentenceExte... | the_stack_v2_python_sparse | cam/sgnmt/blocks/alignment/nam.py | srgangireddy/sgnmt | train | 0 |
bbdd5b58c83e55e9411b8425d21ee7c2c8c43076 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernor... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.... | to create an encoder block for a transformer: | DecoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""to create an encoder block for a transformer:"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
""""initialize decoder"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_001669 | 11,342 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "\"initialize decoder",
"name": "call",
"signature": "def call(self, x, encoder_output, training, look_ahead_mask, padding_mask)"
}
] | 2 | null | Implement the Python class `DecoderBlock` described below.
Class description:
to create an encoder block for a transformer:
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): constructor
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): "initialize decode... | Implement the Python class `DecoderBlock` described below.
Class description:
to create an encoder block for a transformer:
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): constructor
- def call(self, x, encoder_output, training, look_ahead_mask, padding_mask): "initialize decode... | bda9efa60075afa834433ff1b5179db80f2487ae | <|skeleton|>
class DecoderBlock:
"""to create an encoder block for a transformer:"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
""""initialize decoder"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DecoderBlock:
"""to create an encoder block for a transformer:"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden ... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer..py | vandeldiegoc/holbertonschool-machine_learning | train | 0 |
4dfeacbf2e8401086a6e036c5b8831acd80d7dfe | [
"super().__init__(name=name, **kwargs)\nself.num_bins = num_bins\nself.sigma_ratio = sigma_ratio",
"if len(y_true.shape) == 4:\n y_true = tf.expand_dims(y_true, axis=4)\n y_pred = tf.expand_dims(y_pred, axis=4)\nassert len(y_true.shape) == len(y_pred.shape) == 5\ny_true = tf.clip_by_value(y_true, 0, 1)\ny_p... | <|body_start_0|>
super().__init__(name=name, **kwargs)
self.num_bins = num_bins
self.sigma_ratio = sigma_ratio
<|end_body_0|>
<|body_start_1|>
if len(y_true.shape) == 4:
y_true = tf.expand_dims(y_true, axis=4)
y_pred = tf.expand_dims(y_pred, axis=4)
asser... | Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1 | GlobalMutualInformation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalMutualInformation:
"""Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1"""
def __init__(self, nu... | stack_v2_sparse_classes_75kplus_train_001670 | 12,244 | permissive | [
{
"docstring": "Init. :param num_bins: number of bins for intensity, the default value is empirical. :param sigma_ratio: a hyper param for gaussian function :param name: name of the loss :param kwargs: additional arguments.",
"name": "__init__",
"signature": "def __init__(self, num_bins: int=23, sigma_r... | 3 | null | Implement the Python class `GlobalMutualInformation` described below.
Class description:
Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Al... | Implement the Python class `GlobalMutualInformation` described below.
Class description:
Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Al... | 650a2f1a88ad3c6932be305d6a98a36e26feedc6 | <|skeleton|>
class GlobalMutualInformation:
"""Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1"""
def __init__(self, nu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GlobalMutualInformation:
"""Differentiable global mutual information via Parzen windowing method. y_true and y_pred have to be at least 4d tensor, including batch axis. Reference: https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1"""
def __init__(self, num_bins: int=2... | the_stack_v2_python_sparse | deepreg/loss/image.py | DeepRegNet/DeepReg | train | 509 |
97cf5fe2bc9be4a1732cb159b55adadf649d4fb4 | [
"\"\"\"Initialization\"\"\"\nself.img_shape = img_shape\nself.chunk_size = chunk_size\nself.attr_vals = load_attr_vals_txts()\nself.attr_cnt = len(self.attr_vals)\nself.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()\nprint('-- Generator Wiki initialized.')",
"images = []\nerrs =... | <|body_start_0|>
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = chunk_size
self.attr_vals = load_attr_vals_txts()
self.attr_cnt = len(self.attr_vals)
self.train_ids, self.validation_ids, self.test_ids, self.attr_map = load_config_wiki()
print('-... | DataGeneratorWiki | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_75kplus_train_001671 | 3,756 | no_license | [
{
"docstring": ":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation",
"name": "__init__",
"signature": "def __init__(self, img_shape=(100, 100), chunk_size=1024)"
},
{
"docstring": "Reads list of images from specidied fol... | 4 | stack_v2_sparse_classes_30k_val_000501 | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | Implement the Python class `DataGeneratorWiki` described below.
Class description:
Implement the DataGeneratorWiki class.
Method signatures and docstrings:
- def __init__(self, img_shape=(100, 100), chunk_size=1024): :param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: in... | acd540fe845d0496c9cf2560f59623de3b93898c | <|skeleton|>
class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
<|body_0|>
def get_images_online(self, img_names):
"""Re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataGeneratorWiki:
def __init__(self, img_shape=(100, 100), chunk_size=1024):
""":param img_shape: resolution of final image :param chunk_size: size of super batch :param rot_int: interval for image rotation"""
"""Initialization"""
self.img_shape = img_shape
self.chunk_size = c... | the_stack_v2_python_sparse | data_proc/DataGeneratorWiki.py | MarcisinMatej/CNN | train | 0 | |
d7c7e62165a52178590ade734048b8f292472f7f | [
"assert model_name in ['Resnet50_FPN', 'MobileNetV3_largeFPN', 'MobileNetV3_largeFPN_320', 'MaskRCNN', 'YOLOv5x'], 'Error: model not found'\nweights_path += 'best_' + model_name + '.pt'\nself.model = get_object_detection_model(num_classes=2, mtype=model_name, weights_path=weights_path, device=torch.device('cpu'))\n... | <|body_start_0|>
assert model_name in ['Resnet50_FPN', 'MobileNetV3_largeFPN', 'MobileNetV3_largeFPN_320', 'MaskRCNN', 'YOLOv5x'], 'Error: model not found'
weights_path += 'best_' + model_name + '.pt'
self.model = get_object_detection_model(num_classes=2, mtype=model_name, weights_path=weights_p... | ObjectPredictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectPredictor:
def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'):
"""Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights"""
... | stack_v2_sparse_classes_75kplus_train_001672 | 11,558 | no_license | [
{
"docstring": "Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights",
"name": "__init__",
"signature": "def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/mo... | 2 | stack_v2_sparse_classes_30k_train_047391 | Implement the Python class `ObjectPredictor` described below.
Class description:
Implement the ObjectPredictor class.
Method signatures and docstrings:
- def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): Constructor :param model_name: n... | Implement the Python class `ObjectPredictor` described below.
Class description:
Implement the ObjectPredictor class.
Method signatures and docstrings:
- def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'): Constructor :param model_name: n... | 7101da99d0744405b9faa0ef6c9c98f4e3adf148 | <|skeleton|>
class ObjectPredictor:
def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'):
"""Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectPredictor:
def __init__(self, model_name='MobileNetV3_largeFPN', weights_path='/home/phil/Documents/Projects/CV_SLAM_project/cv_lib/models/'):
"""Constructor :param model_name: name of the pre trained model to load :param weights_path: from where to load the trained weights"""
assert mod... | the_stack_v2_python_sparse | cv_lib/src/object_prediction.py | PhiCtl/Object-pose-estimation | train | 0 | |
b5ca4e48721c8110ff8d8d1be95f78481ca92dd8 | [
"self.N = N\nself.R = zeros((3, 3), float64)\nself.length = 0.0",
"vect = fetch_data('vect')\nnum_calcs = 0\nfor i in range(self.N):\n R_random_hypersphere(self.R)\n new_vect = dot(self.R, vect)\n self.length += norm(new_vect)\n num_calcs += 1\nprocessor.return_object(Test_result_command(processor, me... | <|body_start_0|>
self.N = N
self.R = zeros((3, 3), float64)
self.length = 0.0
<|end_body_0|>
<|body_start_1|>
vect = fetch_data('vect')
num_calcs = 0
for i in range(self.N):
R_random_hypersphere(self.R)
new_vect = dot(self.R, vect)
sel... | The slave command for use by the slave processor. | Test_slave_command | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_slave_command:
"""The slave command for use by the slave processor."""
def __init__(self, N=0):
"""Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @type N: int"""
<|body_0|>
def run(self, proc... | stack_v2_sparse_classes_75kplus_train_001673 | 10,343 | no_license | [
{
"docstring": "Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @type N: int",
"name": "__init__",
"signature": "def __init__(self, N=0)"
},
{
"docstring": "Essential method for performing calculations on the slave process... | 2 | null | Implement the Python class `Test_slave_command` described below.
Class description:
The slave command for use by the slave processor.
Method signatures and docstrings:
- def __init__(self, N=0): Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @... | Implement the Python class `Test_slave_command` described below.
Class description:
The slave command for use by the slave processor.
Method signatures and docstrings:
- def __init__(self, N=0): Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Test_slave_command:
"""The slave command for use by the slave processor."""
def __init__(self, N=0):
"""Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @type N: int"""
<|body_0|>
def run(self, proc... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_slave_command:
"""The slave command for use by the slave processor."""
def __init__(self, N=0):
"""Set up the slave command object for the slave processor. @keyword N: The number of calculations for the slave to perform. @type N: int"""
self.N = N
self.R = zeros((3, 3), float... | the_stack_v2_python_sparse | multi/test_implementation2.py | jlec/relax | train | 4 |
c62d9e8a0be736fd0678937837522b59f51a32e6 | [
"py_typecheck.check_callable(executor_stack_fn)\nself._executor_stack_fn = executor_stack_fn\nself._executors = {}",
"py_typecheck.check_type(cardinalities, dict)\nkey = _get_hashable_key(cardinalities)\nex = self._executors.get(key)\nif ex is not None:\n return ex\nex = self._executor_stack_fn(cardinalities)\... | <|body_start_0|>
py_typecheck.check_callable(executor_stack_fn)
self._executor_stack_fn = executor_stack_fn
self._executors = {}
<|end_body_0|>
<|body_start_1|>
py_typecheck.check_type(cardinalities, dict)
key = _get_hashable_key(cardinalities)
ex = self._executors.get(k... | Implementation of executor factory holding an executor per cardinality. | ExecutorFactoryImpl | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping fr... | stack_v2_sparse_classes_75kplus_train_001674 | 9,860 | permissive | [
{
"docstring": "Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping from `placement_literals.PlacementLiteral` to integers, and returning an `executor_base.Executor`. The returned executor will be configured to handle these cardinalities.",
"name": "__init__",
"signatur... | 3 | stack_v2_sparse_classes_30k_train_007657 | Implement the Python class `ExecutorFactoryImpl` described below.
Class description:
Implementation of executor factory holding an executor per cardinality.
Method signatures and docstrings:
- def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]): Initializes `ExecutorFactoryImp... | Implement the Python class `ExecutorFactoryImpl` described below.
Class description:
Implementation of executor factory holding an executor per cardinality.
Method signatures and docstrings:
- def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]): Initializes `ExecutorFactoryImp... | 7797df103bf965a9d0cd70e20ae61066650382d9 | <|skeleton|>
class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping fr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ExecutorFactoryImpl:
"""Implementation of executor factory holding an executor per cardinality."""
def __init__(self, executor_stack_fn: Callable[[CardinalitiesType], executor_base.Executor]):
"""Initializes `ExecutorFactoryImpl`. Args: executor_stack_fn: Callable taking a mapping from `placement... | the_stack_v2_python_sparse | tensorflow_federated/python/core/impl/executors/executor_factory.py | tf-encrypted/federated | train | 1 |
9315fa507033fe98749a343224ffdaa28fe43dda | [
"table = self.tables[table_name]\nupdate_dict = _clean_dict(update_dict, table.schema)\ntb_func = getattr(self.tensorboard, 'add_%s' % summary_type)\nstep = step if step else table.nrows\nfor name, value in update_dict.items():\n tb_func('/'.join([table_name, name]), value, step)",
"table = self.tables[table_n... | <|body_start_0|>
table = self.tables[table_name]
update_dict = _clean_dict(update_dict, table.schema)
tb_func = getattr(self.tensorboard, 'add_%s' % summary_type)
step = step if step else table.nrows
for name, value in update_dict.items():
tb_func('/'.join([table_name... | The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree. | CustomStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, ta... | stack_v2_sparse_classes_75kplus_train_001675 | 3,794 | no_license | [
{
"docstring": "Log to only tensorboard. Args: table_name (str) : which table to log to update_dict (dict) : values to log and store as a dictionary of column mapping to value. summary_type (str) : what type of summary to log to tensorboard as step: which step index to insert datapoint",
"name": "log_tb",
... | 3 | stack_v2_sparse_classes_30k_train_016437 | Implement the Python class `CustomStore` described below.
Class description:
The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this s... | Implement the Python class `CustomStore` described below.
Class description:
The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this s... | 978de314897904c9014209d479c03dc3509f7dc0 | <|skeleton|>
class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, ta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, table_name, upd... | the_stack_v2_python_sparse | playground/trl/projections/custom_store.py | NiklasFreymuth/bayesian-aggregation-for-swarm-reinforcement-learning | train | 0 |
52bbfc6a0c577ad69c1e9504cd0d9ff5ed751616 | [
"with open(trainTextNLTK4russian, encoding='utf-8') as f:\n sents = list(read_corpus_to_nltk(f))\ncontextTegger = PMContextTagger(train=sents, type_='full')\ngraphemAnaliz = GraphematicAnalysis(textOriginal)\ntextTokenz = graphemAnaliz.get_sentences()\ntagsDict = contextTegger.tag(textTokenz)\ntokenPosList = sel... | <|body_start_0|>
with open(trainTextNLTK4russian, encoding='utf-8') as f:
sents = list(read_corpus_to_nltk(f))
contextTegger = PMContextTagger(train=sents, type_='full')
graphemAnaliz = GraphematicAnalysis(textOriginal)
textTokenz = graphemAnaliz.get_sentences()
tagsD... | Класс текстового анализа. Включает в себя морфологию и синтаксис | TextAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextAnalysis:
"""Класс текстового анализа. Включает в себя морфологию и синтаксис"""
def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=False):
"""Морфологический анализ текста :param trainTextNLTK4russian: текст с табцляциями для тренировки модели :param textOrigin... | stack_v2_sparse_classes_75kplus_train_001676 | 4,012 | no_license | [
{
"docstring": "Морфологический анализ текста :param trainTextNLTK4russian: текст с табцляциями для тренировки модели :param textOriginal: путь к файлу с текстом :return: список tag pymorphy",
"name": "morph_analysis",
"signature": "def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=Fa... | 3 | stack_v2_sparse_classes_30k_train_050281 | Implement the Python class `TextAnalysis` described below.
Class description:
Класс текстового анализа. Включает в себя морфологию и синтаксис
Method signatures and docstrings:
- def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=False): Морфологический анализ текста :param trainTextNLTK4russian: те... | Implement the Python class `TextAnalysis` described below.
Class description:
Класс текстового анализа. Включает в себя морфологию и синтаксис
Method signatures and docstrings:
- def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=False): Морфологический анализ текста :param trainTextNLTK4russian: те... | 94337c6a3ea113285bd1ffb7bb891c1c4fed90e6 | <|skeleton|>
class TextAnalysis:
"""Класс текстового анализа. Включает в себя морфологию и синтаксис"""
def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=False):
"""Морфологический анализ текста :param trainTextNLTK4russian: текст с табцляциями для тренировки модели :param textOrigin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TextAnalysis:
"""Класс текстового анализа. Включает в себя морфологию и синтаксис"""
def morph_analysis(self, trainTextNLTK4russian, textOriginal, rusTag=False):
"""Морфологический анализ текста :param trainTextNLTK4russian: текст с табцляциями для тренировки модели :param textOriginal: путь к фа... | the_stack_v2_python_sparse | parsing/TextAnalysis.py | Ameise-github/WordProcessing | train | 0 |
5edb315325d15ee34a0de95a5d780bd46024f37c | [
"self.chardict = [x if x != '<eos>' else '</s>' for x in token_list]\nself.charlen = len(self.chardict)\nself.lm = kenlm.LanguageModel(ngram_model)\nself.tmpkenlmstate = kenlm.State()",
"state = kenlm.State()\nself.lm.NullContextWrite(state)\nreturn state",
"out_state = kenlm.State()\nys = self.chardict[y[-1]] ... | <|body_start_0|>
self.chardict = [x if x != '<eos>' else '</s>' for x in token_list]
self.charlen = len(self.chardict)
self.lm = kenlm.LanguageModel(ngram_model)
self.tmpkenlmstate = kenlm.State()
<|end_body_0|>
<|body_start_1|>
state = kenlm.State()
self.lm.NullContextW... | Ngram base implemented through ScorerInterface. | Ngrambase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ngrambase:
"""Ngram base implemented through ScorerInterface."""
def __init__(self, ngram_model, token_list):
"""Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json"""
<|body_0|>
def init_state(self, x):
"""Ini... | stack_v2_sparse_classes_75kplus_train_001677 | 3,838 | permissive | [
{
"docstring": "Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json",
"name": "__init__",
"signature": "def __init__(self, ngram_model, token_list)"
},
{
"docstring": "Initialize tmp state.",
"name": "init_state",
"signature": "def ini... | 3 | stack_v2_sparse_classes_30k_val_001067 | Implement the Python class `Ngrambase` described below.
Class description:
Ngram base implemented through ScorerInterface.
Method signatures and docstrings:
- def __init__(self, ngram_model, token_list): Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json
- def ini... | Implement the Python class `Ngrambase` described below.
Class description:
Ngram base implemented through ScorerInterface.
Method signatures and docstrings:
- def __init__(self, ngram_model, token_list): Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json
- def ini... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class Ngrambase:
"""Ngram base implemented through ScorerInterface."""
def __init__(self, ngram_model, token_list):
"""Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json"""
<|body_0|>
def init_state(self, x):
"""Ini... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ngrambase:
"""Ngram base implemented through ScorerInterface."""
def __init__(self, ngram_model, token_list):
"""Initialize Ngrambase. Args: ngram_model: ngram model path token_list: token list from dict or model.json"""
self.chardict = [x if x != '<eos>' else '</s>' for x in token_list]
... | the_stack_v2_python_sparse | paddlespeech/s2t/decoders/scorers/ngram.py | anniyanvr/DeepSpeech-1 | train | 0 |
e7b68062cd7ed5e091a506151424d2bb31f24fe5 | [
"user = sample_user()\nproject = Project.objects.create(name='Test Project', description='Test Project Description')\nself.assertEqual(project.name, 'Test Project')\nself.assertEqual(project.description, 'Test Project Description')",
"lead1 = sample_user(name='Test User 1', email='test1@xyz.com')\nlead2 = sample_... | <|body_start_0|>
user = sample_user()
project = Project.objects.create(name='Test Project', description='Test Project Description')
self.assertEqual(project.name, 'Test Project')
self.assertEqual(project.description, 'Test Project Description')
<|end_body_0|>
<|body_start_1|>
le... | TestProjectModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProjectModel:
def test_project_creation(self):
"""Test project creation"""
<|body_0|>
def test_project_leads(self):
"""Test many to many relationship of project leads"""
<|body_1|>
def test_project_members(self):
"""Test many to many relation... | stack_v2_sparse_classes_75kplus_train_001678 | 1,939 | permissive | [
{
"docstring": "Test project creation",
"name": "test_project_creation",
"signature": "def test_project_creation(self)"
},
{
"docstring": "Test many to many relationship of project leads",
"name": "test_project_leads",
"signature": "def test_project_leads(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_039157 | Implement the Python class `TestProjectModel` described below.
Class description:
Implement the TestProjectModel class.
Method signatures and docstrings:
- def test_project_creation(self): Test project creation
- def test_project_leads(self): Test many to many relationship of project leads
- def test_project_members(... | Implement the Python class `TestProjectModel` described below.
Class description:
Implement the TestProjectModel class.
Method signatures and docstrings:
- def test_project_creation(self): Test project creation
- def test_project_leads(self): Test many to many relationship of project leads
- def test_project_members(... | 34c50bf68f774fe0d5fdbf74498fac1347c263b6 | <|skeleton|>
class TestProjectModel:
def test_project_creation(self):
"""Test project creation"""
<|body_0|>
def test_project_leads(self):
"""Test many to many relationship of project leads"""
<|body_1|>
def test_project_members(self):
"""Test many to many relation... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestProjectModel:
def test_project_creation(self):
"""Test project creation"""
user = sample_user()
project = Project.objects.create(name='Test Project', description='Test Project Description')
self.assertEqual(project.name, 'Test Project')
self.assertEqual(project.desc... | the_stack_v2_python_sparse | officialWebsite/projects/tests.py | developer-student-club-thapar/officialWebsite | train | 24 | |
e992bca67f3546cd6e55dfacc3207c7b319d2090 | [
"self.maxlen = maxSize\nself.currlen = 0\nself.val = []",
"if self.currlen < self.maxlen:\n self.val.append(x)\n self.currlen += 1\nelse:\n pass",
"if self.currlen > 0:\n number = self.val[self.currlen - 1]\n self.val.pop()\n self.currlen -= 1\n return number\nelse:\n return -1",
"if k... | <|body_start_0|>
self.maxlen = maxSize
self.currlen = 0
self.val = []
<|end_body_0|>
<|body_start_1|>
if self.currlen < self.maxlen:
self.val.append(x)
self.currlen += 1
else:
pass
<|end_body_1|>
<|body_start_2|>
if self.currlen > 0:
... | CustomStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def increment(self, k, val):
""":type k: ... | stack_v2_sparse_classes_75kplus_train_001679 | 1,361 | no_license | [
{
"docstring": ":type maxSize: int",
"name": "__init__",
"signature": "def __init__(self, maxSize)"
},
{
"docstring": ":type x: int :rtype: None",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def pop(self)"... | 4 | null | Implement the Python class `CustomStack` described below.
Class description:
Implement the CustomStack class.
Method signatures and docstrings:
- def __init__(self, maxSize): :type maxSize: int
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def increment(self, k, val): :type k: int :typ... | Implement the Python class `CustomStack` described below.
Class description:
Implement the CustomStack class.
Method signatures and docstrings:
- def __init__(self, maxSize): :type maxSize: int
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def increment(self, k, val): :type k: int :typ... | ee59b82125f100970c842d5e1245287c484d6649 | <|skeleton|>
class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def increment(self, k, val):
""":type k: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomStack:
def __init__(self, maxSize):
""":type maxSize: int"""
self.maxlen = maxSize
self.currlen = 0
self.val = []
def push(self, x):
""":type x: int :rtype: None"""
if self.currlen < self.maxlen:
self.val.append(x)
self.currlen... | the_stack_v2_python_sparse | _CodeTopics/LeetCode_contest/weekly/weekly2020/180/180_2.py | BIAOXYZ/variousCodes | train | 0 | |
5aba0ab342f104edea4b86747dc9fe9fed0b963b | [
"testfile = 'nuts.zip'\ntest_data, testfile_content = self.get_testformdata(testfile)\nresponse = self.client.post('api/geofile/', data=test_data, content_type='multipart/form-data', follow_redirects=True)\nself.assertStatusCodeEqual(response, 200)\nresponse.close()\nargs = self.TILE_PARAMETERS\nargs['layers'] = te... | <|body_start_0|>
testfile = 'nuts.zip'
test_data, testfile_content = self.get_testformdata(testfile)
response = self.client.post('api/geofile/', data=test_data, content_type='multipart/form-data', follow_redirects=True)
self.assertStatusCodeEqual(response, 200)
response.close()
... | Test the wms GetMap endpoint | WMSGetMapTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WMSGetMapTest:
"""Test the wms GetMap endpoint"""
def testVectorTileWorkflow(self):
"""Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty."""
<|body_0|>
def testRasterTileWorkflow(self):
"""Upload... | stack_v2_sparse_classes_75kplus_train_001680 | 10,175 | permissive | [
{
"docstring": "Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty.",
"name": "testVectorTileWorkflow",
"signature": "def testVectorTileWorkflow(self)"
},
{
"docstring": "Upload a raster, then check that the tile request is not e... | 2 | null | Implement the Python class `WMSGetMapTest` described below.
Class description:
Test the wms GetMap endpoint
Method signatures and docstrings:
- def testVectorTileWorkflow(self): Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty.
- def testRasterTileW... | Implement the Python class `WMSGetMapTest` described below.
Class description:
Test the wms GetMap endpoint
Method signatures and docstrings:
- def testVectorTileWorkflow(self): Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty.
- def testRasterTileW... | bb336e434afcc11463b53880558d9c314f309c0e | <|skeleton|>
class WMSGetMapTest:
"""Test the wms GetMap endpoint"""
def testVectorTileWorkflow(self):
"""Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty."""
<|body_0|>
def testRasterTileWorkflow(self):
"""Upload... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WMSGetMapTest:
"""Test the wms GetMap endpoint"""
def testVectorTileWorkflow(self):
"""Post a vector file, retrieve it as image from WMS endpoint, check if the image has the right size without being empty."""
testfile = 'nuts.zip'
test_data, testfile_content = self.get_testformdat... | the_stack_v2_python_sparse | api/app/endpoints/test_wms.py | sfrias/enermaps | train | 0 |
2fa417d4d0364590e2fedc09ccc1400d746d34ad | [
"super().__init__()\nself.enc_hidden_size = enc_hidden_size\nself.dec_hidden_size = dec_hidden_size\nself.coverage = coverage\nself.bias = bias\nself.weight_norm = weight_norm\nself.end_bias = pointer_end_bias\nself.Wh = nn.Linear(enc_hidden_size, attention_size, bias=False)\nself.Ws = nn.Linear(dec_hidden_size, at... | <|body_start_0|>
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hidden_size = dec_hidden_size
self.coverage = coverage
self.bias = bias
self.weight_norm = weight_norm
self.end_bias = pointer_end_bias
self.Wh = nn.Linear(enc_hidden_size,... | BahdanauAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BahdanauAttention:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False):
"""Bahdanau Attention (+ Coverage)"""
<|body_0|>
def forward(self, encoder_outputs, decoder_state, mask,... | stack_v2_sparse_classes_75kplus_train_001681 | 49,575 | no_license | [
{
"docstring": "Bahdanau Attention (+ Coverage)",
"name": "__init__",
"signature": "def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False)"
},
{
"docstring": "Args: encoder_outputs [B, source_len, hid... | 2 | stack_v2_sparse_classes_30k_train_051391 | Implement the Python class `BahdanauAttention` described below.
Class description:
Implement the BahdanauAttention class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False): Bahdanau... | Implement the Python class `BahdanauAttention` described below.
Class description:
Implement the BahdanauAttention class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False): Bahdanau... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class BahdanauAttention:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False):
"""Bahdanau Attention (+ Coverage)"""
<|body_0|>
def forward(self, encoder_outputs, decoder_state, mask,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BahdanauAttention:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256, attention_size=700, coverage=False, weight_norm=False, bias=True, pointer_end_bias=False):
"""Bahdanau Attention (+ Coverage)"""
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hi... | the_stack_v2_python_sparse | generated/test_clovaai_FocusSeq2Seq.py | jansel/pytorch-jit-paritybench | train | 35 | |
2765a0336464353548d7c5b53034d9ee89fba671 | [
"user = get_a_user(categoryid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn get_a_user(data=data)",
"user = complete_users(categoryid)\nif not user:\n api.abort(404)\nelse:\n return user\ndata = request.json\nreturn complete_users(data=data)",
"user = delete_user(... | <|body_start_0|>
user = get_a_user(categoryid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
<|end_body_0|>
<|body_start_1|>
user = complete_users(categoryid)
if not user:
api.ab... | Category | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Category:
def get(self, categoryid):
"""get a Category given its identifier"""
<|body_0|>
def put(self, categoryid):
"""Category Updated"""
<|body_1|>
def delete(self, categoryid):
"""Category Deleted"""
<|body_2|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_001682 | 2,613 | no_license | [
{
"docstring": "get a Category given its identifier",
"name": "get",
"signature": "def get(self, categoryid)"
},
{
"docstring": "Category Updated",
"name": "put",
"signature": "def put(self, categoryid)"
},
{
"docstring": "Category Deleted",
"name": "delete",
"signature":... | 3 | null | Implement the Python class `Category` described below.
Class description:
Implement the Category class.
Method signatures and docstrings:
- def get(self, categoryid): get a Category given its identifier
- def put(self, categoryid): Category Updated
- def delete(self, categoryid): Category Deleted | Implement the Python class `Category` described below.
Class description:
Implement the Category class.
Method signatures and docstrings:
- def get(self, categoryid): get a Category given its identifier
- def put(self, categoryid): Category Updated
- def delete(self, categoryid): Category Deleted
<|skeleton|>
class ... | 4fa4042304ee01cf23ecc81f9c27977fd12c31b9 | <|skeleton|>
class Category:
def get(self, categoryid):
"""get a Category given its identifier"""
<|body_0|>
def put(self, categoryid):
"""Category Updated"""
<|body_1|>
def delete(self, categoryid):
"""Category Deleted"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Category:
def get(self, categoryid):
"""get a Category given its identifier"""
user = get_a_user(categoryid)
if not user:
api.abort(404)
else:
return user
data = request.json
return get_a_user(data=data)
def put(self, categoryid):
... | the_stack_v2_python_sparse | main/controller/category_controller.py | Gauravkumar45/Flask-RESTPlus-API | train | 0 | |
cd752f1e7eec40a1fda1fa415627c6e5a2758c95 | [
"ret = {}\nret = {}\nret['notebook'] = self.notebook.name\nif include_notebook:\n ret['notebook_text'] = self.notebook.meta.notebook\nret['job'] = self.job.name\nret['parameters'] = self.parameters\nret['type'] = self.type\nret['output'] = self.output\nret['strip_code'] = self.strip_code\nret['template'] = self.... | <|body_start_0|>
ret = {}
ret = {}
ret['notebook'] = self.notebook.name
if include_notebook:
ret['notebook_text'] = self.notebook.meta.notebook
ret['job'] = self.job.name
ret['parameters'] = self.parameters
ret['type'] = self.type
ret['output']... | Paperboy configuration object representing a Report (metadata component) | ReportMetadataConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportMetadataConfig:
"""Paperboy configuration object representing a Report (metadata component)"""
def to_json(self, include_notebook=False):
"""Convert ReportMetadata to a JSON"""
<|body_0|>
def from_json(jsn):
"""Create ReportMetadata from a JSON"""
<... | stack_v2_sparse_classes_75kplus_train_001683 | 8,336 | permissive | [
{
"docstring": "Convert ReportMetadata to a JSON",
"name": "to_json",
"signature": "def to_json(self, include_notebook=False)"
},
{
"docstring": "Create ReportMetadata from a JSON",
"name": "from_json",
"signature": "def from_json(jsn)"
}
] | 2 | stack_v2_sparse_classes_30k_val_003036 | Implement the Python class `ReportMetadataConfig` described below.
Class description:
Paperboy configuration object representing a Report (metadata component)
Method signatures and docstrings:
- def to_json(self, include_notebook=False): Convert ReportMetadata to a JSON
- def from_json(jsn): Create ReportMetadata fro... | Implement the Python class `ReportMetadataConfig` described below.
Class description:
Paperboy configuration object representing a Report (metadata component)
Method signatures and docstrings:
- def to_json(self, include_notebook=False): Convert ReportMetadata to a JSON
- def from_json(jsn): Create ReportMetadata fro... | b27bfdbb4ed27dea597ff1d6346eb831542ae81f | <|skeleton|>
class ReportMetadataConfig:
"""Paperboy configuration object representing a Report (metadata component)"""
def to_json(self, include_notebook=False):
"""Convert ReportMetadata to a JSON"""
<|body_0|>
def from_json(jsn):
"""Create ReportMetadata from a JSON"""
<... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReportMetadataConfig:
"""Paperboy configuration object representing a Report (metadata component)"""
def to_json(self, include_notebook=False):
"""Convert ReportMetadata to a JSON"""
ret = {}
ret = {}
ret['notebook'] = self.notebook.name
if include_notebook:
... | the_stack_v2_python_sparse | paperboy/config/report.py | timkpaine/paperboy | train | 245 |
bd7a6effe3a7fad1d55d8f505b61970c387c94ab | [
"self.type = 'FILL'\nself.timeindex = timeindex\nself.symbol = symbol\nself.exchange = exchange\nself.quantity = quantity\nself.direction = direction\nself.fill_cost = fill_cost\nif commission is None:\n self.commission = self.calculate_ib_commission()\nelse:\n self.commission = commission",
"full_cost = 1.... | <|body_start_0|>
self.type = 'FILL'
self.timeindex = timeindex
self.symbol = symbol
self.exchange = exchange
self.quantity = quantity
self.direction = direction
self.fill_cost = fill_cost
if commission is None:
self.commission = self.calculate_... | Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker. | FillEvent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillEvent:
"""Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker."""
def __init__(self, timeindex, symbol, exchange, quantity, ... | stack_v2_sparse_classes_75kplus_train_001684 | 5,389 | no_license | [
{
"docstring": "Inizializza l'oggetto FillEvent. Imposta il simbolo, il broker, la quantità, la direzione, il costo di esecuzione e una commissione opzionale. Se la commissione non viene fornita, l'oggetto Fill la calcola in base alla dimensione del trade e alle commissioni di Interactive Brokers. Parametri: ti... | 2 | stack_v2_sparse_classes_30k_train_053413 | Implement the Python class `FillEvent` described below.
Class description:
Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker.
Method signatures and docs... | Implement the Python class `FillEvent` described below.
Class description:
Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker.
Method signatures and docs... | 32853c951710d1562d7888173dc525e6b0a0f5fe | <|skeleton|>
class FillEvent:
"""Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker."""
def __init__(self, timeindex, symbol, exchange, quantity, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FillEvent:
"""Incorpora il concetto di un ordine eseguito, come restituito da un broker. Memorizza l'effettiva quantità scambiata di uno strumento e a quale prezzo. Inoltre, memorizza la commissione del trade applicata dal broker."""
def __init__(self, timeindex, symbol, exchange, quantity, direction, fi... | the_stack_v2_python_sparse | event/event.py | datatrading-info/DataBacktest | train | 3 |
f0843a41c841e4aa253e69e52108f76f2b915e5e | [
"viewManage.go_to_newtopic_page()\ntopicAction.add_topic('share', 'hello world', 'hello world')\ntitle_text = topicpage.title_text\nassert title_text == 'hello world'\ncontent_text = topicpage.content_text\nassert content_text == 'hello world'",
"viewManage.go_to_home_page()\nviewManage.go_to_user_center('testuse... | <|body_start_0|>
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'hello world')
title_text = topicpage.title_text
assert title_text == 'hello world'
content_text = topicpage.content_text
assert content_text == 'hello world'
<|end_body_0|>
<... | TestTmp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
<|body_0|>
def test_updatetopic(self):
"""更新话题 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'h... | stack_v2_sparse_classes_75kplus_train_001685 | 2,373 | no_license | [
{
"docstring": "测试创建话题 :return:",
"name": "test_newtopic",
"signature": "def test_newtopic(self)"
},
{
"docstring": "更新话题 :return:",
"name": "test_updatetopic",
"signature": "def test_updatetopic(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001323 | Implement the Python class `TestTmp` described below.
Class description:
Implement the TestTmp class.
Method signatures and docstrings:
- def test_newtopic(self): 测试创建话题 :return:
- def test_updatetopic(self): 更新话题 :return: | Implement the Python class `TestTmp` described below.
Class description:
Implement the TestTmp class.
Method signatures and docstrings:
- def test_newtopic(self): 测试创建话题 :return:
- def test_updatetopic(self): 更新话题 :return:
<|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
... | 1b039bb5cf4b92b63a947dcb9f10531cbf847b66 | <|skeleton|>
class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
<|body_0|>
def test_updatetopic(self):
"""更新话题 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestTmp:
def test_newtopic(self):
"""测试创建话题 :return:"""
viewManage.go_to_newtopic_page()
topicAction.add_topic('share', 'hello world', 'hello world')
title_text = topicpage.title_text
assert title_text == 'hello world'
content_text = topicpage.content_text
... | the_stack_v2_python_sparse | test_project/testcase/test_topics.py | jack-fjh/pytest_demo | train | 0 | |
75a0a4bae11c26714d94eea4764c6123834322d6 | [
"self._api_key = api_key\nself._app_secret = app_secret\nself._event = event\nself._tracker = tracker\nself._headers = {HTTP_HEADER_APPID: self._api_key, HTTP_HEADER_APPSECRET: self._app_secret, CONTENT_TYPE: CONTENT_TYPE_JSON}",
"title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)\ndata = {'event': self._event, '... | <|body_start_0|>
self._api_key = api_key
self._app_secret = app_secret
self._event = event
self._tracker = tracker
self._headers = {HTTP_HEADER_APPID: self._api_key, HTTP_HEADER_APPSECRET: self._app_secret, CONTENT_TYPE: CONTENT_TYPE_JSON}
<|end_body_0|>
<|body_start_1|>
... | Implementation of the notification service for Instapush. | InstapushNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstapushNotificationService:
"""Implementation of the notification service for Instapush."""
def __init__(self, api_key, app_secret, event, tracker):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a us... | stack_v2_sparse_classes_75kplus_train_001686 | 3,059 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, api_key, app_secret, event, tracker)"
},
{
"docstring": "Send a message to a user.",
"name": "send_message",
"signature": "def send_message(self, message='', **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026952 | Implement the Python class `InstapushNotificationService` described below.
Class description:
Implementation of the notification service for Instapush.
Method signatures and docstrings:
- def __init__(self, api_key, app_secret, event, tracker): Initialize the service.
- def send_message(self, message='', **kwargs): S... | Implement the Python class `InstapushNotificationService` described below.
Class description:
Implementation of the notification service for Instapush.
Method signatures and docstrings:
- def __init__(self, api_key, app_secret, event, tracker): Initialize the service.
- def send_message(self, message='', **kwargs): S... | 3838be4cb84cb4b7782af30150ff76faa970d7a4 | <|skeleton|>
class InstapushNotificationService:
"""Implementation of the notification service for Instapush."""
def __init__(self, api_key, app_secret, event, tracker):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstapushNotificationService:
"""Implementation of the notification service for Instapush."""
def __init__(self, api_key, app_secret, event, tracker):
"""Initialize the service."""
self._api_key = api_key
self._app_secret = app_secret
self._event = event
self._trac... | the_stack_v2_python_sparse | homeassistant/components/notify/instapush.py | bramkragten/home-assistant | train | 4 |
3a3d08afba5c5a3b24676f78e5f27075c77f863f | [
"def six_addr():\n ans = ''\n for i in range(6):\n tmp = letters[random.randint(0, 10000) % 62]\n ans = ans + tmp\n return ans\nif longUrl in full_tiny:\n return 'http://tinyurl.com/' + full_tiny[longUrl]\nelse:\n suffix = six_addr()\n full_tiny[longUrl] = suffix\n tiny_full[suffi... | <|body_start_0|>
def six_addr():
ans = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans = ans + tmp
return ans
if longUrl in full_tiny:
return 'http://tinyurl.com/' + full_tiny[longUrl]
else:
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def six_addr():
... | stack_v2_sparse_classes_75kplus_train_001687 | 1,066 | permissive | [
{
"docstring": "Encodes a URL to a shortened URL.",
"name": "encode",
"signature": "def encode(self, longUrl: str) -> str"
},
{
"docstring": "Decodes a shortened URL to its original URL.",
"name": "decode",
"signature": "def decode(self, shortUrl: str) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_015234 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, longUrl: str) -> str: Encodes a URL to a shortened URL.
- def decode(self, shortUrl: str) -> str: Decodes a shortened URL to its original URL.
<|skeleton|>
class Code... | 7754dcee38ffda18a5759113ef06d7becf4fe728 | <|skeleton|>
class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
<|body_0|>
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL."""
def six_addr():
ans = ''
for i in range(6):
tmp = letters[random.randint(0, 10000) % 62]
ans = ans + tmp
return ans
if longUrl in fu... | the_stack_v2_python_sparse | 535.py | RafaelHuang87/Leet-Code-Practice | train | 0 | |
12ec2034a9b71799a99823770d5df942f9f9ef0e | [
"if spec is None:\n return TamperingMethod()\nif spec == 'truncate':\n return TruncateTamperingMethod()\nif spec == 'mutate':\n return MutateTamperingMethod()\nif spec == 'half-sign':\n return HalfSigningTamperingMethod()\n(tampering_tag, tampering_values_spec), = spec.items()\nif tampering_tag == 'chan... | <|body_start_0|>
if spec is None:
return TamperingMethod()
if spec == 'truncate':
return TruncateTamperingMethod()
if spec == 'mutate':
return MutateTamperingMethod()
if spec == 'half-sign':
return HalfSigningTamperingMethod()
(tamp... | Base class for all tampering methods. | TamperingMethod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TamperingMethod:
"""Base class for all tampering methods."""
def from_tampering_spec(cls, spec):
"""Load from a tampering specification"""
<|body_0|>
def run_scenario_with_tampering(self, ciphertext_writer, generation_scenario, plaintext_uri):
"""Run a given scen... | stack_v2_sparse_classes_75kplus_train_001688 | 21,659 | permissive | [
{
"docstring": "Load from a tampering specification",
"name": "from_tampering_spec",
"signature": "def from_tampering_spec(cls, spec)"
},
{
"docstring": "Run a given scenario, tampering with the input or the result. return: a list of (ciphertext, result) pairs",
"name": "run_scenario_with_ta... | 2 | stack_v2_sparse_classes_30k_train_005320 | Implement the Python class `TamperingMethod` described below.
Class description:
Base class for all tampering methods.
Method signatures and docstrings:
- def from_tampering_spec(cls, spec): Load from a tampering specification
- def run_scenario_with_tampering(self, ciphertext_writer, generation_scenario, plaintext_u... | Implement the Python class `TamperingMethod` described below.
Class description:
Base class for all tampering methods.
Method signatures and docstrings:
- def from_tampering_spec(cls, spec): Load from a tampering specification
- def run_scenario_with_tampering(self, ciphertext_writer, generation_scenario, plaintext_u... | 3ba8019681ed95c41bb9448f0c3897d1aecc7559 | <|skeleton|>
class TamperingMethod:
"""Base class for all tampering methods."""
def from_tampering_spec(cls, spec):
"""Load from a tampering specification"""
<|body_0|>
def run_scenario_with_tampering(self, ciphertext_writer, generation_scenario, plaintext_uri):
"""Run a given scen... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TamperingMethod:
"""Base class for all tampering methods."""
def from_tampering_spec(cls, spec):
"""Load from a tampering specification"""
if spec is None:
return TamperingMethod()
if spec == 'truncate':
return TruncateTamperingMethod()
if spec == '... | the_stack_v2_python_sparse | test_vector_handlers/src/awses_test_vectors/manifests/full_message/decrypt_generation.py | aws/aws-encryption-sdk-python | train | 137 |
aa111b2bb6627e11b479cd5b986e182b36b01c98 | [
"send_url = self.get_peizhi_('Login', yaml_ming='yilou_fangdong.yaml')\nsend_url = send_url['send_verifcode']\nlogging.info('url is %s' % send_url)\ndict_send = {'mobile': mobile}\nresponse = self.request_post(send_url, dict_send)\nlogging.info(response)\nyanzhengma = self.get_YanZhengMa(mobile)\nif yanzhengma != N... | <|body_start_0|>
send_url = self.get_peizhi_('Login', yaml_ming='yilou_fangdong.yaml')
send_url = send_url['send_verifcode']
logging.info('url is %s' % send_url)
dict_send = {'mobile': mobile}
response = self.request_post(send_url, dict_send)
logging.info(response)
... | 登录 | Login | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Login:
"""登录"""
def login(self, mobile):
"""denglu"""
<|body_0|>
def send_verifcode(self, mobile):
"""发送验证码"""
<|body_1|>
def shuru_yanzhengma(self, mobile, Code):
"""输入验证码"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
sen... | stack_v2_sparse_classes_75kplus_train_001689 | 3,124 | no_license | [
{
"docstring": "denglu",
"name": "login",
"signature": "def login(self, mobile)"
},
{
"docstring": "发送验证码",
"name": "send_verifcode",
"signature": "def send_verifcode(self, mobile)"
},
{
"docstring": "输入验证码",
"name": "shuru_yanzhengma",
"signature": "def shuru_yanzhengma(... | 3 | stack_v2_sparse_classes_30k_train_031858 | Implement the Python class `Login` described below.
Class description:
登录
Method signatures and docstrings:
- def login(self, mobile): denglu
- def send_verifcode(self, mobile): 发送验证码
- def shuru_yanzhengma(self, mobile, Code): 输入验证码 | Implement the Python class `Login` described below.
Class description:
登录
Method signatures and docstrings:
- def login(self, mobile): denglu
- def send_verifcode(self, mobile): 发送验证码
- def shuru_yanzhengma(self, mobile, Code): 输入验证码
<|skeleton|>
class Login:
"""登录"""
def login(self, mobile):
"""den... | e173d4e535ac22b72b67371b8a2524ee425cdcbf | <|skeleton|>
class Login:
"""登录"""
def login(self, mobile):
"""denglu"""
<|body_0|>
def send_verifcode(self, mobile):
"""发送验证码"""
<|body_1|>
def shuru_yanzhengma(self, mobile, Code):
"""输入验证码"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Login:
"""登录"""
def login(self, mobile):
"""denglu"""
send_url = self.get_peizhi_('Login', yaml_ming='yilou_fangdong.yaml')
send_url = send_url['send_verifcode']
logging.info('url is %s' % send_url)
dict_send = {'mobile': mobile}
response = self.request_pos... | the_stack_v2_python_sparse | public/aYiLou_fangdong/yilou_fangdong_business/fangdongduan_login__.py | GSIL-Monitor/mrbao_python | train | 0 |
a026da9df5dadbf65066268f88dbdb186e9599c1 | [
"if patch_type is None:\n return CBPollPerformance.select().where(CBPollPerformance.cs == cs, CBPollPerformance.patch_type.is_null(True)).count()\nelse:\n return CBPollPerformance.select().where(CBPollPerformance.cs == cs, CBPollPerformance.patch_type == patch_type).count()",
"if patch_type is None:\n te... | <|body_start_0|>
if patch_type is None:
return CBPollPerformance.select().where(CBPollPerformance.cs == cs, CBPollPerformance.patch_type.is_null(True)).count()
else:
return CBPollPerformance.select().where(CBPollPerformance.cs == cs, CBPollPerformance.patch_type == patch_type).co... | Performance of a CB against a poll. | CBPollPerformance | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBPollPerformance:
"""Performance of a CB against a poll."""
def num_tested_polls(cls, cs, patch_type):
"""Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :param patch_type: Patch Type for which results need to be... | stack_v2_sparse_classes_75kplus_train_001690 | 2,620 | permissive | [
{
"docstring": "Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :param patch_type: Patch Type for which results need to be fetched. :return: num of tested polls",
"name": "num_tested_polls",
"signature": "def num_tested_polls(cls, cs... | 2 | stack_v2_sparse_classes_30k_train_050670 | Implement the Python class `CBPollPerformance` described below.
Class description:
Performance of a CB against a poll.
Method signatures and docstrings:
- def num_tested_polls(cls, cs, patch_type): Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :... | Implement the Python class `CBPollPerformance` described below.
Class description:
Performance of a CB against a poll.
Method signatures and docstrings:
- def num_tested_polls(cls, cs, patch_type): Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :... | 7d6bcbd94ab5ab521c29309fe3c47a0f6005a5d3 | <|skeleton|>
class CBPollPerformance:
"""Performance of a CB against a poll."""
def num_tested_polls(cls, cs, patch_type):
"""Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :param patch_type: Patch Type for which results need to be... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CBPollPerformance:
"""Performance of a CB against a poll."""
def num_tested_polls(cls, cs, patch_type):
"""Get number of tested polls on the provided CS and patch type :param cs: Challenge Set for num successful polls tested. :param patch_type: Patch Type for which results need to be fetched. :re... | the_stack_v2_python_sparse | farnsworth/models/cb_poll_performance.py | nnamon/farnsworth | train | 0 |
d6ca8dd435162d3a0bf9409e984136bf54671cd9 | [
"currency_code = currency_for_request(request)\ncurrency = Currency.objects.all_accepted().get(iso_4217_code=currency_code)\nserializer = CurrencySerializer(currency)\nreturn Response(serializer.data)",
"serializer = CurrencySessionSerializer(data=request.data)\nif serializer.is_valid():\n currency_code = seri... | <|body_start_0|>
currency_code = currency_for_request(request)
currency = Currency.objects.all_accepted().get(iso_4217_code=currency_code)
serializer = CurrencySerializer(currency)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = CurrencySessionSeria... | CurrencySessionAPIView | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurrencySessionAPIView:
def get(self, request, *args, **kwargs):
"""Return the currency for the request."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Set the currency in the session."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
curr... | stack_v2_sparse_classes_75kplus_train_001691 | 2,594 | permissive | [
{
"docstring": "Return the currency for the request.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Set the currency in the session.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_029509 | Implement the Python class `CurrencySessionAPIView` described below.
Class description:
Implement the CurrencySessionAPIView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the currency for the request.
- def post(self, request, *args, **kwargs): Set the currency in the sess... | Implement the Python class `CurrencySessionAPIView` described below.
Class description:
Implement the CurrencySessionAPIView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Return the currency for the request.
- def post(self, request, *args, **kwargs): Set the currency in the sess... | c2814749c547349ff63415bdc81f53eb1215c7c0 | <|skeleton|>
class CurrencySessionAPIView:
def get(self, request, *args, **kwargs):
"""Return the currency for the request."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Set the currency in the session."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CurrencySessionAPIView:
def get(self, request, *args, **kwargs):
"""Return the currency for the request."""
currency_code = currency_for_request(request)
currency = Currency.objects.all_accepted().get(iso_4217_code=currency_code)
serializer = CurrencySerializer(currency)
... | the_stack_v2_python_sparse | satchmo/currency/api/views.py | ToeKnee/jelly-roll | train | 0 | |
23b77cbfe62da71219b7e82bb51005c68f02fd03 | [
"if n == 0 or n == 1:\n return 0\nmax_val = 0\nfor i in range(1, n - 1):\n max_val = max(max_val, max(i * (n - i), i * self.maxProductCutRecursive(n - i)))\nreturn max_val",
"val = [0] * (n + 1)\nfor i in range(2, n + 1):\n max_prod = 0\n for j in range(1, i):\n max_prod = max(max_prod, j * (i ... | <|body_start_0|>
if n == 0 or n == 1:
return 0
max_val = 0
for i in range(1, n - 1):
max_val = max(max_val, max(i * (n - i), i * self.maxProductCutRecursive(n - i)))
return max_val
<|end_body_0|>
<|body_start_1|>
val = [0] * (n + 1)
for i in range... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProductCutRecursive(self, n: int) -> int:
"""Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters.... | stack_v2_sparse_classes_75kplus_train_001692 | 4,610 | no_license | [
{
"docstring": "Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters. Return the max product value. EG: n = 10 -> 3*3*4 is max, so output t... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProductCutRecursive(self, n: int) -> int: Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProductCutRecursive(self, n: int) -> int: Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of... | e1a4c1bc5d01b4e2ba51a5255deed6426557dcb0 | <|skeleton|>
class Solution:
def maxProductCutRecursive(self, n: int) -> int:
"""Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxProductCutRecursive(self, n: int) -> int:
"""Given a rope of length n meters, cut the rope in different parts of integer lengths in a way that maximizes product of lengths of all parts. You must make at least one cut. Assume that the length of rope is more than 2 meters. Return the ma... | the_stack_v2_python_sparse | quoraOA/maxCut.py | xuetingandyang/leetcode | train | 3 | |
630eb8b075d2ce5e8ba44ff5734c254a22dc6663 | [
"associations_to_create = []\nusers = list(users)\nusers_ids = [u.id for u in users]\nusers_already_added = video.users.filter(id__in=users_ids)\nusers_to_add = [u for u in users if u not in users_already_added]\nfor user in users_to_add:\n association = self.model(video=video, user=user)\n association.hash_k... | <|body_start_0|>
associations_to_create = []
users = list(users)
users_ids = [u.id for u in users]
users_already_added = video.users.filter(id__in=users_ids)
users_to_add = [u for u in users if u not in users_already_added]
for user in users_to_add:
associatio... | Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` and `remove()`. This Manager gives us back versions of those methods | VideoUsersManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoUsersManager:
"""Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` and `remove()`. This Manager gives us ba... | stack_v2_sparse_classes_75kplus_train_001693 | 36,145 | no_license | [
{
"docstring": "Associate users with a given video's collection of users Args: video: video to associate users with users: 0 or more user objects to add to video.users Returns: A list of the created VideoUser objects",
"name": "add_users_to_video",
"signature": "def add_users_to_video(self, video, *user... | 2 | null | Implement the Python class `VideoUsersManager` described below.
Class description:
Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` a... | Implement the Python class `VideoUsersManager` described below.
Class description:
Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` a... | 1f4b4cd74c9b4280437f73bdfef4491536194eeb | <|skeleton|>
class VideoUsersManager:
"""Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` and `remove()`. This Manager gives us ba... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VideoUsersManager:
"""Custom Model Manager for VideoUsers class. We are using VideoUsers as a through-table for the many-to-many relationship between videos and users. This means we lose the default django convenience methods defined on M2M fields, `add()` and `remove()`. This Manager gives us back versions o... | the_stack_v2_python_sparse | gravvy/apps/video/models.py | nceruchalu/gravvy-server | train | 1 |
519a9cfed28371bb4bc4c8b24648392060504200 | [
"digit = []\nroman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC', 300: 'CCC', 400: 'CD', 500: 'D', 600: 'DC', 700: 'DCC', 800: 'DCCC', 900: 'CM', 1000: 'M', 2000: '... | <|body_start_0|>
digit = []
roman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC', 300: 'CCC', 400: 'CD', 500: 'D', 600: 'DC', 700: 'DCC', 800: 'DCCC', 90... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intToRoman(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
digit = []
roman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: ... | stack_v2_sparse_classes_75kplus_train_001694 | 1,710 | permissive | [
{
"docstring": ":type num: int :rtype: str",
"name": "intToRoman",
"signature": "def intToRoman(self, num)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "romanToInt",
"signature": "def romanToInt(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013024 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intToRoman(self, num): :type num: int :rtype: str
- def romanToInt(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intToRoman(self, num): :type num: int :rtype: str
- def romanToInt(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def intToRoman(self, num):
""... | 38eb0556f865fd06f517ca45253d00aaca39d70b | <|skeleton|>
class Solution:
def intToRoman(self, num):
""":type num: int :rtype: str"""
<|body_0|>
def romanToInt(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def intToRoman(self, num):
""":type num: int :rtype: str"""
digit = []
roman = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50: 'L', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC', ... | the_stack_v2_python_sparse | Python3/no12_Integer_to_Roman.py | yif042/leetcode | train | 0 | |
f45fff8b0df7c4d591b4dedf223c0cb50e7bd34b | [
"self.origine = origine\nself.x = axex\nself.y = axey\nself.z = axez",
"res = copy.copy(self.origine)\nres.x += v.x * self.x.x + v.y * self.y.x + v.z * self.z.x\nres.y += v.x * self.x.y + v.y * self.y.y + v.z * self.z.y\nres.z += v.x * self.x.z + v.y * self.y.z + v.z * self.z.z\nreturn res",
"s = 'origine : ' +... | <|body_start_0|>
self.origine = origine
self.x = axex
self.y = axey
self.z = axez
<|end_body_0|>
<|body_start_1|>
res = copy.copy(self.origine)
res.x += v.x * self.x.x + v.y * self.y.x + v.z * self.z.x
res.y += v.x * self.x.y + v.y * self.y.y + v.z * self.z.y
... | définition d'un repère orthonormé | Repere | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repere:
"""définition d'un repère orthonormé"""
def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
<|body_0|>
def coordonnees(self, v):
"""on suppose q... | stack_v2_sparse_classes_75kplus_train_001695 | 8,673 | permissive | [
{
"docstring": "initialisation, origine et les trois axes",
"name": "__init__",
"signature": "def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1))"
},
{
"docstring": "on suppose que les coordonnées de v sont exprimées dans ce repère, c... | 3 | null | Implement the Python class `Repere` described below.
Class description:
définition d'un repère orthonormé
Method signatures and docstrings:
- def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1)): initialisation, origine et les trois axes
- def coordonnees(s... | Implement the Python class `Repere` described below.
Class description:
définition d'un repère orthonormé
Method signatures and docstrings:
- def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1)): initialisation, origine et les trois axes
- def coordonnees(s... | 2abbc7a20c7437f9ab91d1ec83a6aecdefceb028 | <|skeleton|>
class Repere:
"""définition d'un repère orthonormé"""
def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
<|body_0|>
def coordonnees(self, v):
"""on suppose q... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Repere:
"""définition d'un repère orthonormé"""
def __init__(self, origine=Vecteur(0, 0, 0), axex=Vecteur(1, 0, 0), axey=Vecteur(0, 1, 0), axez=Vecteur(0, 0, 1)):
"""initialisation, origine et les trois axes"""
self.origine = origine
self.x = axex
self.y = axey
sel... | the_stack_v2_python_sparse | src/ensae_teaching_cs/special/image/image_synthese_base.py | Pandinosaurus/ensae_teaching_cs | train | 1 |
898844c574a735ddd0b2c73f92daf849c700c4e1 | [
"adm = ApplikationsAdministration()\neintrag = adm.get_listeneintrag_by_id(id)\nadm.delete_listeneintrag(eintrag)\nreturn eintrag",
"adm = ApplikationsAdministration()\neintrag = Listeneintrag.from_dict(api.payload)\nif eintrag is not None:\n eintrag.set_id(id)\n eintrag.set_aenderungs_zeitpunkt_now()\n ... | <|body_start_0|>
adm = ApplikationsAdministration()
eintrag = adm.get_listeneintrag_by_id(id)
adm.delete_listeneintrag(eintrag)
return eintrag
<|end_body_0|>
<|body_start_1|>
adm = ApplikationsAdministration()
eintrag = Listeneintrag.from_dict(api.payload)
if ein... | ListeneintragOperations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
<|body_0|>
def put(self, id):
"""Update eines durch eine id bestimmten Listeneintrag"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
adm = Applikation... | stack_v2_sparse_classes_75kplus_train_001696 | 23,456 | no_license | [
{
"docstring": "Löschen eines Listeneintrages anhand einer id",
"name": "delete",
"signature": "def delete(self, id)"
},
{
"docstring": "Update eines durch eine id bestimmten Listeneintrag",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000008 | Implement the Python class `ListeneintragOperations` described below.
Class description:
Implement the ListeneintragOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen eines Listeneintrages anhand einer id
- def put(self, id): Update eines durch eine id bestimmten Listeneintrag | Implement the Python class `ListeneintragOperations` described below.
Class description:
Implement the ListeneintragOperations class.
Method signatures and docstrings:
- def delete(self, id): Löschen eines Listeneintrages anhand einer id
- def put(self, id): Update eines durch eine id bestimmten Listeneintrag
<|skel... | d4a2b196f21a5379188cb78b31c59d69f739964f | <|skeleton|>
class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
<|body_0|>
def put(self, id):
"""Update eines durch eine id bestimmten Listeneintrag"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ListeneintragOperations:
def delete(self, id):
"""Löschen eines Listeneintrages anhand einer id"""
adm = ApplikationsAdministration()
eintrag = adm.get_listeneintrag_by_id(id)
adm.delete_listeneintrag(eintrag)
return eintrag
def put(self, id):
"""Update ein... | the_stack_v2_python_sparse | src/main.py | SvenjaHolzinger/SoftwarePraktikum | train | 0 | |
31d7b448d555286c387ebbbb43a57751951a23e0 | [
"headers = DEFAULT_HEADERS\nif (etag := kwargs.get('etag')) is not None:\n headers[IF_NONE_MATCH] = f'W/\"{etag}\"'\nrequest = await self.session.get(url=URL, headers=headers, timeout=ClientTimeout(total=self.timeout))\nself._etag = request.headers.get('etag')\nif request.status == 304:\n raise HaVersionNotMo... | <|body_start_0|>
headers = DEFAULT_HEADERS
if (etag := kwargs.get('etag')) is not None:
headers[IF_NONE_MATCH] = f'W/"{etag}"'
request = await self.session.get(url=URL, headers=headers, timeout=ClientTimeout(total=self.timeout))
self._etag = request.headers.get('etag')
... | Handle versions for the PyPi source. | HaVersionPypi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HaVersionPypi:
"""Handle versions for the PyPi source."""
async def fetch(self, **kwargs):
"""Logic to fetch new version data."""
<|body_0|>
def parse(self):
"""Logic to parse new version data."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hea... | stack_v2_sparse_classes_75kplus_train_001697 | 1,657 | permissive | [
{
"docstring": "Logic to fetch new version data.",
"name": "fetch",
"signature": "async def fetch(self, **kwargs)"
},
{
"docstring": "Logic to parse new version data.",
"name": "parse",
"signature": "def parse(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_027643 | Implement the Python class `HaVersionPypi` described below.
Class description:
Handle versions for the PyPi source.
Method signatures and docstrings:
- async def fetch(self, **kwargs): Logic to fetch new version data.
- def parse(self): Logic to parse new version data. | Implement the Python class `HaVersionPypi` described below.
Class description:
Handle versions for the PyPi source.
Method signatures and docstrings:
- async def fetch(self, **kwargs): Logic to fetch new version data.
- def parse(self): Logic to parse new version data.
<|skeleton|>
class HaVersionPypi:
"""Handle... | eea1272644065b5745f890ca6403361035c85acc | <|skeleton|>
class HaVersionPypi:
"""Handle versions for the PyPi source."""
async def fetch(self, **kwargs):
"""Logic to fetch new version data."""
<|body_0|>
def parse(self):
"""Logic to parse new version data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HaVersionPypi:
"""Handle versions for the PyPi source."""
async def fetch(self, **kwargs):
"""Logic to fetch new version data."""
headers = DEFAULT_HEADERS
if (etag := kwargs.get('etag')) is not None:
headers[IF_NONE_MATCH] = f'W/"{etag}"'
request = await self.... | the_stack_v2_python_sparse | pyhaversion/pypi.py | ludeeus/pyhaversion | train | 5 |
1476efeb3e657995a52da993a83b207470af6553 | [
"re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])\nresult = re\nAssertions().assert_in_text(result, expect['mockCarOutMessage'])",
"re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], send_data['carOutHandleType'], send_data['carOut_jobId'])\nresult = re\... | <|body_start_0|>
re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarOutMessage'])
<|end_body_0|>
<|body_start_1|>
re = CarInOutHandle(sentryLogin).carInOutHandle(send_data['carNum'], s... | 临时车无在场需缴费宽出(岗亭收费处收费放行) | TestCarOutNoInside | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
<|body_0|>
def test_sentryAbnormalPay(self, sentryLogin, send_data, expect):
"""岗亭端收费异常放行"""
<|body_1|>
def test_carLeaveHistory(self... | stack_v2_sparse_classes_75kplus_train_001698 | 1,943 | no_license | [
{
"docstring": "离场",
"name": "test_mockCarOut",
"signature": "def test_mockCarOut(self, sentryLogin, send_data, expect)"
},
{
"docstring": "岗亭端收费异常放行",
"name": "test_sentryAbnormalPay",
"signature": "def test_sentryAbnormalPay(self, sentryLogin, send_data, expect)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_035653 | Implement the Python class `TestCarOutNoInside` described below.
Class description:
临时车无在场需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarOut(self, sentryLogin, send_data, expect): 离场
- def test_sentryAbnormalPay(self, sentryLogin, send_data, expect): 岗亭端收费异常放行
- def test_carLeaveHistory(self, us... | Implement the Python class `TestCarOutNoInside` described below.
Class description:
临时车无在场需缴费宽出(岗亭收费处收费放行)
Method signatures and docstrings:
- def test_mockCarOut(self, sentryLogin, send_data, expect): 离场
- def test_sentryAbnormalPay(self, sentryLogin, send_data, expect): 岗亭端收费异常放行
- def test_carLeaveHistory(self, us... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
<|body_0|>
def test_sentryAbnormalPay(self, sentryLogin, send_data, expect):
"""岗亭端收费异常放行"""
<|body_1|>
def test_carLeaveHistory(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestCarOutNoInside:
"""临时车无在场需缴费宽出(岗亭收费处收费放行)"""
def test_mockCarOut(self, sentryLogin, send_data, expect):
"""离场"""
re = cloudparking_service().mockCarInOut(send_data['carNum'], 1, send_data['outClientID'])
result = re
Assertions().assert_in_text(result, expect['mockCarOu... | the_stack_v2_python_sparse | test_suite/sentryDutyRoom/carInOutHandle/test_carOutNoInside.py | oyebino/pomp_api | train | 1 |
e804cbc4743f9116f09feae4823ea611fa4ad352 | [
"answer, tmp = (nums[0], 0)\nl, r = (0, 0)\nwhile r < len(nums):\n tmp += nums[r]\n answer = max(answer, tmp)\n r += 1\n if tmp < 0:\n tmp, l = (0, r)\nreturn answer",
"self.answer = nums[0]\n\ndef divide_and_conquer(k):\n if k == 0:\n return nums[0]\n tmp = divide_and_conquer(k - ... | <|body_start_0|>
answer, tmp = (nums[0], 0)
l, r = (0, 0)
while r < len(nums):
tmp += nums[r]
answer = max(answer, tmp)
r += 1
if tmp < 0:
tmp, l = (0, r)
return answer
<|end_body_0|>
<|body_start_1|>
self.answer = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArrayLinear(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
answer, tmp = (nums[0], 0)
l, r... | stack_v2_sparse_classes_75kplus_train_001699 | 973 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArrayLinear",
"signature": "def maxSubArrayLinear(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray",
"signature": "def maxSubArray(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArrayLinear(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArrayLinear(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSu... | 64b9e452371d989f6061d89c6b96af2ba7fe5990 | <|skeleton|>
class Solution:
def maxSubArrayLinear(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxSubArrayLinear(self, nums):
""":type nums: List[int] :rtype: int"""
answer, tmp = (nums[0], 0)
l, r = (0, 0)
while r < len(nums):
tmp += nums[r]
answer = max(answer, tmp)
r += 1
if tmp < 0:
tmp, l ... | the_stack_v2_python_sparse | 51-100/53.py | hurenjun/LeetCode | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.