blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cd66ab4a8c2b5a1c4847b517486b38540457e69 | [
"self.rotateByDegrees_(angle)\ntf = NSAffineTransform.transform()\ntf.rotateByDegrees_(-angle)\noldPt = tf.transformPoint_(point)\noldPt.x -= point.x\noldPt.y -= point.y\nself.translateXBy_yBy_(oldPt.x, oldPt.y)",
"self.rotateByRadians_(angle)\ntf = NSAffineTransform.transform()\ntf.rotateByRadians_(-angle)\noldP... | <|body_start_0|>
self.rotateByDegrees_(angle)
tf = NSAffineTransform.transform()
tf.rotateByDegrees_(-angle)
oldPt = tf.transformPoint_(point)
oldPt.x -= point.x
oldPt.y -= point.y
self.translateXBy_yBy_(oldPt.x, oldPt.y)
<|end_body_0|>
<|body_start_1|>
s... | NSAffineTransform | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSAffineTransform:
def rotateByDegrees_atPoint_(self, angle, point):
"""Rotate the coordinatespace ``angle`` degrees around ``point``."""
<|body_0|>
def rotateByRadians_atPoint_(self, angle, point):
"""Rotate the coordinatespace ``angle`` radians around ``point``."""... | stack_v2_sparse_classes_36k_train_001700 | 1,027 | permissive | [
{
"docstring": "Rotate the coordinatespace ``angle`` degrees around ``point``.",
"name": "rotateByDegrees_atPoint_",
"signature": "def rotateByDegrees_atPoint_(self, angle, point)"
},
{
"docstring": "Rotate the coordinatespace ``angle`` radians around ``point``.",
"name": "rotateByRadians_at... | 2 | stack_v2_sparse_classes_30k_train_014966 | Implement the Python class `NSAffineTransform` described below.
Class description:
Implement the NSAffineTransform class.
Method signatures and docstrings:
- def rotateByDegrees_atPoint_(self, angle, point): Rotate the coordinatespace ``angle`` degrees around ``point``.
- def rotateByRadians_atPoint_(self, angle, poi... | Implement the Python class `NSAffineTransform` described below.
Class description:
Implement the NSAffineTransform class.
Method signatures and docstrings:
- def rotateByDegrees_atPoint_(self, angle, point): Rotate the coordinatespace ``angle`` degrees around ``point``.
- def rotateByRadians_atPoint_(self, angle, poi... | 375ab43104712c5e1c782e5ea5f04073b5f8916c | <|skeleton|>
class NSAffineTransform:
def rotateByDegrees_atPoint_(self, angle, point):
"""Rotate the coordinatespace ``angle`` degrees around ``point``."""
<|body_0|>
def rotateByRadians_atPoint_(self, angle, point):
"""Rotate the coordinatespace ``angle`` radians around ``point``."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NSAffineTransform:
def rotateByDegrees_atPoint_(self, angle, point):
"""Rotate the coordinatespace ``angle`` degrees around ``point``."""
self.rotateByDegrees_(angle)
tf = NSAffineTransform.transform()
tf.rotateByDegrees_(-angle)
oldPt = tf.transformPoint_(point)
... | the_stack_v2_python_sparse | venv/lib/python3.7/site-packages/PyObjCTools/FndCategories.py | ykhade/Advent_Of_Code_2019 | train | 1 | |
efcf1122ba0e143d0cbe72a202c8098a5eaac205 | [
"self.__repository = phone_repository\nself.__unit_of_work = unit_of_work\nself.__event_bus = event_bus",
"phone_id = PhoneID(create_phone_command.id)\nnumber = Number(create_phone_command.number)\nextension = Extension(create_phone_command.extension)\nphone_number_entity = PhoneCreatorService.create_phone_entity... | <|body_start_0|>
self.__repository = phone_repository
self.__unit_of_work = unit_of_work
self.__event_bus = event_bus
<|end_body_0|>
<|body_start_1|>
phone_id = PhoneID(create_phone_command.id)
number = Number(create_phone_command.number)
extension = Extension(create_pho... | PhoneCreator | PhoneCreator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhoneCreator:
"""PhoneCreator"""
def __init__(self, phone_repository: PhoneRepository, unit_of_work: UnitOfWork, event_bus: EventBus):
"""Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.persons.domain.repository.PhoneRepository @param unit_of_w... | stack_v2_sparse_classes_36k_train_001701 | 2,336 | permissive | [
{
"docstring": "Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.persons.domain.repository.PhoneRepository @param unit_of_work: Unit of work @type unit_of_work: modules.shared.domain.repository.PhoneRepository @param message_bus: @type message_bus:",
"name": "__init__"... | 2 | stack_v2_sparse_classes_30k_train_021277 | Implement the Python class `PhoneCreator` described below.
Class description:
PhoneCreator
Method signatures and docstrings:
- def __init__(self, phone_repository: PhoneRepository, unit_of_work: UnitOfWork, event_bus: EventBus): Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.p... | Implement the Python class `PhoneCreator` described below.
Class description:
PhoneCreator
Method signatures and docstrings:
- def __init__(self, phone_repository: PhoneRepository, unit_of_work: UnitOfWork, event_bus: EventBus): Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.p... | 8055927cb460bc40f3a2651c01a9d1da696177e8 | <|skeleton|>
class PhoneCreator:
"""PhoneCreator"""
def __init__(self, phone_repository: PhoneRepository, unit_of_work: UnitOfWork, event_bus: EventBus):
"""Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.persons.domain.repository.PhoneRepository @param unit_of_w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhoneCreator:
"""PhoneCreator"""
def __init__(self, phone_repository: PhoneRepository, unit_of_work: UnitOfWork, event_bus: EventBus):
"""Phone Creator @param phone_repository: Phone repository @type phone_repository: modules.persons.domain.repository.PhoneRepository @param unit_of_work: Unit of ... | the_stack_v2_python_sparse | modules/persons/application/create/phone_creator.py | eduardolujan/hexagonal_architecture_django | train | 5 |
4009f1adddb7dfee2b442da308572a635616057e | [
"if not nums:\n return -1\nlo = 0\nhi = len(nums) - 1\nold_size = len(nums)\nif nums[lo] <= nums[hi]:\n return self.binary_search(nums, lo, hi + 1, target)\nelse:\n while nums[lo] > nums[hi]:\n lo = hi\n hi -= 1\n nums += nums[:hi + 1]\n re = self.binary_search(nums, lo, len(nums), targ... | <|body_start_0|>
if not nums:
return -1
lo = 0
hi = len(nums) - 1
old_size = len(nums)
if nums[lo] <= nums[hi]:
return self.binary_search(nums, lo, hi + 1, target)
else:
while nums[lo] > nums[hi]:
lo = hi
... | Solution | [
"WTFPL"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def binary_search(self, array, low, high, target):
"""low: dtype int, index of lowest int high: dtype int, index of highest int target: dtype int, the int w... | stack_v2_sparse_classes_36k_train_001702 | 1,270 | permissive | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search",
"signature": "def search(self, nums, target)"
},
{
"docstring": "low: dtype int, index of lowest int high: dtype int, index of highest int target: dtype int, the int we search for this function is a normal bi... | 2 | stack_v2_sparse_classes_30k_train_001441 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def binary_search(self, array, low, high, target): low: dtype int, index of lowest int high:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def binary_search(self, array, low, high, target): low: dtype int, index of lowest int high:... | 2677b6d26bedb9bc6c6137a2392d0afaceb91ec2 | <|skeleton|>
class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def binary_search(self, array, low, high, target):
"""low: dtype int, index of lowest int high: dtype int, index of highest int target: dtype int, the int w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def search(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
if not nums:
return -1
lo = 0
hi = len(nums) - 1
old_size = len(nums)
if nums[lo] <= nums[hi]:
return self.binary_search(nums, lo, hi + 1,... | the_stack_v2_python_sparse | search_rotated_sorted_array/solution.py | haotianzhu/Questions_Solutions | train | 0 | |
3a4b872a33d4449b1c7439576e86573beb9d5f7e | [
"if not root:\n return []\nret = []\nq = [[root], []]\ni = 0\nwhile q[0] or q[1]:\n level = []\n j = (i + 1) % 2\n while q[i]:\n n = q[i].pop(0)\n level.append(n.val)\n if n.left:\n q[j].append(n.left)\n if n.right:\n q[j].append(n.right)\n if i % 2 =... | <|body_start_0|>
if not root:
return []
ret = []
q = [[root], []]
i = 0
while q[0] or q[1]:
level = []
j = (i + 1) % 2
while q[i]:
n = q[i].pop(0)
level.append(n.val)
if n.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def zigzagLevelOrder(self, root):
"""May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
"""Mar 22, 2023 00:13"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_001703 | 2,778 | no_license | [
{
"docstring": "May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]",
"name": "zigzagLevelOrder",
"signature": "def zigzagLevelOrder(self, root)"
},
{
"docstring": "Mar 22, 2023 00:13",
"name": "zigzagLevelOrder",
"signature": "def zigzagLevelOrder(self, root: Optional[TreeNo... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def zigzagLevelOrder(self, root): May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]
- def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: Mar 2... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def zigzagLevelOrder(self, root): May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]
- def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: Mar 2... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def zigzagLevelOrder(self, root):
"""May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]"""
<|body_0|>
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
"""Mar 22, 2023 00:13"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def zigzagLevelOrder(self, root):
"""May 06, 2018 06:44 :type root: TreeNode :rtype: List[List[int]]"""
if not root:
return []
ret = []
q = [[root], []]
i = 0
while q[0] or q[1]:
level = []
j = (i + 1) % 2
... | the_stack_v2_python_sparse | leetcode/solved/103_Binary_Tree_Zigzag_Level_Order_Traversal/solution.py | sungminoh/algorithms | train | 0 | |
3a31009a3d6a71eeda31ed4d942766d16d687c47 | [
"from app.services.users.groups import GroupFactory\ngroup_factory = GroupFactory(model)\nif group_factory.check_soft_delete():\n return\nif is_created is True:\n group_factory.add_group()\nelse:\n group_factory.modify_group()\nsuper().on_model_change(form, model, is_created)",
"from app.services.users.g... | <|body_start_0|>
from app.services.users.groups import GroupFactory
group_factory = GroupFactory(model)
if group_factory.check_soft_delete():
return
if is_created is True:
group_factory.add_group()
else:
group_factory.modify_group()
sup... | 用户组管理 | GroupModelView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupModelView:
"""用户组管理"""
def on_model_change(self, form, model, is_created):
"""创建修改组时"""
<|body_0|>
def delete_model(self, model):
"""删除组时"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from app.services.users.groups import GroupFactory
... | stack_v2_sparse_classes_36k_train_001704 | 5,835 | permissive | [
{
"docstring": "创建修改组时",
"name": "on_model_change",
"signature": "def on_model_change(self, form, model, is_created)"
},
{
"docstring": "删除组时",
"name": "delete_model",
"signature": "def delete_model(self, model)"
}
] | 2 | null | Implement the Python class `GroupModelView` described below.
Class description:
用户组管理
Method signatures and docstrings:
- def on_model_change(self, form, model, is_created): 创建修改组时
- def delete_model(self, model): 删除组时 | Implement the Python class `GroupModelView` described below.
Class description:
用户组管理
Method signatures and docstrings:
- def on_model_change(self, form, model, is_created): 创建修改组时
- def delete_model(self, model): 删除组时
<|skeleton|>
class GroupModelView:
"""用户组管理"""
def on_model_change(self, form, model, is_... | 4f866b2264e224389c99bbbdb4521f4b0799b2a3 | <|skeleton|>
class GroupModelView:
"""用户组管理"""
def on_model_change(self, form, model, is_created):
"""创建修改组时"""
<|body_0|>
def delete_model(self, model):
"""删除组时"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupModelView:
"""用户组管理"""
def on_model_change(self, form, model, is_created):
"""创建修改组时"""
from app.services.users.groups import GroupFactory
group_factory = GroupFactory(model)
if group_factory.check_soft_delete():
return
if is_created is True:
... | the_stack_v2_python_sparse | admin/views/users.py | ssfdust/full-stack-flask-smorest | train | 39 |
79fdb3240c72c7ac648a1e2b9b775367d6bcc505 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn Windows10SecureAssessmentConfiguration()",
"from .device_configuration import DeviceConfiguration\nfrom .device_configuration import DeviceConfiguration\nfields: Dict[str, Callable[[Any], None]] = {'allowPrinting': lambda n: setattr(se... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return Windows10SecureAssessmentConfiguration()
<|end_body_0|>
<|body_start_1|>
from .device_configuration import DeviceConfiguration
from .device_configuration import DeviceConfiguration
... | This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource. | Windows10SecureAssessmentConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Windows10SecureAssessmentConfiguration:
"""This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Windows10SecureAssessmentConfiguration:
... | stack_v2_sparse_classes_36k_train_001705 | 3,847 | 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: Windows10SecureAssessmentConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create... | 3 | null | Implement the Python class `Windows10SecureAssessmentConfiguration` described below.
Class description:
This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: O... | Implement the Python class `Windows10SecureAssessmentConfiguration` described below.
Class description:
This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: O... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class Windows10SecureAssessmentConfiguration:
"""This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Windows10SecureAssessmentConfiguration:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Windows10SecureAssessmentConfiguration:
"""This topic provides descriptions of the declared methods, properties and relationships exposed by the secureAssessment resource."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> Windows10SecureAssessmentConfiguration:
"""Cr... | the_stack_v2_python_sparse | msgraph/generated/models/windows10_secure_assessment_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
7beb43cc03f22cf483e046d6f83af5835f13256a | [
"if encoding is None:\n encoding = DEFAULT_ENCODING\nself.encoding = encoding\nself.object_hook = object_hook\nself.object_pairs_hook = object_pairs_hook\nself.parse_float = parse_float or float\nself.parse_int = parse_int or int\nself.strict = strict\nself.parse_object = JSONObject\nself.parse_array = JSONArray... | <|body_start_0|>
if encoding is None:
encoding = DEFAULT_ENCODING
self.encoding = encoding
self.object_hook = object_hook
self.object_pairs_hook = object_pairs_hook
self.parse_float = parse_float or float
self.parse_int = parse_int or int
self.strict =... | Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | str, unicode | +--------------... | HjsonDecoder | [
"Apache-2.0",
"Python-2.0",
"AFL-2.1",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HjsonDecoder:
"""Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ |... | stack_v2_sparse_classes_36k_train_001706 | 19,552 | permissive | [
{
"docstring": "*encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be pas... | 3 | null | Implement the Python class `HjsonDecoder` described below.
Class description:
Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | ... | Implement the Python class `HjsonDecoder` described below.
Class description:
Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | ... | d59c99dcdcd280d7eec36a693dd80f8c8c831ea2 | <|skeleton|>
class HjsonDecoder:
"""Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ |... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HjsonDecoder:
"""Hjson decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | str... | the_stack_v2_python_sparse | modules/dbnd/src/dbnd/_vendor/hjson/decoder.py | databand-ai/dbnd | train | 257 |
9a78f89c499c09412a9cb8b91e23ab724b40a2a3 | [
"self.cap = capacity\nself.key2node = {}\nself.count2node = defaultdict(OrderedDict)\nself.minCount = None",
"if key not in self.key2node:\n return -1\nnode = self.key2node[key]\ndel self.count2node[node.count][key]\nif not self.count2node[node.count]:\n del self.count2node[node.count]\nnode.count += 1\nsel... | <|body_start_0|>
self.cap = capacity
self.key2node = {}
self.count2node = defaultdict(OrderedDict)
self.minCount = None
<|end_body_0|>
<|body_start_1|>
if key not in self.key2node:
return -1
node = self.key2node[key]
del self.count2node[node.count][ke... | LFUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_001707 | 3,596 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LFUCache` described below.
Class description:
Implement the LFUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 59f70dc4466e15df591ba285317e4a1fe808ed60 | <|skeleton|>
class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LFUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.cap = capacity
self.key2node = {}
self.count2node = defaultdict(OrderedDict)
self.minCount = None
def get(self, key):
""":type key: int :rtype: int"""
if key not in self.key2node... | the_stack_v2_python_sparse | leet/Design/460_LFU_Cache.py | arsamigullin/problem_solving_python | train | 0 | |
e4d363a40065584e3c9b6bf5d4438188f09440e6 | [
"l_s, l_t = (len(s), len(t))\ns_skip, t_skip = (False, False)\nif abs(l_s - l_t) > 1:\n return False\nelif abs(l_s - l_t) == 1:\n if l_s < l_t:\n t_skip = True\n else:\n s_skip = True\ni = j = count = 0\nwhile i < l_s and j < l_t:\n if count > 1:\n return False\n elif s[i] != t[j... | <|body_start_0|>
l_s, l_t = (len(s), len(t))
s_skip, t_skip = (False, False)
if abs(l_s - l_t) > 1:
return False
elif abs(l_s - l_t) == 1:
if l_s < l_t:
t_skip = True
else:
s_skip = True
i = j = count = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isOneEditDistance(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isOneEditDistance2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l_s, l_t = (len(s), le... | stack_v2_sparse_classes_36k_train_001708 | 1,532 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isOneEditDistance",
"signature": "def isOneEditDistance(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isOneEditDistance2",
"signature": "def isOneEditDistance2(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): :type s: str :type t: str :rtype: bool
- def isOneEditDistance2(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isOneEditDistance(self, s, t): :type s: str :type t: str :rtype: bool
- def isOneEditDistance2(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solutio... | e12025e754547d18d5bb50a9dbe5e725fd03fd9c | <|skeleton|>
class Solution:
def isOneEditDistance(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isOneEditDistance2(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isOneEditDistance(self, s, t):
""":type s: str :type t: str :rtype: bool"""
l_s, l_t = (len(s), len(t))
s_skip, t_skip = (False, False)
if abs(l_s - l_t) > 1:
return False
elif abs(l_s - l_t) == 1:
if l_s < l_t:
t_sk... | the_stack_v2_python_sparse | leetcode/161one_edit_distance.py | clovery410/mycode | train | 1 | |
4a9ac082e0c734e0f22dd9679562f00b079808ba | [
"table_name = name\nusername = request.user.username\nerror, workspace, dtable = _resource_check(workspace_id, table_name)\nif error:\n return error\nowner = workspace.owner\nerror = _permission_check_for_api_token(username, owner)\nif error:\n return error\napi_tokens = list()\ntry:\n api_token_queryset =... | <|body_start_0|>
table_name = name
username = request.user.username
error, workspace, dtable = _resource_check(workspace_id, table_name)
if error:
return error
owner = workspace.owner
error = _permission_check_for_api_token(username, owner)
if error:
... | DTableAPITokensView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DTableAPITokensView:
def get(self, request, workspace_id, name):
"""list dtable api token for thirdpart app"""
<|body_0|>
def post(self, request, workspace_id, name):
"""generate dtable api token"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
table... | stack_v2_sparse_classes_36k_train_001709 | 18,184 | no_license | [
{
"docstring": "list dtable api token for thirdpart app",
"name": "get",
"signature": "def get(self, request, workspace_id, name)"
},
{
"docstring": "generate dtable api token",
"name": "post",
"signature": "def post(self, request, workspace_id, name)"
}
] | 2 | null | Implement the Python class `DTableAPITokensView` described below.
Class description:
Implement the DTableAPITokensView class.
Method signatures and docstrings:
- def get(self, request, workspace_id, name): list dtable api token for thirdpart app
- def post(self, request, workspace_id, name): generate dtable api token | Implement the Python class `DTableAPITokensView` described below.
Class description:
Implement the DTableAPITokensView class.
Method signatures and docstrings:
- def get(self, request, workspace_id, name): list dtable api token for thirdpart app
- def post(self, request, workspace_id, name): generate dtable api token... | 3d08b64bf2a3724326eab9dfa771863bc6743bc2 | <|skeleton|>
class DTableAPITokensView:
def get(self, request, workspace_id, name):
"""list dtable api token for thirdpart app"""
<|body_0|>
def post(self, request, workspace_id, name):
"""generate dtable api token"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DTableAPITokensView:
def get(self, request, workspace_id, name):
"""list dtable api token for thirdpart app"""
table_name = name
username = request.user.username
error, workspace, dtable = _resource_check(workspace_id, table_name)
if error:
return error
... | the_stack_v2_python_sparse | seahub/api2/endpoints/dtable_api_token.py | flazx/dtable-web | train | 0 | |
6ebf328484aad8dd6c9f53dc8cdcf9f09b39f53c | [
"cameraDTO = request.json\ncameraManager.postCamera(**cameraDTO)\nreturn make_response({'operation': 'success'}, 200)",
"cameraPath = os.path.join(cfg.UPLOAD_FOLDER, cameraId)\nif not os.path.exists(cameraPath):\n return make_response({'images': [], 'id': cameraId}, 200)\nlastImageDate = os.listdir(cameraPath)... | <|body_start_0|>
cameraDTO = request.json
cameraManager.postCamera(**cameraDTO)
return make_response({'operation': 'success'}, 200)
<|end_body_0|>
<|body_start_1|>
cameraPath = os.path.join(cfg.UPLOAD_FOLDER, cameraId)
if not os.path.exists(cameraPath):
return make_r... | Camera | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
def post(self, cameraId):
"""Добавить новую камеру"""
<|body_0|>
def get(self, cameraId):
"""Получить информацию о камере"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cameraDTO = request.json
cameraManager.postCamera(**cameraDTO)
... | stack_v2_sparse_classes_36k_train_001710 | 3,745 | permissive | [
{
"docstring": "Добавить новую камеру",
"name": "post",
"signature": "def post(self, cameraId)"
},
{
"docstring": "Получить информацию о камере",
"name": "get",
"signature": "def get(self, cameraId)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007958 | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def post(self, cameraId): Добавить новую камеру
- def get(self, cameraId): Получить информацию о камере | Implement the Python class `Camera` described below.
Class description:
Implement the Camera class.
Method signatures and docstrings:
- def post(self, cameraId): Добавить новую камеру
- def get(self, cameraId): Получить информацию о камере
<|skeleton|>
class Camera:
def post(self, cameraId):
"""Добавить... | ac6d90da101a5c2f2c305ba21f67369a0f3b786f | <|skeleton|>
class Camera:
def post(self, cameraId):
"""Добавить новую камеру"""
<|body_0|>
def get(self, cameraId):
"""Получить информацию о камере"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Camera:
def post(self, cameraId):
"""Добавить новую камеру"""
cameraDTO = request.json
cameraManager.postCamera(**cameraDTO)
return make_response({'operation': 'success'}, 200)
def get(self, cameraId):
"""Получить информацию о камере"""
cameraPath = os.path... | the_stack_v2_python_sparse | Premier-eye.API/controllers/camera/camera.py | Sapfir0/premier-eye | train | 18 | |
0c8f102b63892bbf99742d9d5c4899b763bc83f2 | [
"agent = parser.add_argument_group('Transformer Arguments')\nadd_common_cmdline_args(agent)\ncls.dictionary_class().add_cmdline_args(parser, partial_opt=partial_opt)\nsuper().add_cmdline_args(parser, partial_opt=partial_opt)\nreturn agent",
"_check_positional_embeddings(self.opt)\nmodel = TransformerGeneratorMode... | <|body_start_0|>
agent = parser.add_argument_group('Transformer Arguments')
add_common_cmdline_args(agent)
cls.dictionary_class().add_cmdline_args(parser, partial_opt=partial_opt)
super().add_cmdline_args(parser, partial_opt=partial_opt)
return agent
<|end_body_0|>
<|body_start_... | TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer | TransformerGeneratorAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerGeneratorAgent:
"""TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer"""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command-line arguments specifically for this ag... | stack_v2_sparse_classes_36k_train_001711 | 15,643 | permissive | [
{
"docstring": "Add command-line arguments specifically for this agent.",
"name": "add_cmdline_args",
"signature": "def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser"
},
{
"docstring": "Build and return model.",
"name": "build_model",
"signa... | 3 | null | Implement the Python class `TransformerGeneratorAgent` described below.
Class description:
TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer
Method signatures and docstrings:
- def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiPa... | Implement the Python class `TransformerGeneratorAgent` described below.
Class description:
TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer
Method signatures and docstrings:
- def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiPa... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class TransformerGeneratorAgent:
"""TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer"""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command-line arguments specifically for this ag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerGeneratorAgent:
"""TransformerGeneratorAgent. Implementation of TorchGeneratorAgent, where the model is a Transformer"""
def add_cmdline_args(cls, parser: ParlaiParser, partial_opt: Optional[Opt]=None) -> ParlaiParser:
"""Add command-line arguments specifically for this agent."""
... | the_stack_v2_python_sparse | parlai/agents/transformer/transformer.py | facebookresearch/ParlAI | train | 10,943 |
c68ca9e3c6c23db3b19896b893703b652e4bb083 | [
"self.config.update_config()\nquery = self.config.get_base_query()\nquery = self.validate_base_query(query)\nquery = query.filter(or_(and_(Task.predecessor == None, Task.successors == None), Task.client_id == get_client_id()))\nquery = self.extend_query_with_ordering(query)\nif self.config.filter_text:\n query =... | <|body_start_0|>
self.config.update_config()
query = self.config.get_base_query()
query = self.validate_base_query(query)
query = query.filter(or_(and_(Task.predecessor == None, Task.successors == None), Task.client_id == get_client_id()))
query = self.extend_query_with_ordering(... | Source adapter for Tasks we got from SQL | GlobalTaskTableSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlobalTaskTableSource:
"""Source adapter for Tasks we got from SQL"""
def build_query(self):
"""Builds the query based on `get_base_query()` method of config. Returns the query object."""
<|body_0|>
def extend_query_with_statefilter(self, query, open_state):
"""W... | stack_v2_sparse_classes_36k_train_001712 | 6,256 | no_license | [
{
"docstring": "Builds the query based on `get_base_query()` method of config. Returns the query object.",
"name": "build_query",
"signature": "def build_query(self)"
},
{
"docstring": "When a state filter is active, we add a filter which select just the open tasks",
"name": "extend_query_wi... | 2 | null | Implement the Python class `GlobalTaskTableSource` described below.
Class description:
Source adapter for Tasks we got from SQL
Method signatures and docstrings:
- def build_query(self): Builds the query based on `get_base_query()` method of config. Returns the query object.
- def extend_query_with_statefilter(self, ... | Implement the Python class `GlobalTaskTableSource` described below.
Class description:
Source adapter for Tasks we got from SQL
Method signatures and docstrings:
- def build_query(self): Builds the query based on `get_base_query()` method of config. Returns the query object.
- def extend_query_with_statefilter(self, ... | 954964872f73c0d18d5b0e0ab2dbf603849e4e87 | <|skeleton|>
class GlobalTaskTableSource:
"""Source adapter for Tasks we got from SQL"""
def build_query(self):
"""Builds the query based on `get_base_query()` method of config. Returns the query object."""
<|body_0|>
def extend_query_with_statefilter(self, query, open_state):
"""W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlobalTaskTableSource:
"""Source adapter for Tasks we got from SQL"""
def build_query(self):
"""Builds the query based on `get_base_query()` method of config. Returns the query object."""
self.config.update_config()
query = self.config.get_base_query()
query = self.validat... | the_stack_v2_python_sparse | opengever/tabbedview/browser/tasklisting.py | hellfish2/opengever.core | train | 1 |
ee978e7d9dbfdcdf02c738ab5311e47043690c96 | [
"if blog_title.data == '':\n raise ValidationError('タイトルを入力してください')\nif len(blog_title.data) > 10:\n raise ValidationError('タイトルは10文字以下にしてください。')\nif '/' in blog_title.data:\n raise ValidationError('タイトルに「/」は含められません。')",
"if description.data == '':\n raise ValidationError('本文を入力してください。')\nif len(descr... | <|body_start_0|>
if blog_title.data == '':
raise ValidationError('タイトルを入力してください')
if len(blog_title.data) > 10:
raise ValidationError('タイトルは10文字以下にしてください。')
if '/' in blog_title.data:
raise ValidationError('タイトルに「/」は含められません。')
<|end_body_0|>
<|body_start_1|>
... | BlogForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlogForm:
def validate_blog_title(self, blog_title):
"""バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止"""
<|body_0|>
def validate_description(self, description):
"""バリデーション内容: - 未入力は禁止 - 文字数が10文字未満は禁止"""
<|body_1|>
def validate_tags(self, tags):
... | stack_v2_sparse_classes_36k_train_001713 | 1,567 | no_license | [
{
"docstring": "バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止",
"name": "validate_blog_title",
"signature": "def validate_blog_title(self, blog_title)"
},
{
"docstring": "バリデーション内容: - 未入力は禁止 - 文字数が10文字未満は禁止",
"name": "validate_description",
"signature": "def validate_description(self... | 3 | stack_v2_sparse_classes_30k_train_001112 | Implement the Python class `BlogForm` described below.
Class description:
Implement the BlogForm class.
Method signatures and docstrings:
- def validate_blog_title(self, blog_title): バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止
- def validate_description(self, description): バリデーション内容: - 未入力は禁止 - 文字数が10文字未満は禁止
- ... | Implement the Python class `BlogForm` described below.
Class description:
Implement the BlogForm class.
Method signatures and docstrings:
- def validate_blog_title(self, blog_title): バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止
- def validate_description(self, description): バリデーション内容: - 未入力は禁止 - 文字数が10文字未満は禁止
- ... | e0876211af2e461082f16235aa565c467d200521 | <|skeleton|>
class BlogForm:
def validate_blog_title(self, blog_title):
"""バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止"""
<|body_0|>
def validate_description(self, description):
"""バリデーション内容: - 未入力は禁止 - 文字数が10文字未満は禁止"""
<|body_1|>
def validate_tags(self, tags):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlogForm:
def validate_blog_title(self, blog_title):
"""バリデーション内容: - 未入力は禁止 - 文字数が10文字以上は禁止 - 「/」を含むことは禁止"""
if blog_title.data == '':
raise ValidationError('タイトルを入力してください')
if len(blog_title.data) > 10:
raise ValidationError('タイトルは10文字以下にしてください。')
if '/... | the_stack_v2_python_sparse | ac-1201-flask-form/blog_form.py | kotamatsuoka/advent-calendar-2018 | train | 0 | |
4a864c2112e81ca907f7fcebc83ed8af78880c0d | [
"super().__init__(links, context=context)\nself._action_link = action_link\nself._available_actions = available_actions",
"links = {}\nlink = self._action_link\nfor action in self._available_actions:\n ctx = self.context.copy()\n ctx['action_name'] = action['action_name']\n ctx['action'] = action['action... | <|body_start_0|>
super().__init__(links, context=context)
self._action_link = action_link
self._available_actions = available_actions
<|end_body_0|>
<|body_start_1|>
links = {}
link = self._action_link
for action in self._available_actions:
ctx = self.context... | Templates for generating links for a community object. | CommunityLinksTemplate | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommunityLinksTemplate:
"""Templates for generating links for a community object."""
def __init__(self, links, action_link, available_actions, context=None):
"""Constructor."""
<|body_0|>
def expand(self, identity, community):
"""Expand all the link templates."""... | stack_v2_sparse_classes_36k_train_001714 | 1,863 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, links, action_link, available_actions, context=None)"
},
{
"docstring": "Expand all the link templates.",
"name": "expand",
"signature": "def expand(self, identity, community)"
}
] | 2 | null | Implement the Python class `CommunityLinksTemplate` described below.
Class description:
Templates for generating links for a community object.
Method signatures and docstrings:
- def __init__(self, links, action_link, available_actions, context=None): Constructor.
- def expand(self, identity, community): Expand all t... | Implement the Python class `CommunityLinksTemplate` described below.
Class description:
Templates for generating links for a community object.
Method signatures and docstrings:
- def __init__(self, links, action_link, available_actions, context=None): Constructor.
- def expand(self, identity, community): Expand all t... | 9a17455c06bf606c19c6b1367e4e3d36bf017be9 | <|skeleton|>
class CommunityLinksTemplate:
"""Templates for generating links for a community object."""
def __init__(self, links, action_link, available_actions, context=None):
"""Constructor."""
<|body_0|>
def expand(self, identity, community):
"""Expand all the link templates."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommunityLinksTemplate:
"""Templates for generating links for a community object."""
def __init__(self, links, action_link, available_actions, context=None):
"""Constructor."""
super().__init__(links, context=context)
self._action_link = action_link
self._available_actions... | the_stack_v2_python_sparse | invenio_communities/communities/services/links.py | inveniosoftware/invenio-communities | train | 5 |
64bad77f8d57950ea783aee3a4ffa34779d6a6a6 | [
"n = len(nums)\nif len(nums) == 0:\n return (-1, -1)\nleft, right = (-1, -1)\nl, r = (0, n - 1)\nwhile l < r:\n m = (l + r) // 2\n if nums[m] < target:\n l = m + 1\n print(l)\n else:\n r = m\nif nums[l] != target:\n return (-1, -1)\nleft = l\nl, r = (left, n - 1)\nwhile l < r:\n ... | <|body_start_0|>
n = len(nums)
if len(nums) == 0:
return (-1, -1)
left, right = (-1, -1)
l, r = (0, n - 1)
while l < r:
m = (l + r) // 2
if nums[m] < target:
l = m + 1
print(l)
else:
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_001715 | 1,225 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange",
"signature": "def searchRange(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "searchRange",
"signature": "def searchRange(self, ... | 2 | stack_v2_sparse_classes_30k_train_010804 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def searchRange(self, nums, target): :type nums: List[int] :type target: int :rty... | cf9eb31bd6800f24519aec6e31645ffa0db15947 | <|skeleton|>
class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchRange(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
n = len(nums)
if len(nums) == 0:
return (-1, -1)
left, right = (-1, -1)
l, r = (0, n - 1)
while l < r:
m = (l + r) // 2
... | the_stack_v2_python_sparse | 34. Find First and Last Position of Element in Sorted Array.py | sang4-uiuc/Leetcode | train | 0 | |
f4f103b335564271eaaf6b5e4af94434ed7be6d2 | [
"user = get_jwt_identity()\ntry:\n filename = solution_delete_photo_from_ddb(user, photo_id)\n file_deleted = delete(filename, user['email'])\n if file_deleted:\n app.logger.debug('success:photo deleted: photo_id: {}'.format(photo_id))\n return make_response({'ok': True, 'photos': {'photo_id'... | <|body_start_0|>
user = get_jwt_identity()
try:
filename = solution_delete_photo_from_ddb(user, photo_id)
file_deleted = delete(filename, user['email'])
if file_deleted:
app.logger.debug('success:photo deleted: photo_id: {}'.format(photo_id))
... | OnePhoto | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnePhoto:
def delete(self, photo_id):
"""one photo delete"""
<|body_0|>
def get(self, photo_id):
"""Return image for thumbnail and original photo. :param photo_id: target photo id :queryparam mode: None(original) or thumbnail :return: image url for authenticated user... | stack_v2_sparse_classes_36k_train_001716 | 8,226 | permissive | [
{
"docstring": "one photo delete",
"name": "delete",
"signature": "def delete(self, photo_id)"
},
{
"docstring": "Return image for thumbnail and original photo. :param photo_id: target photo id :queryparam mode: None(original) or thumbnail :return: image url for authenticated user",
"name": ... | 2 | stack_v2_sparse_classes_30k_train_008046 | Implement the Python class `OnePhoto` described below.
Class description:
Implement the OnePhoto class.
Method signatures and docstrings:
- def delete(self, photo_id): one photo delete
- def get(self, photo_id): Return image for thumbnail and original photo. :param photo_id: target photo id :queryparam mode: None(ori... | Implement the Python class `OnePhoto` described below.
Class description:
Implement the OnePhoto class.
Method signatures and docstrings:
- def delete(self, photo_id): one photo delete
- def get(self, photo_id): Return image for thumbnail and original photo. :param photo_id: target photo id :queryparam mode: None(ori... | 312248c689a19ea9b589025c82f880593fc70f82 | <|skeleton|>
class OnePhoto:
def delete(self, photo_id):
"""one photo delete"""
<|body_0|>
def get(self, photo_id):
"""Return image for thumbnail and original photo. :param photo_id: target photo id :queryparam mode: None(original) or thumbnail :return: image url for authenticated user... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnePhoto:
def delete(self, photo_id):
"""one photo delete"""
user = get_jwt_identity()
try:
filename = solution_delete_photo_from_ddb(user, photo_id)
file_deleted = delete(filename, user['email'])
if file_deleted:
app.logger.debug('su... | the_stack_v2_python_sparse | LAB03/01-DDB/backend/cloudalbum/api/photos.py | aws-kr-tnc/moving-to-serverless-renew | train | 6 | |
971be3e250c0470186e826d3dc3ab53cd38d6baa | [
"forgetting = super().result_key(k)\nbwt = forgetting_to_bwt(forgetting)\nreturn bwt",
"forgetting = super().result()\nbwt = forgetting_to_bwt(forgetting)\nreturn bwt"
] | <|body_start_0|>
forgetting = super().result_key(k)
bwt = forgetting_to_bwt(forgetting)
return bwt
<|end_body_0|>
<|body_start_1|>
forgetting = super().result()
bwt = forgetting_to_bwt(forgetting)
return bwt
<|end_body_1|>
| The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the difference between the last value recorded for a specific key and the fi... | BWT | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BWT:
"""The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the difference between the last value recorde... | stack_v2_sparse_classes_36k_train_001717 | 22,498 | permissive | [
{
"docstring": "Backward Transfer is returned only for keys encountered twice. Backward Transfer is the negative forgetting. :param k: the key for which returning backward transfer. If k has not updated at least twice it returns None. :return: the difference between the last value encountered for k and its firs... | 2 | null | Implement the Python class `BWT` described below.
Class description:
The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the di... | Implement the Python class `BWT` described below.
Class description:
The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the di... | deb2b3e842046f48efc96e55a16d7a566e022c72 | <|skeleton|>
class BWT:
"""The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the difference between the last value recorde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BWT:
"""The standalone Backward Transfer metric. This metric returns the backward transfer relative to a specific key. Alternatively, this metric returns a dict in which each key is associated to the backward transfer. Backward transfer is computed as the difference between the last value recorded for a speci... | the_stack_v2_python_sparse | avalanche/evaluation/metrics/forgetting_bwt.py | ContinualAI/avalanche | train | 1,424 |
9a05326fb5a75b779c5f7c6233ef819756c70fc6 | [
"Module.__init__(self, **kwargs)\nself._warn_sound = warn_sound\nself._warn_interval = warn_interval\nself._start_sound = start_sound\nself._started_sound = started_sound\nself._stop_sound = stop_sound\nself._stopped_sound = stopped_sound\nself._trigger_file = trigger_file\nself._player = player\nself._autonomous =... | <|body_start_0|>
Module.__init__(self, **kwargs)
self._warn_sound = warn_sound
self._warn_interval = warn_interval
self._start_sound = start_sound
self._started_sound = started_sound
self._stop_sound = stop_sound
self._stopped_sound = stopped_sound
self._t... | A module that can plays a warning sound while an IAutonomous module is running. | AutonomousWarning | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutonomousWarning:
"""A module that can plays a warning sound while an IAutonomous module is running."""
def __init__(self, warn_sound: str, warn_interval: float=1, start_sound: Optional[str]=None, started_sound: Optional[str]=None, stop_sound: Optional[str]=None, stopped_sound: Optional[str... | stack_v2_sparse_classes_36k_train_001718 | 4,945 | permissive | [
{
"docstring": "Initialize a new warning. Args: warn_sound: Name of file to play. warn_interval: Interval in seconds between sounds. start_sound: Sound to play when starting systems. started_sound: Sound to play when systems started. stop_sound: Sound to play when stopping systems. stopped_sound: Sound to play ... | 5 | null | Implement the Python class `AutonomousWarning` described below.
Class description:
A module that can plays a warning sound while an IAutonomous module is running.
Method signatures and docstrings:
- def __init__(self, warn_sound: str, warn_interval: float=1, start_sound: Optional[str]=None, started_sound: Optional[st... | Implement the Python class `AutonomousWarning` described below.
Class description:
A module that can plays a warning sound while an IAutonomous module is running.
Method signatures and docstrings:
- def __init__(self, warn_sound: str, warn_interval: float=1, start_sound: Optional[str]=None, started_sound: Optional[st... | 2d7a06e5485b61b6ca7e51d99b08651ea6021086 | <|skeleton|>
class AutonomousWarning:
"""A module that can plays a warning sound while an IAutonomous module is running."""
def __init__(self, warn_sound: str, warn_interval: float=1, start_sound: Optional[str]=None, started_sound: Optional[str]=None, stop_sound: Optional[str]=None, stopped_sound: Optional[str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutonomousWarning:
"""A module that can plays a warning sound while an IAutonomous module is running."""
def __init__(self, warn_sound: str, warn_interval: float=1, start_sound: Optional[str]=None, started_sound: Optional[str]=None, stop_sound: Optional[str]=None, stopped_sound: Optional[str]=None, playe... | the_stack_v2_python_sparse | pyobs/modules/utils/autonomouswarning.py | pyobs/pyobs-core | train | 9 |
9aac3f9e15d04d21001cfcf25b61b9058b719cee | [
"super().__init__()\nself.WRD_EMB_INIT_FILE = WRD_EMB_INIT_FILE\nself.encInputDropout = encInputDropout\nself.qDropout = qDropout\nself.WRD_EMB_DIM = WRD_EMB_DIM\nself.ENC_DIM = ENC_DIM\nself.WRD_EMB_FIXED = WRD_EMB_FIXED\nembInit = np.load(self.WRD_EMB_INIT_FILE)\nself.embeddingsVar = nn.Parameter(torch.Tensor(emb... | <|body_start_0|>
super().__init__()
self.WRD_EMB_INIT_FILE = WRD_EMB_INIT_FILE
self.encInputDropout = encInputDropout
self.qDropout = qDropout
self.WRD_EMB_DIM = WRD_EMB_DIM
self.ENC_DIM = ENC_DIM
self.WRD_EMB_FIXED = WRD_EMB_FIXED
embInit = np.load(self.W... | LCGNEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCGNEncoder:
def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float, qDropout: float, WRD_EMB_DIM: int, ENC_DIM: int, WRD_EMB_FIXED: bool) -> None:
"""Initialization of LCGNEncoder. Args: WRD_EMB_INIT_FILE: the file path storing the initial information of word embedding encInp... | stack_v2_sparse_classes_36k_train_001719 | 5,915 | permissive | [
{
"docstring": "Initialization of LCGNEncoder. Args: WRD_EMB_INIT_FILE: the file path storing the initial information of word embedding encInputDropout: dropout rate of encoder input qDropout: question dropout WRD_EMB_DIM: the dimension of word embedding ENC_DIM: the dimension of encoder WRD_EMB_FIXED: if the w... | 2 | null | Implement the Python class `LCGNEncoder` described below.
Class description:
Implement the LCGNEncoder class.
Method signatures and docstrings:
- def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float, qDropout: float, WRD_EMB_DIM: int, ENC_DIM: int, WRD_EMB_FIXED: bool) -> None: Initialization of LCGNEnco... | Implement the Python class `LCGNEncoder` described below.
Class description:
Implement the LCGNEncoder class.
Method signatures and docstrings:
- def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float, qDropout: float, WRD_EMB_DIM: int, ENC_DIM: int, WRD_EMB_FIXED: bool) -> None: Initialization of LCGNEnco... | af87a17275f02c94932bb2e29f132a84db812002 | <|skeleton|>
class LCGNEncoder:
def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float, qDropout: float, WRD_EMB_DIM: int, ENC_DIM: int, WRD_EMB_FIXED: bool) -> None:
"""Initialization of LCGNEncoder. Args: WRD_EMB_INIT_FILE: the file path storing the initial information of word embedding encInp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCGNEncoder:
def __init__(self, WRD_EMB_INIT_FILE: str, encInputDropout: float, qDropout: float, WRD_EMB_DIM: int, ENC_DIM: int, WRD_EMB_FIXED: bool) -> None:
"""Initialization of LCGNEncoder. Args: WRD_EMB_INIT_FILE: the file path storing the initial information of word embedding encInputDropout: dro... | the_stack_v2_python_sparse | imix/models/encoder/lcgnencoder.py | linxi1158/iMIX | train | 0 | |
0d7435c9c3f78fea8212d02288beb662458c31ff | [
"positions = get_list_or_404(Position)\nif request.GET.get('pagination'):\n pagination = request.GET.get('pagination')\n if pagination == 'true':\n paginator = AdministratorPagination()\n results = paginator.paginate_queryset(positions, request)\n serializer = PositionSerializer(results, ... | <|body_start_0|>
positions = get_list_or_404(Position)
if request.GET.get('pagination'):
pagination = request.GET.get('pagination')
if pagination == 'true':
paginator = AdministratorPagination()
results = paginator.paginate_queryset(positions, requ... | PositionList | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
... | stack_v2_sparse_classes_36k_train_001720 | 30,608 | permissive | [
{
"docstring": "List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: false type: string paramType: query",
"name": "get",
"signature": "def get(self, request, format=None)"
},
{
"docstring": "Create new position --- ser... | 2 | stack_v2_sparse_classes_30k_val_000247 | Implement the Python class `PositionList` described below.
Class description:
Implement the PositionList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: fal... | Implement the Python class `PositionList` described below.
Class description:
Implement the PositionList class.
Method signatures and docstrings:
- def get(self, request, format=None): List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: fal... | 73728463badb3bfd4413aa0f7aeb44a9606fdfea | <|skeleton|>
class PositionList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: false type: string paramType: query"""
<|body_0|>
def post(self, request, format=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PositionList:
def get(self, request, format=None):
"""List all employee positions --- serializer: administrator.serializers.PositionSerializer parameters: - name: pagination required: false type: string paramType: query"""
positions = get_list_or_404(Position)
if request.GET.get('pagin... | the_stack_v2_python_sparse | administrator/views.py | belatrix/BackendAllStars | train | 5 | |
1d90ddcf924a46eee270c77349d7b9bdb184343b | [
"if not isPluginRegistryLoaded() or not isInMainThread():\n return\nif canAppAccessDatabase(allow_test=False):\n try:\n self.create_labels()\n except (AppRegistryNotReady, OperationalError):\n warnings.warn('Database was not ready for creating labels', stacklevel=2)",
"import label.models\n... | <|body_start_0|>
if not isPluginRegistryLoaded() or not isInMainThread():
return
if canAppAccessDatabase(allow_test=False):
try:
self.create_labels()
except (AppRegistryNotReady, OperationalError):
warnings.warn('Database was not ready ... | App configuration class for the 'label' app | LabelConfig | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LabelConfig:
"""App configuration class for the 'label' app"""
def ready(self):
"""This function is called whenever the label app is loaded."""
<|body_0|>
def create_labels(self):
"""Create all default templates."""
<|body_1|>
def create_labels_categ... | stack_v2_sparse_classes_36k_train_001721 | 6,157 | permissive | [
{
"docstring": "This function is called whenever the label app is loaded.",
"name": "ready",
"signature": "def ready(self)"
},
{
"docstring": "Create all default templates.",
"name": "create_labels",
"signature": "def create_labels(self)"
},
{
"docstring": "Create folder and data... | 4 | stack_v2_sparse_classes_30k_train_010846 | Implement the Python class `LabelConfig` described below.
Class description:
App configuration class for the 'label' app
Method signatures and docstrings:
- def ready(self): This function is called whenever the label app is loaded.
- def create_labels(self): Create all default templates.
- def create_labels_category(... | Implement the Python class `LabelConfig` described below.
Class description:
App configuration class for the 'label' app
Method signatures and docstrings:
- def ready(self): This function is called whenever the label app is loaded.
- def create_labels(self): Create all default templates.
- def create_labels_category(... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class LabelConfig:
"""App configuration class for the 'label' app"""
def ready(self):
"""This function is called whenever the label app is loaded."""
<|body_0|>
def create_labels(self):
"""Create all default templates."""
<|body_1|>
def create_labels_categ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LabelConfig:
"""App configuration class for the 'label' app"""
def ready(self):
"""This function is called whenever the label app is loaded."""
if not isPluginRegistryLoaded() or not isInMainThread():
return
if canAppAccessDatabase(allow_test=False):
try:
... | the_stack_v2_python_sparse | InvenTree/label/apps.py | inventree/InvenTree | train | 3,077 |
575fb940fbf80f550afc03b4ecb26a620bd0bc9b | [
"if len(str(month)) == 1:\n month = '0' + str(month)\nself.url = 'http://www.ncdc.noaa.gov/crn/newmonthsummary?' + 'station_id=1007&yyyymm=' + str(year) + str(month) + '&format=csv'\nself.response = ''\nself.save_name = s_dir + 'barrow_4_ENE_' + str(year) + str(month) + '.csv'",
"while True:\n self.response... | <|body_start_0|>
if len(str(month)) == 1:
month = '0' + str(month)
self.url = 'http://www.ncdc.noaa.gov/crn/newmonthsummary?' + 'station_id=1007&yyyymm=' + str(year) + str(month) + '&format=csv'
self.response = ''
self.save_name = s_dir + 'barrow_4_ENE_' + str(year) + str(mon... | this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year. | NCDCCsv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
<|body_0|>
def get_csv(self):
"... | stack_v2_sparse_classes_36k_train_001722 | 6,837 | no_license | [
{
"docstring": "initilizes the class",
"name": "__init__",
"signature": "def __init__(self, year, month, s_dir='')"
},
{
"docstring": "gets the .csv from the noaa website",
"name": "get_csv",
"signature": "def get_csv(self)"
},
{
"docstring": "saves the data to a file",
"name... | 3 | stack_v2_sparse_classes_30k_val_001022 | Implement the Python class `NCDCCsv` described below.
Class description:
this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year.
Method signatures and docstrings:
- def __init__(self, year, month, s_dir=''): initilizes the clas... | Implement the Python class `NCDCCsv` described below.
Class description:
this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year.
Method signatures and docstrings:
- def __init__(self, year, month, s_dir=''): initilizes the clas... | 95d0c102d649c5b028d262f5254106f997a7c77a | <|skeleton|>
class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
<|body_0|>
def get_csv(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NCDCCsv:
"""this class can be used to get the data from one of the sites on www.ncdc.noaa.gov. This data will be in csv file format for a give month and year."""
def __init__(self, year, month, s_dir=''):
"""initilizes the class"""
if len(str(month)) == 1:
month = '0' + str(mo... | the_stack_v2_python_sparse | barrow_monthly.py | rwspicer/csv_utilities | train | 1 |
dfec3e1e50c88a5c261ad10c3a3d86d935d092bf | [
"self.log = logging.getLogger(__name__)\nself.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider}\nself.appname = app\nself.pipeline_config = pipeline_config",
"self.appinfo['accounts'] = ['default']\nself.log.debug('Pipeline Config\\n%s', pformat(self.pipeline_config))\... | <|body_start_0|>
self.log = logging.getLogger(__name__)
self.appinfo = {'app': app, 'email': email, 'project': project, 'repo': repo, 'provider': provider}
self.appname = app
self.pipeline_config = pipeline_config
<|end_body_0|>
<|body_start_1|>
self.appinfo['accounts'] = ['defa... | Base App. | SpinnakerApp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso... | stack_v2_sparse_classes_36k_train_001723 | 3,461 | permissive | [
{
"docstring": "Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with application. project (str): Git namespace or project group repo (str): Repository name",
"name": "__init__",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_008616 | Implement the Python class `SpinnakerApp` described below.
Class description:
Base App.
Method signatures and docstrings:
- def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d... | Implement the Python class `SpinnakerApp` described below.
Class description:
Base App.
Method signatures and docstrings:
- def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None): Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json d... | d88001ea0e33fcd09707b81b5c4ed40e5e21fb59 | <|skeleton|>
class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email asso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpinnakerApp:
"""Base App."""
def __init__(self, provider, pipeline_config=None, app=None, email=None, project=None, repo=None):
"""Class to manage and create Spinnaker applications Args: pipeline_config (dict): pipeline.json data. app (str): Application name. email (str): Email associated with a... | the_stack_v2_python_sparse | src/foremast/app/spinnaker_app.py | foremast/foremast | train | 151 |
277244ff17c4ae4d0ed392652aabe3b2d453e756 | [
"self.align = align\nself.left_border = left_border\nself.right_border = right_border",
"result = ''\nif self.left_border:\n result += '|'\nif self.align == TabularAlignEnum.Left:\n result += 'l'\nelif self.align == TabularAlignEnum.Center:\n result += 'c'\nelif self.align == TabularAlignEnum.Right:\n ... | <|body_start_0|>
self.align = align
self.left_border = left_border
self.right_border = right_border
<|end_body_0|>
<|body_start_1|>
result = ''
if self.left_border:
result += '|'
if self.align == TabularAlignEnum.Left:
result += 'l'
elif s... | Represents information on the alignment of cells of a table. | TabularAlign | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TabularAlign:
"""Represents information on the alignment of cells of a table."""
def __init__(self, align, left_border=False, right_border=False):
"""Initialize object."""
<|body_0|>
def __str__(self):
"""Generate textual representation."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_001724 | 29,852 | permissive | [
{
"docstring": "Initialize object.",
"name": "__init__",
"signature": "def __init__(self, align, left_border=False, right_border=False)"
},
{
"docstring": "Generate textual representation.",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012360 | Implement the Python class `TabularAlign` described below.
Class description:
Represents information on the alignment of cells of a table.
Method signatures and docstrings:
- def __init__(self, align, left_border=False, right_border=False): Initialize object.
- def __str__(self): Generate textual representation. | Implement the Python class `TabularAlign` described below.
Class description:
Represents information on the alignment of cells of a table.
Method signatures and docstrings:
- def __init__(self, align, left_border=False, right_border=False): Initialize object.
- def __str__(self): Generate textual representation.
<|s... | 9de663884ba5f15153d37e527ade6f55e42661a3 | <|skeleton|>
class TabularAlign:
"""Represents information on the alignment of cells of a table."""
def __init__(self, align, left_border=False, right_border=False):
"""Initialize object."""
<|body_0|>
def __str__(self):
"""Generate textual representation."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TabularAlign:
"""Represents information on the alignment of cells of a table."""
def __init__(self, align, left_border=False, right_border=False):
"""Initialize object."""
self.align = align
self.left_border = left_border
self.right_border = right_border
def __str__(s... | the_stack_v2_python_sparse | v7/latex/latex/tree.py | getnikola/plugins | train | 62 |
54b21101f7314c6440704b44f765871b9ca6f459 | [
"self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}\nself.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)\nself.wait = WebDriverWait(self.driver, TIMEOUT)\nself.client = MongoClient(MONGO_URL)\nself.db = self.client[MONGO_DB]... | <|body_start_0|>
self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIMEOUT)
self.client = MongoClient(MO... | Moments | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录微信 :return:"""
<|body_1|>
def enter(self):
"""进入朋友圈 :return:"""
<|body_2|>
def crawl(self):
"""爬取 :return:"""
<|body_3|>
def main(self):
... | stack_v2_sparse_classes_36k_train_001725 | 6,811 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "登录微信 :return:",
"name": "login",
"signature": "def login(self)"
},
{
"docstring": "进入朋友圈 :return:",
"name": "enter",
"signature": "def enter(self)"
},
{
"docstring": "爬取... | 5 | stack_v2_sparse_classes_30k_train_013074 | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录微信 :return:
- def enter(self): 进入朋友圈 :return:
- def crawl(self): 爬取 :return:
- def main(self): 入口 :return: | Implement the Python class `Moments` described below.
Class description:
Implement the Moments class.
Method signatures and docstrings:
- def __init__(self): 初始化
- def login(self): 登录微信 :return:
- def enter(self): 进入朋友圈 :return:
- def crawl(self): 爬取 :return:
- def main(self): 入口 :return:
<|skeleton|>
class Moments:... | 9147c8ea56f241e192110ce57d29946c0ca69868 | <|skeleton|>
class Moments:
def __init__(self):
"""初始化"""
<|body_0|>
def login(self):
"""登录微信 :return:"""
<|body_1|>
def enter(self):
"""进入朋友圈 :return:"""
<|body_2|>
def crawl(self):
"""爬取 :return:"""
<|body_3|>
def main(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Moments:
def __init__(self):
"""初始化"""
self.desired_caps = {'platformName': PLATFORM, 'deviceName': DEVICE_NAME, 'appPackage': APP_PACKAGE, 'appActivity': APP_ACTIVITY}
self.driver = webdriver.Remote(DRIVER_SERVER, self.desired_caps)
self.wait = WebDriverWait(self.driver, TIMEO... | the_stack_v2_python_sparse | AppSpider/moments.py | hcxgit/PycharmProjects | train | 0 | |
7f82c9efe22f1d02f486768d1e7b64acf2fe9b96 | [
"if role in self.workspaces.keys():\n if tab in self.workspaces[role].keys():\n return self.workspaces[role][tab]\nreturn None",
"if role not in self.workspaces:\n self.workspaces[role] = {}\nif tab not in self.workspaces[role]:\n self.workspaces[role][tab] = {}\nif domain_class not in self.worksp... | <|body_start_0|>
if role in self.workspaces.keys():
if tab in self.workspaces[role].keys():
return self.workspaces[role][tab]
return None
<|end_body_0|>
<|body_start_1|>
if role not in self.workspaces:
self.workspaces[role] = {}
if tab not in self... | This is utility stores the workflow configuration | WorkspaceTabsUtility | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspaceTabsUtility:
"""This is utility stores the workflow configuration"""
def getDomainAndStatuses(self, role, tab):
"""Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applicable statuses"""
<|body_0|>
def setContent(se... | stack_v2_sparse_classes_36k_train_001726 | 4,696 | no_license | [
{
"docstring": "Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applicable statuses",
"name": "getDomainAndStatuses",
"signature": "def getDomainAndStatuses(self, role, tab)"
},
{
"docstring": "Sets the",
"name": "setContent",
"signature": ... | 4 | null | Implement the Python class `WorkspaceTabsUtility` described below.
Class description:
This is utility stores the workflow configuration
Method signatures and docstrings:
- def getDomainAndStatuses(self, role, tab): Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applica... | Implement the Python class `WorkspaceTabsUtility` described below.
Class description:
This is utility stores the workflow configuration
Method signatures and docstrings:
- def getDomainAndStatuses(self, role, tab): Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applica... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class WorkspaceTabsUtility:
"""This is utility stores the workflow configuration"""
def getDomainAndStatuses(self, role, tab):
"""Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applicable statuses"""
<|body_0|>
def setContent(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkspaceTabsUtility:
"""This is utility stores the workflow configuration"""
def getDomainAndStatuses(self, role, tab):
"""Returns a dictionary with the domain classes as keys. the value for each key is a dictionary of applicable statuses"""
if role in self.workspaces.keys():
... | the_stack_v2_python_sparse | bungeni.main/branches/sterch-issue712/bungeni/core/workspace.py | malangalanga/bungeni-portal | train | 0 |
6fe4fe9f1625e7364064de6f835293781fcab788 | [
"Calculator.__init__(self, name)\nself._model = model\nfrom diffpy.srfit.sas.sasparameter import SASParameter\nfor parname in model.params:\n par = SASParameter(parname, model)\n self.addParameter(par)\nfor parname in model.dispersion:\n name = parname + '_width'\n parname += '.width'\n par = SASPara... | <|body_start_0|>
Calculator.__init__(self, name)
self._model = model
from diffpy.srfit.sas.sasparameter import SASParameter
for parname in model.params:
par = SASParameter(parname, model)
self.addParameter(par)
for parname in model.dispersion:
... | Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. Attributes: _model -- BaseModel ob... | SASCF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. A... | stack_v2_sparse_classes_36k_train_001727 | 10,746 | no_license | [
{
"docstring": "Initialize the generator. name -- A name for the SASCF model -- SASModel object this adapts.",
"name": "__init__",
"signature": "def __init__(self, name, model)"
},
{
"docstring": "Calculate the characteristic function from the transform of the BaseModel.",
"name": "__call__"... | 2 | stack_v2_sparse_classes_30k_train_015790 | Implement the Python class `SASCF` described below.
Class description:
Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" r... | Implement the Python class `SASCF` described below.
Class description:
Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" r... | 303f73c570c1d756106aa69724898d5b119c4ead | <|skeleton|>
class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. Attributes: _m... | the_stack_v2_python_sparse | diffpy/srfit/pdf/characteristicfunctions.py | cfarrow/diffpy.srfit | train | 0 |
7f21afa787311f4cd9c37462c5750848692caf33 | [
"serializer = IDCardOpenSerializer(data=request.DATA)\nif not serializer.is_valid():\n print(serializer.errors)\n return response.Response('Invalid request data.', 400)\nif self.can_open_door(serializer.data):\n return response.Response('Valid ID card.', 200)\nreturn response.Response('Invalid ID card.', 4... | <|body_start_0|>
serializer = IDCardOpenSerializer(data=request.DATA)
if not serializer.is_valid():
print(serializer.errors)
return response.Response('Invalid request data.', 400)
if self.can_open_door(serializer.data):
return response.Response('Valid ID card.... | API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403. | IDCardOpenView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IDCardOpenView:
"""API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403."""
def post(self, request, *args, **kwargs):
"""POST handl... | stack_v2_sparse_classes_36k_train_001728 | 2,067 | no_license | [
{
"docstring": "POST handler.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Check if the provided `card_uid` is allowed to open the door that corresponds to the provided `device_id`.",
"name": "can_open_door",
"signature": "def can_open_door... | 2 | stack_v2_sparse_classes_30k_train_002050 | Implement the Python class `IDCardOpenView` described below.
Class description:
API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403.
Method signatures and docstring... | Implement the Python class `IDCardOpenView` described below.
Class description:
API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403.
Method signatures and docstring... | c7d792db975b72b9b058298f9309238da05351a9 | <|skeleton|>
class IDCardOpenView:
"""API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403."""
def post(self, request, *args, **kwargs):
"""POST handl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IDCardOpenView:
"""API view that is POSTed to by a door device. The POST data must include a `device_id` and a `card_uid`. If a match is successfull, indicating that the door can be opened, a 200 is returned, otherwise a 403."""
def post(self, request, *args, **kwargs):
"""POST handler."""
... | the_stack_v2_python_sparse | sparkdoor/apps/common/views.py | dummerbd/sparkdoor | train | 0 |
773f0d381695cf9ab75154a5b6097d25f537d590 | [
"self = super().__new__(cls)\nif not isinstance(func, T.Callable):\n out_dtype = in_dtype\n in_dtype = func\n func = None\nif func is not None:\n self.__init__(in_dtype, out_dtype)\n return self(func)\nreturn self",
"super().__init__()\nself._in_dtype = in_dtype\nself._out_dtype = out_dtype\nreturn... | <|body_start_0|>
self = super().__new__(cls)
if not isinstance(func, T.Callable):
out_dtype = in_dtype
in_dtype = func
func = None
if func is not None:
self.__init__(in_dtype, out_dtype)
return self(func)
return self
<|end_body_... | Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not a function, then func is assumed to be ina... | dtypeDecorator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not ... | stack_v2_sparse_classes_36k_train_001729 | 19,204 | permissive | [
{
"docstring": "New dtypeDecorator.",
"name": "__new__",
"signature": "def __new__(cls, func: T.Optional[T.Callable]=None, in_dtype: T.Any=None, out_dtype: T.Any=None)"
},
{
"docstring": "Initialize dtypeDecorator.",
"name": "__init__",
"signature": "def __init__(self, in_dtype: T.Any=No... | 3 | stack_v2_sparse_classes_30k_train_007126 | Implement the Python class `dtypeDecorator` described below.
Class description:
Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word ... | Implement the Python class `dtypeDecorator` described below.
Class description:
Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word ... | 17984942145d31126724df23500bafba18fb7516 | <|skeleton|>
class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class dtypeDecorator:
"""Ensure arguments are type *dtype*. Parameters ---------- func : function, optional function to decorate inargs : list [(index, dtype), ...] outargs : list [(index, dtype), ...] these arguments, except func, should be specified by key word if inargs is forgotten and func is not a function, t... | the_stack_v2_python_sparse | utilipy/decorators/func_io.py | nstarman/utilipy | train | 2 |
fbb066de88213e7074676d436d9b82132705a6b1 | [
"self.name = name\nself.age = age\nprint('Создан SchoolMember: ' + self.name)",
"attributes = self.__dict__\nstr2shw = ''\nfor key in attributes.keys():\n str2shw += key + ': ' + str(attributes[key]) + ' '\nprint(str2shw)"
] | <|body_start_0|>
self.name = name
self.age = age
print('Создан SchoolMember: ' + self.name)
<|end_body_0|>
<|body_start_1|>
attributes = self.__dict__
str2shw = ''
for key in attributes.keys():
str2shw += key + ': ' + str(attributes[key]) + ' '
print(... | Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.). | SchoolMember | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchoolMember:
"""Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.)."""
def __init__(self, name, age):
"""Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :param age: Возраст человека. :type age: int."""
<|bod... | stack_v2_sparse_classes_36k_train_001730 | 2,436 | no_license | [
{
"docstring": "Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :param age: Возраст человека. :type age: int.",
"name": "__init__",
"signature": "def __init__(self, name, age)"
},
{
"docstring": "Выводит на экран информацию о представителе класса SchoolMember. :param se... | 2 | stack_v2_sparse_classes_30k_train_013250 | Implement the Python class `SchoolMember` described below.
Class description:
Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.).
Method signatures and docstrings:
- def __init__(self, name, age): Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :para... | Implement the Python class `SchoolMember` described below.
Class description:
Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.).
Method signatures and docstrings:
- def __init__(self, name, age): Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :para... | af9611cfc0809148536c4ab2491f945ef626e710 | <|skeleton|>
class SchoolMember:
"""Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.)."""
def __init__(self, name, age):
"""Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :param age: Возраст человека. :type age: int."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchoolMember:
"""Класс, описывающий человека, имеющего какое-либо отношение к школе(сотрудник, ученик и т.п.)."""
def __init__(self, name, age):
"""Конструктор класса. :param name: Имя и фамилия человека. :type name: str. :param age: Возраст человека. :type age: int."""
self.name = name
... | the_stack_v2_python_sparse | lec5/lec/task2.py | catr1ne55/epam_training_python | train | 0 |
9802125f7641254cc909c245c591a78fd0368b05 | [
"self._username = username\nself._client_id = client_id\nwith open(private_key_file, 'rb') as f:\n payload = f.read()\n self._pk = load_pem_private_key(payload, None)",
"resp = requests.post(LOGIN_BASE_URL + '/services/oauth2/token', data={'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assert... | <|body_start_0|>
self._username = username
self._client_id = client_id
with open(private_key_file, 'rb') as f:
payload = f.read()
self._pk = load_pem_private_key(payload, None)
<|end_body_0|>
<|body_start_1|>
resp = requests.post(LOGIN_BASE_URL + '/services/oauth... | Salesforce | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Salesforce:
def __init__(self, username: str, client_id: str, private_key_file: str) -> None:
"""Wrapper over the Salesforce REST API. :param username: Target user username. :param client_id: Application client ID. :param private_key_file: PEM format private key filename."""
<|bo... | stack_v2_sparse_classes_36k_train_001731 | 3,385 | permissive | [
{
"docstring": "Wrapper over the Salesforce REST API. :param username: Target user username. :param client_id: Application client ID. :param private_key_file: PEM format private key filename.",
"name": "__init__",
"signature": "def __init__(self, username: str, client_id: str, private_key_file: str) -> ... | 4 | stack_v2_sparse_classes_30k_test_000790 | Implement the Python class `Salesforce` described below.
Class description:
Implement the Salesforce class.
Method signatures and docstrings:
- def __init__(self, username: str, client_id: str, private_key_file: str) -> None: Wrapper over the Salesforce REST API. :param username: Target user username. :param client_i... | Implement the Python class `Salesforce` described below.
Class description:
Implement the Salesforce class.
Method signatures and docstrings:
- def __init__(self, username: str, client_id: str, private_key_file: str) -> None: Wrapper over the Salesforce REST API. :param username: Target user username. :param client_i... | c7611c7b812709ada8bb7e34434fe22fd54a597c | <|skeleton|>
class Salesforce:
def __init__(self, username: str, client_id: str, private_key_file: str) -> None:
"""Wrapper over the Salesforce REST API. :param username: Target user username. :param client_id: Application client ID. :param private_key_file: PEM format private key filename."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Salesforce:
def __init__(self, username: str, client_id: str, private_key_file: str) -> None:
"""Wrapper over the Salesforce REST API. :param username: Target user username. :param client_id: Application client ID. :param private_key_file: PEM format private key filename."""
self._username = u... | the_stack_v2_python_sparse | python/goals-api-sfdc/src/asana_goals/data_source/salesforce/client.py | Asana/devrel-examples | train | 21 | |
4ffe03bb5dd471fdf95760691ac866888b51f421 | [
"def dfs(n, g, visited):\n if visited[n]:\n return\n visited[n] = 1\n for x in g[n]:\n dfs(x, g, visited)\nvisited = [0] * n\ng = {x: [] for x in xrange(n)}\nfor x, y in edges:\n g[x].append(y)\n g[y].append(x)\nret = 0\nfor i in xrange(n):\n if not visited[i]:\n dfs(i, g, vis... | <|body_start_0|>
def dfs(n, g, visited):
if visited[n]:
return
visited[n] = 1
for x in g[n]:
dfs(x, g, visited)
visited = [0] * n
g = {x: [] for x in xrange(n)}
for x, y in edges:
g[x].append(y)
g... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countComponents(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%"""
<|body_0|>
def countComponents1(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: int BFS beats 75.99%"""
<|body_1|... | stack_v2_sparse_classes_36k_train_001732 | 1,887 | no_license | [
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%",
"name": "countComponents",
"signature": "def countComponents(self, n, edges)"
},
{
"docstring": ":type n: int :type edges: List[List[int]] :rtype: int BFS beats 75.99%",
"name": "countComponents1",
"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countComponents(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%
- def countComponents1(self, n, edges): :type n: int :type edges: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countComponents(self, n, edges): :type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%
- def countComponents1(self, n, edges): :type n: int :type edges: List... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def countComponents(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%"""
<|body_0|>
def countComponents1(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: int BFS beats 75.99%"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countComponents(self, n, edges):
""":type n: int :type edges: List[List[int]] :rtype: int DFS beats 69.65%"""
def dfs(n, g, visited):
if visited[n]:
return
visited[n] = 1
for x in g[n]:
dfs(x, g, visited)
... | the_stack_v2_python_sparse | LeetCode/323_number_of_connected_components_in_an_undirected_graph.py | yao23/Machine_Learning_Playground | train | 12 | |
61844fe67498f91247ffde49913534ab30d59a3a | [
"user.set_unusable_password()\nuser = self.update_user(user, attributes, attribute_mapping, force_save=True)\nuser_pendings = Invitation.objects.filter(email=user.email)\nfor user_pending in user_pendings:\n CourseTeacher.objects.get_or_create(course=user_pending.course, teacher=user)\n user_pending.delete()\... | <|body_start_0|>
user.set_unusable_password()
user = self.update_user(user, attributes, attribute_mapping, force_save=True)
user_pendings = Invitation.objects.filter(email=user.email)
for user_pending in user_pendings:
CourseTeacher.objects.get_or_create(course=user_pending.c... | Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1 | Saml2BackendExtension | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Saml2BackendExtension:
"""Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1"""
def configure_user(self, user, attributes, attribute_mapping):
"""Configures a user after creation and returns the updated user. By default, returns the user with his attrib... | stack_v2_sparse_classes_36k_train_001733 | 3,604 | permissive | [
{
"docstring": "Configures a user after creation and returns the updated user. By default, returns the user with his attributes updated.",
"name": "configure_user",
"signature": "def configure_user(self, user, attributes, attribute_mapping)"
},
{
"docstring": "Update a user with a set of attribu... | 2 | null | Implement the Python class `Saml2BackendExtension` described below.
Class description:
Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1
Method signatures and docstrings:
- def configure_user(self, user, attributes, attribute_mapping): Configures a user after creation and returns the u... | Implement the Python class `Saml2BackendExtension` described below.
Class description:
Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1
Method signatures and docstrings:
- def configure_user(self, user, attributes, attribute_mapping): Configures a user after creation and returns the u... | d5301ba867cc6c982754478ad26df39d7d858b8d | <|skeleton|>
class Saml2BackendExtension:
"""Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1"""
def configure_user(self, user, attributes, attribute_mapping):
"""Configures a user after creation and returns the updated user. By default, returns the user with his attrib... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Saml2BackendExtension:
"""Extend the SAML2 backend for the integration with OpenMOOC. .. versionadded:: 0.1"""
def configure_user(self, user, attributes, attribute_mapping):
"""Configures a user after creation and returns the updated user. By default, returns the user with his attributes updated.... | the_stack_v2_python_sparse | moocng/courses/backends.py | GeographicaGS/moocng | train | 2 |
075fdae4ade922f2048baa054a77b1d7704c184b | [
"hook_event = request.META.get('HTTP_X_GITHUB_EVENT')\nif hook_event == 'ping':\n return HttpResponse()\nelif hook_event != 'push':\n return HttpResponseBadRequest('Only \"ping\" and \"push\" events are supported.')\nrepository = get_repository_for_hook(repository_id, hosting_service_id, local_site_name)\nm =... | <|body_start_0|>
hook_event = request.META.get('HTTP_X_GITHUB_EVENT')
if hook_event == 'ping':
return HttpResponse()
elif hook_event != 'push':
return HttpResponseBadRequest('Only "ping" and "push" events are supported.')
repository = get_repository_for_hook(repos... | Container class for hook views. | GitHubHookViews | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The req... | stack_v2_sparse_classes_36k_train_001734 | 42,594 | permissive | [
{
"docstring": "Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The request from the Bitbucket webhook. local_site_name (unicode): The local site name, if available. repository_id (int): The pk of the repository, if available. hosting_service_id (unicode):... | 2 | stack_v2_sparse_classes_30k_train_003105 | Implement the Python class `GitHubHookViews` described below.
Class description:
Container class for hook views.
Method signatures and docstrings:
- def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None): Close review requests as submitted automatically after... | Implement the Python class `GitHubHookViews` described below.
Class description:
Container class for hook views.
Method signatures and docstrings:
- def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None): Close review requests as submitted automatically after... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GitHubHookViews:
"""Container class for hook views."""
def post_receive_hook_close_submitted(request, local_site_name=None, repository_id=None, hosting_service_id=None):
"""Close review requests as submitted automatically after a push. Args: request (django.http.HttpRequest): The request from the... | the_stack_v2_python_sparse | reviewboard/hostingsvcs/github.py | reviewboard/reviewboard | train | 1,141 |
ae26f22227c885419efa8fca34fa78d760a17f1e | [
"self.clf = clf\nself.costs = costs\nself.m = m\nself.data_row = data_row\nself.for_individual = for_individual\nself.min_max = min_max",
"if self.for_individual:\n self._build_model_from_scratch()\nelse:\n self._build_model()\nif self.m.Status == 2:\n self._get_values(True)\nelif self.m.Status == 3:\n ... | <|body_start_0|>
self.clf = clf
self.costs = costs
self.m = m
self.data_row = data_row
self.for_individual = for_individual
self.min_max = min_max
<|end_body_0|>
<|body_start_1|>
if self.for_individual:
self._build_model_from_scratch()
else:
... | Find minimal flipset per row of input data with a predicted negative outcome. | FlipsetAlgorithm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
<|body_0|>
def run(self):
"""Build the m... | stack_v2_sparse_classes_36k_train_001735 | 4,227 | no_license | [
{
"docstring": "Initialise variables needed.",
"name": "__init__",
"signature": "def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None)"
},
{
"docstring": "Build the model, get the new values, and write them to an output file.",
"name": "run",
"signature": "... | 5 | stack_v2_sparse_classes_30k_train_014955 | Implement the Python class `FlipsetAlgorithm` described below.
Class description:
Find minimal flipset per row of input data with a predicted negative outcome.
Method signatures and docstrings:
- def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None): Initialise variables needed.
- def r... | Implement the Python class `FlipsetAlgorithm` described below.
Class description:
Find minimal flipset per row of input data with a predicted negative outcome.
Method signatures and docstrings:
- def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None): Initialise variables needed.
- def r... | 05804150a03ab903a3192ce5846e8aa26c652cdb | <|skeleton|>
class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
<|body_0|>
def run(self):
"""Build the m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlipsetAlgorithm:
"""Find minimal flipset per row of input data with a predicted negative outcome."""
def __init__(self, clf, costs, data_row, m=None, for_individual=False, min_max=None):
"""Initialise variables needed."""
self.clf = clf
self.costs = costs
self.m = m
... | the_stack_v2_python_sparse | ActionableClassification_and_Fairness/flipset_algorithm.py | AminaTkh/Benchmarking-for-actionable-recourse-solutions | train | 0 |
4d6f2c94bed5af2eabbad5bbdbeda7ede882e2ad | [
"if num < 1:\n return False\nif num & num - 1 != 0:\n return False\nreturn num % 3 == 1",
"if num < 1:\n return False\nif num & num - 1 != 0:\n return False\nwhile True:\n if num == 0:\n return False\n elif num == 1:\n return True\n num >>= 2"
] | <|body_start_0|>
if num < 1:
return False
if num & num - 1 != 0:
return False
return num % 3 == 1
<|end_body_0|>
<|body_start_1|>
if num < 1:
return False
if num & num - 1 != 0:
return False
while True:
if num =... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
<|body_0|>
def isPowerOfFourNaive(self, num):
"""Naive Determine number of 0 bits to be even :type num: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_001736 | 988 | permissive | [
{
"docstring": "Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:",
"name": "isPowerOfFour",
"signature": "def isPowerOfFour(self, num)"
},
{
"docstring": "Naive Determine number of 0 bits to be even :type num: int :rtype: bool",
"name": "isPowerOfFourNaive",
"signatur... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num): Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:
- def isPowerOfFourNaive(self, num): Naive Determine number of 0 bits to be eve... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfFour(self, num): Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:
- def isPowerOfFourNaive(self, num): Naive Determine number of 0 bits to be eve... | cbbd4a67ab342ada2421e13f82d660b1d47d4d20 | <|skeleton|>
class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
<|body_0|>
def isPowerOfFourNaive(self, num):
"""Naive Determine number of 0 bits to be even :type num: int :rtype: bool"""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPowerOfFour(self, num):
"""Modular calculation 4^a mod 3 = (1)^a mod 3 = 1 :param num: :return:"""
if num < 1:
return False
if num & num - 1 != 0:
return False
return num % 3 == 1
def isPowerOfFourNaive(self, num):
"""Naive D... | the_stack_v2_python_sparse | 342 Power of Four.py | Aminaba123/LeetCode | train | 1 | |
95a471991bc9e5dd14f77180b6e002b3a149a142 | [
"self.t = self.ctx.convert(t)\nself.tmax = self.ctx.convert(kwargs.get('tmax', self.t))\nif 'degree' in kwargs:\n self.degree = kwargs['degree']\n self.dps_goal = self.degree\nelse:\n self.dps_goal = int(1.72 * self.ctx.dps)\n self.degree = max(12, int(1.38 * self.dps_goal))\nM = self.degree\nself.dps_o... | <|body_start_0|>
self.t = self.ctx.convert(t)
self.tmax = self.ctx.convert(kwargs.get('tmax', self.t))
if 'degree' in kwargs:
self.degree = kwargs['degree']
self.dps_goal = self.degree
else:
self.dps_goal = int(1.72 * self.ctx.dps)
self.deg... | FixedTalbot | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FixedTalbot:
def calc_laplace_parameter(self, t, **kwargs):
"""The "fixed" Talbot method deforms the Bromwich contour towards `-\\infty` in the shape of a parabola. Traditionally the Talbot algorithm has adjustable parameters, but the "fixed" version does not. The `r` parameter could be ... | stack_v2_sparse_classes_36k_train_001737 | 36,056 | permissive | [
{
"docstring": "The \"fixed\" Talbot method deforms the Bromwich contour towards `-\\\\infty` in the shape of a parabola. Traditionally the Talbot algorithm has adjustable parameters, but the \"fixed\" version does not. The `r` parameter could be passed in as a parameter, if you want to override the default giv... | 2 | null | Implement the Python class `FixedTalbot` described below.
Class description:
Implement the FixedTalbot class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The "fixed" Talbot method deforms the Bromwich contour towards `-\\infty` in the shape of a parabola. Traditionally the Talbo... | Implement the Python class `FixedTalbot` described below.
Class description:
Implement the FixedTalbot class.
Method signatures and docstrings:
- def calc_laplace_parameter(self, t, **kwargs): The "fixed" Talbot method deforms the Bromwich contour towards `-\\infty` in the shape of a parabola. Traditionally the Talbo... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class FixedTalbot:
def calc_laplace_parameter(self, t, **kwargs):
"""The "fixed" Talbot method deforms the Bromwich contour towards `-\\infty` in the shape of a parabola. Traditionally the Talbot algorithm has adjustable parameters, but the "fixed" version does not. The `r` parameter could be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FixedTalbot:
def calc_laplace_parameter(self, t, **kwargs):
"""The "fixed" Talbot method deforms the Bromwich contour towards `-\\infty` in the shape of a parabola. Traditionally the Talbot algorithm has adjustable parameters, but the "fixed" version does not. The `r` parameter could be passed in as a... | the_stack_v2_python_sparse | contrib/python/mpmath/mpmath/calculus/inverselaplace.py | catboost/catboost | train | 8,012 | |
4cf3859733ae5faeea3f055fffcc638c6e18b893 | [
"pool = multiprocessing.pool.ThreadPool()\nresults = pool.map(_test_filler, range(500))\nself.assertTrue(all((r is quantum_context.q_context() for r in results)))",
"pool = multiprocessing.Pool()\nresults = pool.map(_test_filler, range(500))\nself.assertFalse(all((r is quantum_context.q_context() for r in results... | <|body_start_0|>
pool = multiprocessing.pool.ThreadPool()
results = pool.map(_test_filler, range(500))
self.assertTrue(all((r is quantum_context.q_context() for r in results)))
<|end_body_0|>
<|body_start_1|>
pool = multiprocessing.Pool()
results = pool.map(_test_filler, range(5... | Test that quantum context objects work. | QContextTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QContextTest:
"""Test that quantum context objects work."""
def test_global_singleton(self):
"""Test that context object is a true singleton."""
<|body_0|>
def test_global_not_singleton(self):
"""In the case of Processes singleton objects will be reset."""
... | stack_v2_sparse_classes_36k_train_001738 | 2,579 | permissive | [
{
"docstring": "Test that context object is a true singleton.",
"name": "test_global_singleton",
"signature": "def test_global_singleton(self)"
},
{
"docstring": "In the case of Processes singleton objects will be reset.",
"name": "test_global_not_singleton",
"signature": "def test_globa... | 4 | stack_v2_sparse_classes_30k_test_000944 | Implement the Python class `QContextTest` described below.
Class description:
Test that quantum context objects work.
Method signatures and docstrings:
- def test_global_singleton(self): Test that context object is a true singleton.
- def test_global_not_singleton(self): In the case of Processes singleton objects wil... | Implement the Python class `QContextTest` described below.
Class description:
Test that quantum context objects work.
Method signatures and docstrings:
- def test_global_singleton(self): Test that context object is a true singleton.
- def test_global_not_singleton(self): In the case of Processes singleton objects wil... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class QContextTest:
"""Test that quantum context objects work."""
def test_global_singleton(self):
"""Test that context object is a true singleton."""
<|body_0|>
def test_global_not_singleton(self):
"""In the case of Processes singleton objects will be reset."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QContextTest:
"""Test that quantum context objects work."""
def test_global_singleton(self):
"""Test that context object is a true singleton."""
pool = multiprocessing.pool.ThreadPool()
results = pool.map(_test_filler, range(500))
self.assertTrue(all((r is quantum_context.... | the_stack_v2_python_sparse | tensorflow_quantum/python/quantum_context_test.py | tensorflow/quantum | train | 1,799 |
bb87d916696ef477783510dfd78752130b78e0ad | [
"super(Encoder, self).__init__()\nself.config = config\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.bidirection = bidirection\nif config.rnn_type not in ['LSTM', 'GRU']:\n raise ValueError(\"An invalid option for `--model` was supplied, options are ['LSTM', 'GRU']\")\nself.rnn = getattr(nn... | <|body_start_0|>
super(Encoder, self).__init__()
self.config = config
self.input_size = input_size
self.hidden_size = hidden_size
self.bidirection = bidirection
if config.rnn_type not in ['LSTM', 'GRU']:
raise ValueError("An invalid option for `--model` was su... | Encoder class of a sequence-to-sequence network | Encoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""Encoder class of a sequence-to-sequence network"""
def __init__(self, input_size, hidden_size, bidirection, config):
""""Constructor of the class"""
<|body_0|>
def forward(self, sent_variable, sent_len):
""""Defines the forward computation of the enco... | stack_v2_sparse_classes_36k_train_001739 | 3,931 | permissive | [
{
"docstring": "\"Constructor of the class",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden_size, bidirection, config)"
},
{
"docstring": "\"Defines the forward computation of the encoder",
"name": "forward",
"signature": "def forward(self, sent_variable, sent_le... | 2 | stack_v2_sparse_classes_30k_train_010834 | Implement the Python class `Encoder` described below.
Class description:
Encoder class of a sequence-to-sequence network
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, bidirection, config): "Constructor of the class
- def forward(self, sent_variable, sent_len): "Defines the forward co... | Implement the Python class `Encoder` described below.
Class description:
Encoder class of a sequence-to-sequence network
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, bidirection, config): "Constructor of the class
- def forward(self, sent_variable, sent_len): "Defines the forward co... | 73d13bc1cdf2ea66d13209c007dcc2767cf2155c | <|skeleton|>
class Encoder:
"""Encoder class of a sequence-to-sequence network"""
def __init__(self, input_size, hidden_size, bidirection, config):
""""Constructor of the class"""
<|body_0|>
def forward(self, sent_variable, sent_len):
""""Defines the forward computation of the enco... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""Encoder class of a sequence-to-sequence network"""
def __init__(self, input_size, hidden_size, bidirection, config):
""""Constructor of the class"""
super(Encoder, self).__init__()
self.config = config
self.input_size = input_size
self.hidden_size = hid... | the_stack_v2_python_sparse | mtl_sent2vec/shared_private/nn_layer.py | zhang1546/transferable_sent2vec | train | 0 |
4ef94dc956afa88cdc4f34740cb1f5caf3a939c1 | [
"with catch(self):\n self.params.update(self.get_lord())\n provider = TENCLOUD_PROVIDER_NAME[self.params['cloud_type']]\n data = (yield self.server_service.search_fc_instance({'provider': provider}))\n self.success(data)",
"with catch(self):\n self.params.update(self.get_lord())\n for data in se... | <|body_start_0|>
with catch(self):
self.params.update(self.get_lord())
provider = TENCLOUD_PROVIDER_NAME[self.params['cloud_type']]
data = (yield self.server_service.search_fc_instance({'provider': provider}))
self.success(data)
<|end_body_0|>
<|body_start_1|>
... | CloudCredentialHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudCredentialHandler:
def post(self):
"""@api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiParam {Object} content 凭证内容 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "status": 0, "msg": "s... | stack_v2_sparse_classes_36k_train_001740 | 3,604 | no_license | [
{
"docstring": "@api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiParam {Object} content 凭证内容 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { \"status\": 0, \"msg\": \"success\", \"data\": [ { \"is_add\": int 0:未添加 ... | 3 | stack_v2_sparse_classes_30k_train_019991 | Implement the Python class `CloudCredentialHandler` described below.
Class description:
Implement the CloudCredentialHandler class.
Method signatures and docstrings:
- def post(self): @api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiP... | Implement the Python class `CloudCredentialHandler` described below.
Class description:
Implement the CloudCredentialHandler class.
Method signatures and docstrings:
- def post(self): @api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiP... | 0b09280afe5b764a485b3bf6e760aaf9a68bc4d5 | <|skeleton|>
class CloudCredentialHandler:
def post(self):
"""@api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiParam {Object} content 凭证内容 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "status": 0, "msg": "s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CloudCredentialHandler:
def post(self):
"""@api {post} /api/clouds/credentials 公有云厂商认证 @apiName CloudCredentialHandler @apiGroup Cloud @apiParam {Number} cloud_type 厂商内部id @apiParam {Object} content 凭证内容 @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "status": 0, "msg": "success", "data... | the_stack_v2_python_sparse | handler/cloud/cloud.py | pickCloud/TenCloud_Backend | train | 0 | |
d94a0e634d12443f1b23772a1a6335742fcc536a | [
"is_logits = True\nlogit = np.array([[1, 2, -3.0], [-1, 1, 0]])\nlabels = np.array([1, 2])\nstat = amia.calculate_statistic(logit, labels, None, is_logits, 'conf with prob')\nnp.testing.assert_allclose(stat, np.array([0.72747516, 0.24472847]))\nstat = amia.calculate_statistic(logit, labels, None, is_logits, 'xe')\n... | <|body_start_0|>
is_logits = True
logit = np.array([[1, 2, -3.0], [-1, 1, 0]])
labels = np.array([1, 2])
stat = amia.calculate_statistic(logit, labels, None, is_logits, 'conf with prob')
np.testing.assert_allclose(stat, np.array([0.72747516, 0.24472847]))
stat = amia.calc... | Test calculate_statistic. | TestCalculateStatistic | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
<|body_0|>
def test_calculate_statistic_prob(self):
"""Test calculate_statistic with input as probability vector.... | stack_v2_sparse_classes_36k_train_001741 | 11,625 | permissive | [
{
"docstring": "Test calculate_statistic with input as logit.",
"name": "test_calculate_statistic_logit",
"signature": "def test_calculate_statistic_logit(self)"
},
{
"docstring": "Test calculate_statistic with input as probability vector.",
"name": "test_calculate_statistic_prob",
"sign... | 4 | stack_v2_sparse_classes_30k_train_007222 | Implement the Python class `TestCalculateStatistic` described below.
Class description:
Test calculate_statistic.
Method signatures and docstrings:
- def test_calculate_statistic_logit(self): Test calculate_statistic with input as logit.
- def test_calculate_statistic_prob(self): Test calculate_statistic with input a... | Implement the Python class `TestCalculateStatistic` described below.
Class description:
Test calculate_statistic.
Method signatures and docstrings:
- def test_calculate_statistic_logit(self): Test calculate_statistic with input as logit.
- def test_calculate_statistic_prob(self): Test calculate_statistic with input a... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
<|body_0|>
def test_calculate_statistic_prob(self):
"""Test calculate_statistic with input as probability vector.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCalculateStatistic:
"""Test calculate_statistic."""
def test_calculate_statistic_logit(self):
"""Test calculate_statistic with input as logit."""
is_logits = True
logit = np.array([[1, 2, -3.0], [-1, 1, 0]])
labels = np.array([1, 2])
stat = amia.calculate_stati... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/privacy_tests/membership_inference_attack/advanced_mia_test.py | tensorflow/privacy | train | 1,881 |
0bc1db42ce421dc2edb8afd2b4393e9731f14d00 | [
"output = []\nif args and len(args) > 0:\n for i, arg in enumerate(args):\n meta = {}\n meta['type'] = str(type(arg))\n if isinstance(arg, pd.DataFrame):\n df = arg\n meta['rows'] = len(df)\n meta['schema'] = generate_schema(df)\n samples = analiti... | <|body_start_0|>
output = []
if args and len(args) > 0:
for i, arg in enumerate(args):
meta = {}
meta['type'] = str(type(arg))
if isinstance(arg, pd.DataFrame):
df = arg
meta['rows'] = len(df)
... | A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, to the next and down to the last, then returned to caller as if the process was ju... | PipelinePlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PipelinePlugin:
"""A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, to the next and down to the last, then r... | stack_v2_sparse_classes_36k_train_001742 | 4,684 | permissive | [
{
"docstring": "Transform list of arguments into a dictionary describing them (used to log status, etc)",
"name": "get_metadata",
"signature": "def get_metadata(self, *args)"
},
{
"docstring": "Process plugins in sequence, return combined result",
"name": "run",
"signature": "def run(sel... | 2 | stack_v2_sparse_classes_30k_train_018871 | Implement the Python class `PipelinePlugin` described below.
Class description:
A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, t... | Implement the Python class `PipelinePlugin` described below.
Class description:
A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, t... | ec8ab8d5209d33502f742d62610ed33bc3b222d3 | <|skeleton|>
class PipelinePlugin:
"""A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, to the next and down to the last, then r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PipelinePlugin:
"""A plugin that creates a linear workflow by chaining together other plugins. Plugins that are chained in a pipeline need to take a single input and have a single output of the same kind so they same object can be processed from the first, to the next and down to the last, then returned to ca... | the_stack_v2_python_sparse | analitico/plugin/pipelineplugin.py | analitico/analitico-sdk | train | 2 |
114a26f379a54a0ca74551d5906e6c0040134bfb | [
"super().__init__()\nself.in_chans = in_chans\nself.out_chans = out_chans\nself.chans = chans\nself.num_pool_layers = num_pool_layers\nself.drop_prob = drop_prob\nself.reduction = reduction\nself.down_sample_layers = nn.ModuleList([ConvBlock(in_chans, chans, drop_prob, attention=False, attention_type=attention_type... | <|body_start_0|>
super().__init__()
self.in_chans = in_chans
self.out_chans = out_chans
self.chans = chans
self.num_pool_layers = num_pool_layers
self.drop_prob = drop_prob
self.reduction = reduction
self.down_sample_layers = nn.ModuleList([ConvBlock(in_ch... | PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2015. | CSEUnetModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241... | stack_v2_sparse_classes_36k_train_001743 | 10,589 | no_license | [
{
"docstring": "Args: in_chans (int): Number of channels in the input to the U-Net model. out_chans (int): Number of channels in the output to the U-Net model. chans (int): Number of output channels of the first convolution layer. num_pool_layers (int): Number of down-sampling and up-sampling layers. drop_prob ... | 2 | stack_v2_sparse_classes_30k_train_006601 | Implement the Python class `CSEUnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and comput... | Implement the Python class `CSEUnetModel` described below.
Class description:
PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and comput... | 219652c8a08c4f2f682acd9f95a4e1b3fd36b70b | <|skeleton|>
class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSEUnetModel:
"""PyTorch implementation of a U-Net model. This is based on: Olaf Ronneberger, Philipp Fischer, and Thomas Brox. U-net: Convolutional networks for biomedical image segmentation. In International Conference on Medical image computing and computer-assisted intervention, pages 234–241. Springer, 2... | the_stack_v2_python_sparse | lemawarersn_unet_conv_redundancy_removed_relu/chattn.py | Bala93/Holistic-MRI-Reconstruction | train | 1 |
035b8f157c4a46ef93095433de2e62faad8eb01b | [
"self._batch_size = batch_size\nself._static_shapes = collections.OrderedDict({key: tensor.get_shape() for key, tensor in tensor_dict.items()})\nruntime_shapes = collections.OrderedDict({key + rt_shape_str: tf.shape(tensor) for key, tensor in tensor_dict.items()})\ntensor_dict.update(runtime_shapes)\nbatched_tensor... | <|body_start_0|>
self._batch_size = batch_size
self._static_shapes = collections.OrderedDict({key: tensor.get_shape() for key, tensor in tensor_dict.items()})
runtime_shapes = collections.OrderedDict({key + rt_shape_str: tf.shape(tensor) for key, tensor in tensor_dict.items()})
tensor_di... | BatchQueue | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchQueue:
def __init__(self, tensor_dict, batch_size, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity):
"""Constructs a batch queue holding tensor_dict. Args: tensor_dict: dictionary of tensors to batch. batch_size: size of the training batch. batch_queue_capacit... | stack_v2_sparse_classes_36k_train_001744 | 8,752 | permissive | [
{
"docstring": "Constructs a batch queue holding tensor_dict. Args: tensor_dict: dictionary of tensors to batch. batch_size: size of the training batch. batch_queue_capacity: max capacity of queue from which the tensors are batched. num_batch_queue_threads: number of threads to use for batching. prefetch_queue_... | 2 | stack_v2_sparse_classes_30k_train_014498 | Implement the Python class `BatchQueue` described below.
Class description:
Implement the BatchQueue class.
Method signatures and docstrings:
- def __init__(self, tensor_dict, batch_size, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity): Constructs a batch queue holding tensor_dict. Args: tenso... | Implement the Python class `BatchQueue` described below.
Class description:
Implement the BatchQueue class.
Method signatures and docstrings:
- def __init__(self, tensor_dict, batch_size, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity): Constructs a batch queue holding tensor_dict. Args: tenso... | 445efaeef10960de9eaad6577f78d1df5b02418a | <|skeleton|>
class BatchQueue:
def __init__(self, tensor_dict, batch_size, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity):
"""Constructs a batch queue holding tensor_dict. Args: tensor_dict: dictionary of tensors to batch. batch_size: size of the training batch. batch_queue_capacit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchQueue:
def __init__(self, tensor_dict, batch_size, batch_queue_capacity, num_batch_queue_threads, prefetch_queue_capacity):
"""Constructs a batch queue holding tensor_dict. Args: tensor_dict: dictionary of tensors to batch. batch_size: size of the training batch. batch_queue_capacity: max capacit... | the_stack_v2_python_sparse | src/model_builders/base_model.py | wx-b/DIRL | train | 0 | |
5a11575d7c72aaf583c4c5de6518ce49b9ff5e39 | [
"super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)\nif distribution:\n self.distribution = distribution\nelse:\n raise TypeError('InitRiseVelFromDropletSizeFromDist requires a distribution for droplet sizes')\nself.water_viscosity = water_viscosity\nself.water_density = water_density\nself.ar... | <|body_start_0|>
super(InitRiseVelFromDropletSizeFromDist, self).__init__(**kwargs)
if distribution:
self.distribution = distribution
else:
raise TypeError('InitRiseVelFromDropletSizeFromDist requires a distribution for droplet sizes')
self.water_viscosity = water... | InitRiseVelFromDropletSizeFromDist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_36k_train_001745 | 13,705 | no_license | [
{
"docstring": "Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet size. Even though the droplet size is not changing over time, it is still stored in data array, as it can be useful for post-pro... | 2 | null | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | Implement the Python class `InitRiseVelFromDropletSizeFromDist` described below.
Class description:
Implement the InitRiseVelFromDropletSizeFromDist class.
Method signatures and docstrings:
- def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs): Set the droplet size from a dist... | 2e24d53b8b1099022a08ad73377ed6d1c7838f0f | <|skeleton|>
class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InitRiseVelFromDropletSizeFromDist:
def __init__(self, distribution=None, water_density=1020.0, water_viscosity=1e-06, **kwargs):
"""Set the droplet size from a distribution. Use the C++ get_rise_velocity function exposed via cython (rise_velocity_from_drop_size) to obtain rise_velocity from droplet s... | the_stack_v2_python_sparse | py_gnome/gnome/spill/elements/initializers.py | bhattvihang/PyGnome | train | 1 | |
89066286f11ac5633b5be45d5ed9835a356b0898 | [
"endpoint = 'videos/{}'.format(video_id)\nparams = {'text_format': text_format or self.response_format}\nreturn self._make_request(path=endpoint, params_=params, public_api=True)",
"msg = 'Pass only one of `album_id`, `article_id`, `song_id` and `video_id`., not more than one.'\ncondition = sum([bool(album_id), b... | <|body_start_0|>
endpoint = 'videos/{}'.format(video_id)
params = {'text_format': text_format or self.response_format}
return self._make_request(path=endpoint, params_=params, public_api=True)
<|end_body_0|>
<|body_start_1|>
msg = 'Pass only one of `album_id`, `article_id`, `song_id` an... | Video methods of the public API. | VideoMethods | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Ret... | stack_v2_sparse_classes_36k_train_001746 | 2,796 | permissive | [
{
"docstring": "Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Returns: :obj:`dict`",
"name": "video",
"signature": "def video(self, video_id, text_format=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_015931 | Implement the Python class `VideoMethods` described below.
Class description:
Video methods of the public API.
Method signatures and docstrings:
- def video(self, video_id, text_format=None): Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format o... | Implement the Python class `VideoMethods` described below.
Class description:
Video methods of the public API.
Method signatures and docstrings:
- def video(self, video_id, text_format=None): Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format o... | a702f5f0161bfcb28dd52dbfa96ab3192c36ed93 | <|skeleton|>
class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoMethods:
"""Video methods of the public API."""
def video(self, video_id, text_format=None):
"""Gets data for a specific video. Args: video_id (:obj:`int`): Genius video ID text_format (:obj:`str`, optional): Text format of the results ('dom', 'html', 'markdown' or 'plain'). Returns: :obj:`d... | the_stack_v2_python_sparse | lyricsgenius/api/public_methods/video.py | johnwmillr/LyricsGenius | train | 849 |
11d7ad0146b63656733bc07d42cab8febb365031 | [
"super().__init__()\nself._cardinality = cardinality\nself._width = width\nself._start_filts = start_filts\nself._num_classes = num_classes\nself._block = block\nself._block.start_filts = start_filts\nself._layers = layers\nself.inplanes = copy.deepcopy(self._start_filts)\nself.conv1 = _StartConv(n_dim, norm_layer,... | <|body_start_0|>
super().__init__()
self._cardinality = cardinality
self._width = width
self._start_filts = start_filts
self._num_classes = num_classes
self._block = block
self._block.start_filts = start_filts
self._layers = layers
self.inplanes = ... | ResNeXt model architecture | _ResNeXt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ResNeXt:
"""ResNeXt model architecture"""
def __init__(self, block: torch.nn.Module, layers: Sequence[int], num_classes: int, in_channels: int, cardinality: int, width: int=4, start_filts: int=64, start_mode: str='7x7', n_dim: int=2, norm_layer: str='Batch'):
"""Parameters ---------... | stack_v2_sparse_classes_36k_train_001747 | 12,047 | permissive | [
{
"docstring": "Parameters ---------- block : nn.Module ResNeXt block used to build network layers : list of int defines how many blocks should be used in each stage num_classes : int number of classes in_channels : int number of input channels cardinality : int cardinality (number of groups) width : int width ... | 3 | stack_v2_sparse_classes_30k_train_017297 | Implement the Python class `_ResNeXt` described below.
Class description:
ResNeXt model architecture
Method signatures and docstrings:
- def __init__(self, block: torch.nn.Module, layers: Sequence[int], num_classes: int, in_channels: int, cardinality: int, width: int=4, start_filts: int=64, start_mode: str='7x7', n_d... | Implement the Python class `_ResNeXt` described below.
Class description:
ResNeXt model architecture
Method signatures and docstrings:
- def __init__(self, block: torch.nn.Module, layers: Sequence[int], num_classes: int, in_channels: int, cardinality: int, width: int=4, start_filts: int=64, start_mode: str='7x7', n_d... | 1078f5030b8aac2bf022daf5fa14d66f74c3c893 | <|skeleton|>
class _ResNeXt:
"""ResNeXt model architecture"""
def __init__(self, block: torch.nn.Module, layers: Sequence[int], num_classes: int, in_channels: int, cardinality: int, width: int=4, start_filts: int=64, start_mode: str='7x7', n_dim: int=2, norm_layer: str='Batch'):
"""Parameters ---------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ResNeXt:
"""ResNeXt model architecture"""
def __init__(self, block: torch.nn.Module, layers: Sequence[int], num_classes: int, in_channels: int, cardinality: int, width: int=4, start_filts: int=64, start_mode: str='7x7', n_dim: int=2, norm_layer: str='Batch'):
"""Parameters ---------- block : nn.... | the_stack_v2_python_sparse | dlutils/models/resnext.py | justusschock/dl-utils | train | 15 |
c4e3c202ab69118bd3115d021604789175f404ce | [
"embedding_model = keras_embedding_model_fn(optimizer_class, l2_norm_clip=1.0, noise_multiplier=0.5, num_microbatches=1, learning_rate=1.0, use_sequence_output=True, unconnected_gradients_to_zero=False)\ntrain_data = np.random.randint(0, 10, size=(1000, 4), dtype=np.int32)\ntrain_labels = np.random.randint(0, 2, si... | <|body_start_0|>
embedding_model = keras_embedding_model_fn(optimizer_class, l2_norm_clip=1.0, noise_multiplier=0.5, num_microbatches=1, learning_rate=1.0, use_sequence_output=True, unconnected_gradients_to_zero=False)
train_data = np.random.randint(0, 10, size=(1000, 4), dtype=np.int32)
train_l... | Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could determine if the layer in question was connected or not. In such cases, the gradients are not present for tha... | DPVectorizedOptimizerUnconnectedNodesTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPVectorizedOptimizerUnconnectedNodesTest:
"""Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could determine if the layer in question was c... | stack_v2_sparse_classes_36k_train_001748 | 44,275 | permissive | [
{
"docstring": "Tests that DP vectorized optimizers with 'None' unconnected gradients fail. Sequence models that have unconnected gradients (with 'tf.UnconnectedGradients.NONE' passed to tf.GradientTape.jacobian) will return a 'None' in the corresponding entry in the Jacobian. To mitigate this the 'unconnected_... | 3 | stack_v2_sparse_classes_30k_train_019738 | Implement the Python class `DPVectorizedOptimizerUnconnectedNodesTest` described below.
Class description:
Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could d... | Implement the Python class `DPVectorizedOptimizerUnconnectedNodesTest` described below.
Class description:
Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could d... | c92610e37aa340932ed2d963813e0890035a22bc | <|skeleton|>
class DPVectorizedOptimizerUnconnectedNodesTest:
"""Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could determine if the layer in question was c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DPVectorizedOptimizerUnconnectedNodesTest:
"""Tests for vectorized optimizers when there are unconnected nodes. Subclassed Keras models can have layers that are defined in the graph, but not connected to the input or output. Or a condition expression could determine if the layer in question was connected or n... | the_stack_v2_python_sparse | tensorflow_privacy/privacy/optimizers/dp_optimizer_keras_test.py | tensorflow/privacy | train | 1,881 |
965f1d6339bb5141077ffce23364bb82ab3b5900 | [
"self.has_value = False\nself.value = None\nself.event = threading.Event()\nself.exception = None\npromise_callback = PromiseCallback(self, callback, *args, **kwargs)\npromise_thread = threading.Thread(target=promise_callback)\npromise_thread.start()",
"try:\n self.value = callback(*args, **kwargs)\nexcept Exc... | <|body_start_0|>
self.has_value = False
self.value = None
self.event = threading.Event()
self.exception = None
promise_callback = PromiseCallback(self, callback, *args, **kwargs)
promise_thread = threading.Thread(target=promise_callback)
promise_thread.start()
<|e... | Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() will re-raise the same exception. | Promise | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() wil... | stack_v2_sparse_classes_36k_train_001749 | 21,209 | permissive | [
{
"docstring": "Initialize the promise and immediately call the supplied function. Args: callback: Function that takes the args and returns the promise value. *args: Any arguments to the target function. **kwargs: Any keyword args for the target function.",
"name": "__init__",
"signature": "def __init__... | 3 | stack_v2_sparse_classes_30k_train_020230 | Implement the Python class `Promise` described below.
Class description:
Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an except... | Implement the Python class `Promise` described below.
Class description:
Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an except... | b5d4783f99461438ca9e6a477535617fadab6ba3 | <|skeleton|>
class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() wil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Promise:
"""Class for promises to deliver a value in the future. A thread is started to run callback(args), that thread should return the value that it generates, or raise an expception. p.WaitAndGetValue() will block until a value is available. If an exception was raised, p.WaitAndGetValue() will re-raise th... | the_stack_v2_python_sparse | appengine/monorail/framework/framework_helpers.py | xinghun61/infra | train | 2 |
eac0a414cf82501d09e13ef83ebd72b2b768b748 | [
"try:\n bert_model = BertModel.from_pretrained('bert-base-uncased')\nexcept OSError:\n model_path = PathManager.get_local_path(os.path.join(datapath, 'bert_base_uncased'))\n bert_model = BertModel.from_pretrained(model_path)\nif pretrained_dpr_path:\n BertConversionUtils.load_dpr_model(bert_model, pretr... | <|body_start_0|>
try:
bert_model = BertModel.from_pretrained('bert-base-uncased')
except OSError:
model_path = PathManager.get_local_path(os.path.join(datapath, 'bert_base_uncased'))
bert_model = BertModel.from_pretrained(model_path)
if pretrained_dpr_path:
... | Utilities for converting HFBertModels to ParlAI Models. | BertConversionUtils | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertConversionUtils:
"""Utilities for converting HFBertModels to ParlAI Models."""
def load_bert_state(datapath: str, state_dict: Dict[str, torch.Tensor], pretrained_dpr_path: str, encoder_type: str='query') -> Dict[str, torch.Tensor]:
"""Load BERT State from HF Model, convert to Par... | stack_v2_sparse_classes_36k_train_001750 | 6,130 | permissive | [
{
"docstring": "Load BERT State from HF Model, convert to ParlAI Model. :param state_dict: ParlAI model state_dict :param pretrained_dpr_path: path to pretrained DPR model :param encoder_type: whether we're loading a document or query encoder. :return new_state_dict: return a state_dict with loaded weights.",
... | 3 | null | Implement the Python class `BertConversionUtils` described below.
Class description:
Utilities for converting HFBertModels to ParlAI Models.
Method signatures and docstrings:
- def load_bert_state(datapath: str, state_dict: Dict[str, torch.Tensor], pretrained_dpr_path: str, encoder_type: str='query') -> Dict[str, tor... | Implement the Python class `BertConversionUtils` described below.
Class description:
Utilities for converting HFBertModels to ParlAI Models.
Method signatures and docstrings:
- def load_bert_state(datapath: str, state_dict: Dict[str, torch.Tensor], pretrained_dpr_path: str, encoder_type: str='query') -> Dict[str, tor... | e1d899edfb92471552bae153f59ad30aa7fca468 | <|skeleton|>
class BertConversionUtils:
"""Utilities for converting HFBertModels to ParlAI Models."""
def load_bert_state(datapath: str, state_dict: Dict[str, torch.Tensor], pretrained_dpr_path: str, encoder_type: str='query') -> Dict[str, torch.Tensor]:
"""Load BERT State from HF Model, convert to Par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertConversionUtils:
"""Utilities for converting HFBertModels to ParlAI Models."""
def load_bert_state(datapath: str, state_dict: Dict[str, torch.Tensor], pretrained_dpr_path: str, encoder_type: str='query') -> Dict[str, torch.Tensor]:
"""Load BERT State from HF Model, convert to ParlAI Model. :p... | the_stack_v2_python_sparse | parlai/agents/rag/conversion_utils.py | facebookresearch/ParlAI | train | 10,943 |
f7df26f8d276ce8bc5db279a3374051c3169eb9c | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nd = data.shape[0]\nn = data.shape[1]\nself.mean = np.mean(data, axis=1).reshape(d, 1)\ndeviation = np.tile(sel... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
d = data.shape[0]
n = data.shape[1]
self.mean ... | Class that represents a Multivariate Normal distribution | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""Class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""class constructor"""
<|body_0|>
def pdf(self, x):
"""public instance method that calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_001751 | 1,414 | no_license | [
{
"docstring": "class constructor",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "public instance method that calculates the PDF at a data point",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004464 | Implement the Python class `MultiNormal` described below.
Class description:
Class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): class constructor
- def pdf(self, x): public instance method that calculates the PDF at a data point | Implement the Python class `MultiNormal` described below.
Class description:
Class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): class constructor
- def pdf(self, x): public instance method that calculates the PDF at a data point
<|skeleton|>
class M... | b1d0995023630f2a2b7ed953983c405077c0d5a8 | <|skeleton|>
class MultiNormal:
"""Class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""class constructor"""
<|body_0|>
def pdf(self, x):
"""public instance method that calculates the PDF at a data point"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiNormal:
"""Class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""class constructor"""
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | oscarmrt/holbertonschool-machine_learning | train | 1 |
af15dc2333d6fb9f33f8f7b9703e55149d65f034 | [
"mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, 'parse', return_value=datetime.datetime.now())\nmocker.patch.object(demisto, 'setLastRun')\nmocker.patch.object(demisto, 'getLastRun', return_value=None)\nmain(command='fetch-events', params=PARAMS)\nMicrosoft365DefenderEventCollector.dateparser.pa... | <|body_start_0|>
mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, 'parse', return_value=datetime.datetime.now())
mocker.patch.object(demisto, 'setLastRun')
mocker.patch.object(demisto, 'getLastRun', return_value=None)
main(command='fetch-events', params=PARAMS)
... | TestFetchEventsHappyPath | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFetchEventsHappyPath:
def test_fetch_events_first_time(self, mocker):
"""Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called."""
<|body_0|>
def test_fetch_events_second_time(self... | stack_v2_sparse_classes_36k_train_001752 | 8,420 | permissive | [
{
"docstring": "Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called.",
"name": "test_fetch_events_first_time",
"signature": "def test_fetch_events_first_time(self, mocker)"
},
{
"docstring": "Given - dem... | 3 | null | Implement the Python class `TestFetchEventsHappyPath` described below.
Class description:
Implement the TestFetchEventsHappyPath class.
Method signatures and docstrings:
- def test_fetch_events_first_time(self, mocker): Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first... | Implement the Python class `TestFetchEventsHappyPath` described below.
Class description:
Implement the TestFetchEventsHappyPath class.
Method signatures and docstrings:
- def test_fetch_events_first_time(self, mocker): Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestFetchEventsHappyPath:
def test_fetch_events_first_time(self, mocker):
"""Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called."""
<|body_0|>
def test_fetch_events_second_time(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFetchEventsHappyPath:
def test_fetch_events_first_time(self, mocker):
"""Given - there is no object returned by demist.getLastRun. When - fetch_events called for the first time. Then - ensure the dateparser was called."""
mocker.patch.object(Microsoft365DefenderEventCollector.dateparser, '... | the_stack_v2_python_sparse | Packs/MicrosoftDefenderAdvancedThreatProtection/Integrations/Microsoft365DefenderEventCollector/Microsoft365DefenderEventCollector_test.py | demisto/content | train | 1,023 | |
2131011f6b01c1bb9cd6f9163f423396aef35027 | [
"super().__init__(model_dir, *args, **kwargs)\nfrom modelscope.trainers.nlp.space.trainer.intent_trainer import IntentTrainer\nself.model_dir = model_dir\nself.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))\nself.text_field = kwargs.pop('text_field', IntentBPE... | <|body_start_0|>
super().__init__(model_dir, *args, **kwargs)
from modelscope.trainers.nlp.space.trainer.intent_trainer import IntentTrainer
self.model_dir = model_dir
self.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))
self... | SpaceForDialogIntent | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceForDialogIntent:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path. text_field (`BPETextField`, *optional*, defaults to `IntentBPETextField`): The text field. config (`Config`... | stack_v2_sparse_classes_36k_train_001753 | 3,832 | permissive | [
{
"docstring": "initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path. text_field (`BPETextField`, *optional*, defaults to `IntentBPETextField`): The text field. config (`Config`, *optional*, defaults to config in model hub): The config.",
"name": "__init__",
... | 2 | null | Implement the Python class `SpaceForDialogIntent` described below.
Class description:
Implement the SpaceForDialogIntent class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path... | Implement the Python class `SpaceForDialogIntent` described below.
Class description:
Implement the SpaceForDialogIntent class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SpaceForDialogIntent:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path. text_field (`BPETextField`, *optional*, defaults to `IntentBPETextField`): The text field. config (`Config`... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpaceForDialogIntent:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (str): the model path. text_field (`BPETextField`, *optional*, defaults to `IntentBPETextField`): The text field. config (`Config`, *optional*, ... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/nlp/space/dialog_intent_prediction.py | alldatacenter/alldata | train | 774 | |
dfb6dffb0f177d15b329a7ec41cdbdf6521be772 | [
"try:\n serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)\n return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)\nexcept Exception as e:\n info_message = 'Internal Server Error'\n logger.error(info_message, e)\n return JsonResponse({'error'... | <|body_start_0|>
try:
serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exception as e:
info_message = 'Internal Server Error'
logger.e... | RadiologistPmtView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
<|body_0|>
def post(self, request):
"""Save Radiologist data"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
serializer = RadiologistPmtSerializers(Radiol... | stack_v2_sparse_classes_36k_train_001754 | 31,833 | no_license | [
{
"docstring": "Get all Radiologist_Payment",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Save Radiologist data",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021299 | Implement the Python class `RadiologistPmtView` described below.
Class description:
Implement the RadiologistPmtView class.
Method signatures and docstrings:
- def get(self, request): Get all Radiologist_Payment
- def post(self, request): Save Radiologist data | Implement the Python class `RadiologistPmtView` described below.
Class description:
Implement the RadiologistPmtView class.
Method signatures and docstrings:
- def get(self, request): Get all Radiologist_Payment
- def post(self, request): Save Radiologist data
<|skeleton|>
class RadiologistPmtView:
def get(self... | b63849983a592fd6a1f654191020fd86aa0787ae | <|skeleton|>
class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
<|body_0|>
def post(self, request):
"""Save Radiologist data"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RadiologistPmtView:
def get(self, request):
"""Get all Radiologist_Payment"""
try:
serializer = RadiologistPmtSerializers(RadiologistPmt.objects.all(), many=True)
return JsonResponse({'message': 'listed all', 'data': serializer.data}, status=200)
except Exceptio... | the_stack_v2_python_sparse | radiologist/views.py | RupeshKurlekar/biocare | train | 1 | |
4034d3ea8b4cd744fddd37dc3c864aed42ba145b | [
"ans = defaultdict(list)\nfor s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord('a')] += 1\n ans[tuple(count)].append(s)\nreturn ans.values()",
"ans = defaultdict(list)\nall_chars = string.ascii_lowercase\nfor s in strs:\n count = [s.count(ch) for ch in all_chars]\n ans[tuple(... | <|body_start_0|>
ans = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ans.values()
<|end_body_0|>
<|body_start_1|>
ans = defaultdict(list)
all_char... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams_v2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
def groupAnagrams_v1(self, strs):
""":type st... | stack_v2_sparse_classes_36k_train_001755 | 4,245 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams_v2",
"signature": "def groupAnagrams_v2(self, strs)"
},
{
... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams_v2(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams_v2(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams... | b5e09f24e8e96454dc99e20281e853fb9fcc85ed | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams_v2(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
def groupAnagrams_v1(self, strs):
""":type st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
ans = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord('a')] += 1
ans[tuple(count)].append(s)
return ... | the_stack_v2_python_sparse | python/49_Group_Anagrams.py | Moby5/myleetcode | train | 2 | |
c924a380ca8e0c370ee6c5e5f65534492fb2b496 | [
"try:\n account_id = resource_utils.get_account_id(request)\n if not is_staff(jwt) and account_id is None:\n return resource_utils.account_required_response()\n if not authorized(account_id, jwt):\n return resource_utils.unauthorized_error_response(account_id)\n token = g.jwt_oidc_token_in... | <|body_start_0|>
try:
account_id = resource_utils.get_account_id(request)
if not is_staff(jwt) and account_id is None:
return resource_utils.account_required_response()
if not authorized(account_id, jwt):
return resource_utils.unauthorized_erro... | Resource for maintaining user profile UI preferences. | UserProfileResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileResource:
"""Resource for maintaining user profile UI preferences."""
def get():
"""Get existing user profile UI settings for the user represented by the request JWT."""
<|body_0|>
def patch():
"""Update user profile UI settings for the user represente... | stack_v2_sparse_classes_36k_train_001756 | 6,907 | permissive | [
{
"docstring": "Get existing user profile UI settings for the user represented by the request JWT.",
"name": "get",
"signature": "def get()"
},
{
"docstring": "Update user profile UI settings for the user represented by the request JWT.",
"name": "patch",
"signature": "def patch()"
}
] | 2 | null | Implement the Python class `UserProfileResource` described below.
Class description:
Resource for maintaining user profile UI preferences.
Method signatures and docstrings:
- def get(): Get existing user profile UI settings for the user represented by the request JWT.
- def patch(): Update user profile UI settings fo... | Implement the Python class `UserProfileResource` described below.
Class description:
Resource for maintaining user profile UI preferences.
Method signatures and docstrings:
- def get(): Get existing user profile UI settings for the user represented by the request JWT.
- def patch(): Update user profile UI settings fo... | af1a4458bb78c16ecca484514d4bd0d1d8c24b5d | <|skeleton|>
class UserProfileResource:
"""Resource for maintaining user profile UI preferences."""
def get():
"""Get existing user profile UI settings for the user represented by the request JWT."""
<|body_0|>
def patch():
"""Update user profile UI settings for the user represente... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileResource:
"""Resource for maintaining user profile UI preferences."""
def get():
"""Get existing user profile UI settings for the user represented by the request JWT."""
try:
account_id = resource_utils.get_account_id(request)
if not is_staff(jwt) and ac... | the_stack_v2_python_sparse | ppr-api/src/ppr_api/resources/user_profile.py | bcgov/ppr | train | 4 |
1bf576bcaa1da4d5260f359130eab2f8055198f2 | [
"self._string = string\nself._terminals = {symbol for symbol in string if symbol not in '()|+?.*'}\nself._normalize()",
"string = self._string\nif len(string) == 0:\n return\npos = 0\nfor i in range(0, len(self._string) - 1):\n pair = self._string[i:i + 2]\n if pair[0] in self._terminals and pair[1] in s... | <|body_start_0|>
self._string = string
self._terminals = {symbol for symbol in string if symbol not in '()|+?.*'}
self._normalize()
<|end_body_0|>
<|body_start_1|>
string = self._string
if len(string) == 0:
return
pos = 0
for i in range(0, len(self._s... | Classe que representa a Expressão Regular | RegularExpression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegularExpression:
"""Classe que representa a Expressão Regular"""
def __init__(self, string):
"""Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string"""
<|body_0|>
def _normalize(self):
"""Normaliza a expressão regular a... | stack_v2_sparse_classes_36k_train_001757 | 17,454 | no_license | [
{
"docstring": "Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string",
"name": "__init__",
"signature": "def __init__(self, string)"
},
{
"docstring": "Normaliza a expressão regular ainda como string, adicionando as concatenações que não estão visíveis e... | 5 | stack_v2_sparse_classes_30k_train_008091 | Implement the Python class `RegularExpression` described below.
Class description:
Classe que representa a Expressão Regular
Method signatures and docstrings:
- def __init__(self, string): Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string
- def _normalize(self): Normaliza ... | Implement the Python class `RegularExpression` described below.
Class description:
Classe que representa a Expressão Regular
Method signatures and docstrings:
- def __init__(self, string): Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string
- def _normalize(self): Normaliza ... | b167f12f77a2481a8cf97a570c408e73756c2e07 | <|skeleton|>
class RegularExpression:
"""Classe que representa a Expressão Regular"""
def __init__(self, string):
"""Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string"""
<|body_0|>
def _normalize(self):
"""Normaliza a expressão regular a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegularExpression:
"""Classe que representa a Expressão Regular"""
def __init__(self, string):
"""Construtor da Expressão Regular @param string Expressão Regular na forma de uma simples string"""
self._string = string
self._terminals = {symbol for symbol in string if symbol not in... | the_stack_v2_python_sparse | regular_expression.py | diegomaicon/Formal-Language-Simulator | train | 0 |
6bdfce7a70637badc0f89223b31298195fc86920 | [
"super().__init__(bounds=bounds, dimension=dimension, posrng=posrng)\nndunit_region = Region.from_interval(Interval(0, 1), self.dimension)\nif sizepc is None:\n sizepc = ndunit_region\nif isinstance(sizepc, float) or isinstance(sizepc, int):\n sizepc = Region.from_interval(Interval(0, sizepc), self.dimension)... | <|body_start_0|>
super().__init__(bounds=bounds, dimension=dimension, posrng=posrng)
ndunit_region = Region.from_interval(Interval(0, 1), self.dimension)
if sizepc is None:
sizepc = ndunit_region
if isinstance(sizepc, float) or isinstance(sizepc, int):
sizepc = Re... | Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The number of dimensions of all Regions generated posrng: method or list of methods (... | RegionGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegionGenerator:
"""Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The number of dimensions of all Regions ge... | stack_v2_sparse_classes_36k_train_001758 | 5,228 | no_license | [
{
"docstring": "Initialize data generator with user-specified parameters. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The number of dimensions of all Regions generated posrng: method or list of m... | 3 | stack_v2_sparse_classes_30k_train_015319 | Implement the Python class `RegionGenerator` described below.
Class description:
Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The... | Implement the Python class `RegionGenerator` described below.
Class description:
Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The... | 0394980efc628bfedd4fd504079a534418cbb89a | <|skeleton|>
class RegionGenerator:
"""Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The number of dimensions of all Regions ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegionGenerator:
"""Region generator singleton class. Random generation of regions or graphs. Params ------ bounds : Region (optional, default: None) A region with the outer bounds of the observation space dimension : int (optional, default: bounds or 2) The number of dimensions of all Regions generated posrn... | the_stack_v2_python_sparse | generators/regions/region_generator.py | tipech/spatialnet | train | 1 |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(NAM, self).__init__()\nself._num_inputs = num_inputs\nif isinstance(num_units, list):\n assert len(num_units) == num_inputs\n self._num_units = num_units\nelif isinstance(num_units, int):\n self._num_units = [num_units for _ in range(self._num_inputs)]\nself._trainable = trainable\nself._shallow = s... | <|body_start_0|>
super(NAM, self).__init__()
self._num_inputs = num_inputs
if isinstance(num_units, list):
assert len(num_units) == num_inputs
self._num_units = num_units
elif isinstance(num_units, int):
self._num_units = [num_units for _ in range(self... | Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature. | NAM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of fe... | stack_v2_sparse_classes_36k_train_001759 | 10,796 | permissive | [
{
"docstring": "Initializes NAM hyperparameters. Args: num_inputs: Number of feature inputs in input data. num_units: Number of hidden units in first layer of each feature net. trainable: Whether the NAM parameters are trainable or not. shallow: If True, then shallow feature nets with a single hidden layer are ... | 5 | stack_v2_sparse_classes_30k_train_017402 | Implement the Python class `NAM` described below.
Class description:
Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature.
Method signatures and docstrings:
- def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs): Initia... | Implement the Python class `NAM` described below.
Class description:
Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature.
Method signatures and docstrings:
- def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs): Initia... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of fe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NAM:
"""Neural additive model. Attributes: feature_nns: List of FeatureNN, one per input feature."""
def __init__(self, num_inputs, num_units, trainable=True, shallow=True, feature_dropout=0.0, dropout=0.0, **kwargs):
"""Initializes NAM hyperparameters. Args: num_inputs: Number of feature inputs ... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
892773e94c88097ddf0b6ac2e2ea83ce9032854c | [
"self.started = time.time()\nself.maxdelay = maxdelay\nself.until = self.started + timeout\nself.delay = 1.0 / self.DELAY_MULTIPLIER",
"if self.until < time.time():\n raise StopIteration()\nself.delay = min(self.delay * self.DELAY_MULTIPLIER, self.maxdelay)\nreturn self.delay"
] | <|body_start_0|>
self.started = time.time()
self.maxdelay = maxdelay
self.until = self.started + timeout
self.delay = 1.0 / self.DELAY_MULTIPLIER
<|end_body_0|>
<|body_start_1|>
if self.until < time.time():
raise StopIteration()
self.delay = min(self.delay * ... | Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value. | _RetryIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RetryIterator:
"""Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value."""
def __init__(self, maxdelay=MAX_DELAY_SE... | stack_v2_sparse_classes_36k_train_001760 | 8,039 | no_license | [
{
"docstring": "Initialize an instance of _RetryIterator. @param maxdelay {float} Maximum delay interval (seconds). @param timeout {float} Timeout duration (seconds).",
"name": "__init__",
"signature": "def __init__(self, maxdelay=MAX_DELAY_SECONDS, timeout=TIMEOUT_SECONDS)"
},
{
"docstring": "R... | 2 | null | Implement the Python class `_RetryIterator` described below.
Class description:
Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value.
Method s... | Implement the Python class `_RetryIterator` described below.
Class description:
Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value.
Method s... | 1ea508c3d2b51742bc3b448c445cd0a3dba9e798 | <|skeleton|>
class _RetryIterator:
"""Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value."""
def __init__(self, maxdelay=MAX_DELAY_SE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RetryIterator:
"""Provides an interator that returns a delay interval (seconds) in sucession until a predetermined amount of time has passed. Each returned delay value is larger than the prior value but will not exceed the MAX_DELAY_SECONDS value."""
def __init__(self, maxdelay=MAX_DELAY_SECONDS, timeou... | the_stack_v2_python_sparse | Products/ZenUtils/ZCmdBase.py | zenoss/zenoss-prodbin | train | 27 |
11c5f7a9cca985f5e6f0479dccefa91432f0ab0f | [
"ext = pkt.get_field(self.length_of)\ntmp_len = ext.length_from(pkt)\nif tmp_len is None or tmp_len <= 0:\n v = pkt.tls_session.tls_version\n if v is None or v < 772:\n return (s, None)\nreturn super(_ExtensionsLenField, self).getfield(pkt, s)",
"if i is None:\n if self.length_of is not None:\n ... | <|body_start_0|>
ext = pkt.get_field(self.length_of)
tmp_len = ext.length_from(pkt)
if tmp_len is None or tmp_len <= 0:
v = pkt.tls_session.tls_version
if v is None or v < 772:
return (s, None)
return super(_ExtensionsLenField, self).getfield(pkt, ... | _ExtensionsLenField | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ExtensionsLenField:
def getfield(self, pkt, s):
"""We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero length... | stack_v2_sparse_classes_36k_train_001761 | 31,184 | permissive | [
{
"docstring": "We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always explicit.",
"name": "getfield",
"signat... | 2 | null | Implement the Python class `_ExtensionsLenField` described below.
Class description:
Implement the _ExtensionsLenField class.
Method signatures and docstrings:
- def getfield(self, pkt, s): We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC... | Implement the Python class `_ExtensionsLenField` described below.
Class description:
Implement the _ExtensionsLenField class.
Method signatures and docstrings:
- def getfield(self, pkt, s): We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC... | e6cccba69335816442c515d65d9aedea9e7dc58b | <|skeleton|>
class _ExtensionsLenField:
def getfield(self, pkt, s):
"""We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero length... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ExtensionsLenField:
def getfield(self, pkt, s):
"""We try to compute a length, usually from a msglen parsed earlier. If this length is 0, we consider 'selection_present' (from RFC 5246) to be False. This means that there should not be any length field. However, with TLS 1.3, zero lengths are always e... | the_stack_v2_python_sparse | Botnets/App/App Web/PDG-env/lib/python3.6/site-packages/scapy/layers/tls/extensions.py | i2tResearch/Ciberseguridad_web | train | 14 | |
b397584c6862479af3503c821a6b16ef5f638134 | [
"self.itemAll = []\nself.train = dict()\nself.test = dict()\nself.userList = set()\nself.itemList = set()\nself.readData(seed, M, k)",
"random.seed(seed)\ndata = open('../../data/MoviesLensSmall/u.data').readlines()\ncnt = 0\nfor each in data:\n each = each.split('\\t')[:2]\n cnt += 1\n if random.randint... | <|body_start_0|>
self.itemAll = []
self.train = dict()
self.test = dict()
self.userList = set()
self.itemList = set()
self.readData(seed, M, k)
<|end_body_0|>
<|body_start_1|>
random.seed(seed)
data = open('../../data/MoviesLensSmall/u.data').readlines()
... | DataSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSet:
def __init__(self, seed, M, k):
"""paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the list of all item (no discrete) train : training data (userID , itemID) test : testing data userLi... | stack_v2_sparse_classes_36k_train_001762 | 2,684 | no_license | [
{
"docstring": "paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the list of all item (no discrete) train : training data (userID , itemID) test : testing data userList : for training data , the list of all userID (dis... | 3 | stack_v2_sparse_classes_30k_train_014264 | Implement the Python class `DataSet` described below.
Class description:
Implement the DataSet class.
Method signatures and docstrings:
- def __init__(self, seed, M, k): paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the l... | Implement the Python class `DataSet` described below.
Class description:
Implement the DataSet class.
Method signatures and docstrings:
- def __init__(self, seed, M, k): paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the l... | 98c0280097ad5b7ccbf9c43f656042a8a791eed7 | <|skeleton|>
class DataSet:
def __init__(self, seed, M, k):
"""paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the list of all item (no discrete) train : training data (userID , itemID) test : testing data userLi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSet:
def __init__(self, seed, M, k):
"""paraments : seed : random seed M : how many parts the data split k : the part whitch choose for testing return : itemAll : for training data , the list of all item (no discrete) train : training data (userID , itemID) test : testing data userList : for train... | the_stack_v2_python_sparse | src/LFM/dataProcess.py | cxlove/RecommendSystem | train | 0 | |
67d756bc18026020fbec85e07fd5949673be92f4 | [
"super(XOriginUPAbstractCalculateStrategy, self).__init__()\nself.historical_avg_unit_price_of_last_month = p_historical_avg_unit_price_of_last_month\nself.theoryUPDefaultCalculateStrategy = XTheoryUPAbstractCalculateStrategy() if p_theoryUPDefaultCalculateStrategy == None else p_theoryUPDefaultCalculateStrategy",
... | <|body_start_0|>
super(XOriginUPAbstractCalculateStrategy, self).__init__()
self.historical_avg_unit_price_of_last_month = p_historical_avg_unit_price_of_last_month
self.theoryUPDefaultCalculateStrategy = XTheoryUPAbstractCalculateStrategy() if p_theoryUPDefaultCalculateStrategy == None else p_t... | 理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_price - historical_avg_unit_price_of_last_month * 0.06) origin_unit_price = min( tmp, historical_avg_un... | XOriginalUPDefaultCalculateStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XOriginalUPDefaultCalculateStrategy:
"""理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_price - historical_avg_unit_price_of_las... | stack_v2_sparse_classes_36k_train_001763 | 2,236 | no_license | [
{
"docstring": ":param p_line: :param p_date:",
"name": "__init__",
"signature": "def __init__(self, p_historical_avg_unit_price_of_last_month=None, p_theoryUPDefaultCalculateStrategy=None)"
},
{
"docstring": ":return:",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012419 | Implement the Python class `XOriginalUPDefaultCalculateStrategy` described below.
Class description:
理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_p... | Implement the Python class `XOriginalUPDefaultCalculateStrategy` described below.
Class description:
理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_p... | 45101c3b60ab3e37c6defeb1252756d07e820951 | <|skeleton|>
class XOriginalUPDefaultCalculateStrategy:
"""理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_price - historical_avg_unit_price_of_las... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XOriginalUPDefaultCalculateStrategy:
"""理论单价是我这次预期的成交价格, 但我不能一开始就定价定成它 所以我现在要定一个稍微低一点的价格, 这样有可能我会以更低的价格出手 然后我每次加价是历史单价的百分之3 我期望是在第2次也就是加价6%时成交, 这样我初始单价就设置成理论成交价减去历史价的6% tmp = max( (theory_unit_price + historical_avg_unit_price_of_last_month)/2, theory_unit_price - historical_avg_unit_price_of_last_month * 0.0... | the_stack_v2_python_sparse | app/grab/up_calculate_strategy/origin/XOriginalUPDefaultCalculateStrategy.py | shsun/geo_de_dup_project | train | 0 |
dee7f9da6b89c42093c87f9084e435cad8e42cac | [
"inv_sqrt_diagonal = gs.power(Matrices.diagonal(base_point), -2)\ntangent_vec_a_diagonal = Matrices.diagonal(tangent_vec_a)\ntangent_vec_b_diagonal = Matrices.diagonal(tangent_vec_b)\nprod = tangent_vec_a_diagonal * tangent_vec_b_diagonal * inv_sqrt_diagonal\nreturn gs.sum(prod, axis=-1)",
"sl_tagnet_vec_a = gs.t... | <|body_start_0|>
inv_sqrt_diagonal = gs.power(Matrices.diagonal(base_point), -2)
tangent_vec_a_diagonal = Matrices.diagonal(tangent_vec_a)
tangent_vec_b_diagonal = Matrices.diagonal(tangent_vec_b)
prod = tangent_vec_a_diagonal * tangent_vec_b_diagonal * inv_sqrt_diagonal
return g... | Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326 | CholeskyMetric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CholeskyMetric:
"""Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326"""
def diag_i... | stack_v2_sparse_classes_36k_train_001764 | 11,271 | permissive | [
{
"docstring": "Compute the inner product using only diagonal elements. Parameters ---------- tangent_vec_a : array-like, shape=[..., n, n] Tangent vector at base point. tangent_vec_b : array-like, shape=[..., n, n] Tangent vector at base point. base_point : array-like, shape=[..., n, n] Base point. Returns ---... | 6 | stack_v2_sparse_classes_30k_train_006799 | Implement the Python class `CholeskyMetric` described below.
Class description:
Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxi... | Implement the Python class `CholeskyMetric` described below.
Class description:
Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxi... | 78a5778b5d5ce85225fd97e765d43047fb4526d1 | <|skeleton|>
class CholeskyMetric:
"""Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326"""
def diag_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CholeskyMetric:
"""Class for Cholesky metric on Cholesky space. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326"""
def diag_inner_product(... | the_stack_v2_python_sparse | geomstats/geometry/positive_lower_triangular_matrices.py | geomstats/geomstats | train | 1,017 |
767662a64c994653c397e5016efc57adedbaeef3 | [
"self.Wh = np.random.normal(size=(i + h, h))\nself.Wy = np.random.normal(size=(h, o))\nself.bh = np.zeros((1, h))\nself.by = np.zeros((1, o))",
"xh = np.concatenate((h_prev, x_t), axis=1)\nh_next = np.tanh(np.dot(xh, self.Wh) + self.bh)\ny = np.dot(h_next, self.Wy) + self.by\ny = np.exp(y) / np.sum(np.exp(y), axi... | <|body_start_0|>
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
<|end_body_0|>
<|body_start_1|>
xh = np.concatenate((h_prev, x_t), axis=1)
h_next = np.tanh(np.dot(xh, self.Wh) + se... | Class that represents a cell of a simple RNN | RNNCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Function that performs forward propagation for one time step"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_001765 | 737 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, i, h, o)"
},
{
"docstring": "Function that performs forward propagation for one time step",
"name": "forward",
"signature": "def forward(self, h_prev, x_t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007458 | Implement the Python class `RNNCell` described below.
Class description:
Class that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor
- def forward(self, h_prev, x_t): Function that performs forward propagation for one time step | Implement the Python class `RNNCell` described below.
Class description:
Class that represents a cell of a simple RNN
Method signatures and docstrings:
- def __init__(self, i, h, o): Constructor
- def forward(self, h_prev, x_t): Function that performs forward propagation for one time step
<|skeleton|>
class RNNCell:... | 9dbf8221d4eb22dbc2487cb55e84a801a38aa5c8 | <|skeleton|>
class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor"""
<|body_0|>
def forward(self, h_prev, x_t):
"""Function that performs forward propagation for one time step"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNCell:
"""Class that represents a cell of a simple RNN"""
def __init__(self, i, h, o):
"""Constructor"""
self.Wh = np.random.normal(size=(i + h, h))
self.Wy = np.random.normal(size=(h, o))
self.bh = np.zeros((1, h))
self.by = np.zeros((1, o))
def forward(sel... | the_stack_v2_python_sparse | supervised_learning/0x0D-RNNs/0-rnn_cell.py | yasmineholb/holbertonschool-machine_learning | train | 0 |
00f277ec85fc7b9958882e7659d44286a75fffa6 | [
"try:\n self.predicted_intent = eval_store.intent_predictions[0]\nexcept LookupError:\n self.predicted_intent = None\nself.target_entities = eval_store.entity_targets\nself.predicted_entities = eval_store.entity_predictions\nintent = {'name': eval_store.intent_targets[0]}\nsuper().__init__(event.text, intent,... | <|body_start_0|>
try:
self.predicted_intent = eval_store.intent_predictions[0]
except LookupError:
self.predicted_intent = None
self.target_entities = eval_store.entity_targets
self.predicted_entities = eval_store.entity_predictions
intent = {'name': eval_... | The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories. | WronglyClassifiedUserUtterance | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WronglyClassifiedUserUtterance:
"""The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories."""
def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None:
"""Set `predicted_intent` and `predicted_ent... | stack_v2_sparse_classes_36k_train_001766 | 48,935 | permissive | [
{
"docstring": "Set `predicted_intent` and `predicted_entities` attributes.",
"name": "__init__",
"signature": "def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None"
},
{
"docstring": "A comment attached to this event. Used during dumping.",
"name": "inline_comment",
... | 4 | null | Implement the Python class `WronglyClassifiedUserUtterance` described below.
Class description:
The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories.
Method signatures and docstrings:
- def __init__(self, event: UserUttered, eval_store: Evaluation... | Implement the Python class `WronglyClassifiedUserUtterance` described below.
Class description:
The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories.
Method signatures and docstrings:
- def __init__(self, event: UserUttered, eval_store: Evaluation... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class WronglyClassifiedUserUtterance:
"""The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories."""
def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None:
"""Set `predicted_intent` and `predicted_ent... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WronglyClassifiedUserUtterance:
"""The NLU model predicted the wrong user utterance. Mostly used to mark wrong predictions and be able to dump them as stories."""
def __init__(self, event: UserUttered, eval_store: EvaluationStore) -> None:
"""Set `predicted_intent` and `predicted_entities` attrib... | the_stack_v2_python_sparse | rasa/core/test.py | RasaHQ/rasa | train | 13,167 |
9524a849bd16f9fa793e54f920cc6cf1227a8ec1 | [
"comment = Comment.objects.get(pk=kwargs['comment_pk'])\nif self.request.user.is_authenticated():\n if self.request.user == comment.comment_author:\n editcomment_serializer = self.serializer_class(comment, data=request.data, partial=True)\n editcomment_serializer.is_valid(raise_exception=True)\n ... | <|body_start_0|>
comment = Comment.objects.get(pk=kwargs['comment_pk'])
if self.request.user.is_authenticated():
if self.request.user == comment.comment_author:
editcomment_serializer = self.serializer_class(comment, data=request.data, partial=True)
editcommen... | 댓글 수정 및 삭제 | CommentDetailRetrieveUpdateDestroyView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentDetailRetrieveUpdateDestroyView:
"""댓글 수정 및 삭제"""
def put(self, request, *args, **kwargs):
"""댓글 수정"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""댓글 삭제"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
comment = Comment.objec... | stack_v2_sparse_classes_36k_train_001767 | 4,124 | no_license | [
{
"docstring": "댓글 수정",
"name": "put",
"signature": "def put(self, request, *args, **kwargs)"
},
{
"docstring": "댓글 삭제",
"name": "delete",
"signature": "def delete(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020685 | Implement the Python class `CommentDetailRetrieveUpdateDestroyView` described below.
Class description:
댓글 수정 및 삭제
Method signatures and docstrings:
- def put(self, request, *args, **kwargs): 댓글 수정
- def delete(self, request, *args, **kwargs): 댓글 삭제 | Implement the Python class `CommentDetailRetrieveUpdateDestroyView` described below.
Class description:
댓글 수정 및 삭제
Method signatures and docstrings:
- def put(self, request, *args, **kwargs): 댓글 수정
- def delete(self, request, *args, **kwargs): 댓글 삭제
<|skeleton|>
class CommentDetailRetrieveUpdateDestroyView:
"""댓... | 4031afe1b5d45865a61f4ff4136a8314258a917a | <|skeleton|>
class CommentDetailRetrieveUpdateDestroyView:
"""댓글 수정 및 삭제"""
def put(self, request, *args, **kwargs):
"""댓글 수정"""
<|body_0|>
def delete(self, request, *args, **kwargs):
"""댓글 삭제"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentDetailRetrieveUpdateDestroyView:
"""댓글 수정 및 삭제"""
def put(self, request, *args, **kwargs):
"""댓글 수정"""
comment = Comment.objects.get(pk=kwargs['comment_pk'])
if self.request.user.is_authenticated():
if self.request.user == comment.comment_author:
... | the_stack_v2_python_sparse | django_app/motif/apis/comment.py | Monaegi/Julia-WordyGallery | train | 1 |
5ee937ced5a77d338602e7d14205dbeaa6cf50e5 | [
"if user_input is None:\n user_input = {}\nreturn self.async_show_form(step_id='user', data_schema=vol.Schema({vol.Required(CONF_STATION_CODE, default=user_input.get(CONF_STATION_CODE, '')): str}), errors=errors or {})",
"errors = {}\nif user_input is None:\n return self._show_setup_form(user_input, errors)... | <|body_start_0|>
if user_input is None:
user_input = {}
return self.async_show_form(step_id='user', data_schema=vol.Schema({vol.Required(CONF_STATION_CODE, default=user_input.get(CONF_STATION_CODE, '')): str}), errors=errors or {})
<|end_body_0|>
<|body_start_1|>
errors = {}
... | Handle a Meteoclimatic config flow. | MeteoclimaticFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeteoclimaticFlowHandler:
"""Handle a Meteoclimatic config flow."""
def _show_setup_form(self, user_input=None, errors=None):
"""Show the setup form to the user."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the use... | stack_v2_sparse_classes_36k_train_001768 | 2,082 | permissive | [
{
"docstring": "Show the setup form to the user.",
"name": "_show_setup_form",
"signature": "def _show_setup_form(self, user_input=None, errors=None)"
},
{
"docstring": "Handle a flow initiated by the user.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_i... | 2 | stack_v2_sparse_classes_30k_train_001657 | Implement the Python class `MeteoclimaticFlowHandler` described below.
Class description:
Handle a Meteoclimatic config flow.
Method signatures and docstrings:
- def _show_setup_form(self, user_input=None, errors=None): Show the setup form to the user.
- async def async_step_user(self, user_input=None): Handle a flow... | Implement the Python class `MeteoclimaticFlowHandler` described below.
Class description:
Handle a Meteoclimatic config flow.
Method signatures and docstrings:
- def _show_setup_form(self, user_input=None, errors=None): Show the setup form to the user.
- async def async_step_user(self, user_input=None): Handle a flow... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class MeteoclimaticFlowHandler:
"""Handle a Meteoclimatic config flow."""
def _show_setup_form(self, user_input=None, errors=None):
"""Show the setup form to the user."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Handle a flow initiated by the use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeteoclimaticFlowHandler:
"""Handle a Meteoclimatic config flow."""
def _show_setup_form(self, user_input=None, errors=None):
"""Show the setup form to the user."""
if user_input is None:
user_input = {}
return self.async_show_form(step_id='user', data_schema=vol.Schem... | the_stack_v2_python_sparse | homeassistant/components/meteoclimatic/config_flow.py | home-assistant/core | train | 35,501 |
052724f8edd87c4990e534d14e91e68a42d0b3c6 | [
"self.chunk_list = chunk_list\nself.chunk_tensor_index = chunk_tensor_index\nself.cached_src_chunk_id = None\nself.cached_target_chunk_id = None\nself.gpu_fp32_buff = torch.zeros(chunk_size, dtype=torch.float, device=torch.device(f'cuda:{torch.cuda.current_device()}'))",
"assert src_param.ps_attr.param_type == Pa... | <|body_start_0|>
self.chunk_list = chunk_list
self.chunk_tensor_index = chunk_tensor_index
self.cached_src_chunk_id = None
self.cached_target_chunk_id = None
self.gpu_fp32_buff = torch.zeros(chunk_size, dtype=torch.float, device=torch.device(f'cuda:{torch.cuda.current_device()}')... | A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of chunk. This class is for doing the above copy a... | FP16ChunkWriteBuffer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of... | stack_v2_sparse_classes_36k_train_001769 | 9,910 | permissive | [
{
"docstring": "Args: chunk_list: :class:`ChunkList`. chunk_tensor_index: :class:`ChunkTensorIndex`. chunk_size: `int`.",
"name": "__init__",
"signature": "def __init__(self, chunk_list: ChunkList, chunk_tensor_index: ChunkTensorIndex, chunk_size: int)"
},
{
"docstring": "Write the value of `tar... | 3 | stack_v2_sparse_classes_30k_train_011882 | Implement the Python class `FP16ChunkWriteBuffer` described below.
Class description:
A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and... | Implement the Python class `FP16ChunkWriteBuffer` described below.
Class description:
A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and... | 884af4631a5bc51c9812a108cf5c3b5d5516ddfb | <|skeleton|>
class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FP16ChunkWriteBuffer:
"""A buffer for copy the param. At the end of the CPU Adam, we need to copy the updated fp32 params back to the fp16 params for the next iteration of training. And because the params are organized in chunks, we can optimize the copy and cast by doing it at the granularity of chunk. This ... | the_stack_v2_python_sparse | patrickstar/ops/chunk_io_buff.py | runzhech/PatrickStar | train | 0 |
630cb1fc6b447449c63a1ac0015b21b6aab91897 | [
"self.dictionary = defaultdict(list)\ni = 0\nfor word in words:\n self.dictionary[word].append(i)\n i += 1",
"word1List = self.dictionary[word1]\nword2List = self.dictionary[word2]\ni, j = (0, 0)\nminimum = sys.maxint\nwhile i < len(word1List) and j < len(word2List):\n index1 = word1List[i]\n index2 =... | <|body_start_0|>
self.dictionary = defaultdict(list)
i = 0
for word in words:
self.dictionary[word].append(i)
i += 1
<|end_body_0|>
<|body_start_1|>
word1List = self.dictionary[word1]
word2List = self.dictionary[word2]
i, j = (0, 0)
minimu... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.dictionary = defaultdict(list)
... | stack_v2_sparse_classes_36k_train_001770 | 952 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | fdb6bcb4c721e03e853890dd89122f2c4196a1ea | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.dictionary = defaultdict(list)
i = 0
for word in words:
self.dictionary[word].append(i)
i += 1
def shortest(self, word1, word2):
""":type word1: str :type word2: str ... | the_stack_v2_python_sparse | python/DP/shortestWordDistance.py | XifeiNi/LeetCode-Traversal | train | 2 | |
784853d4e7f89f3f808949c56bb430cdb7f79c39 | [
"if self.request.version == 'v6' or self.request.version == 'v7':\n return self.get_v6(request, dsm_id=dsm_id)\nelse:\n raise Http404",
"try:\n dsm = DataSetMember.objects.get_details_v6(dsm_id)\nexcept DataSet.DoesNotExist:\n raise Http404\nserializer = self.get_serializer(dsm)\nreturn Response(seria... | <|body_start_0|>
if self.request.version == 'v6' or self.request.version == 'v7':
return self.get_v6(request, dsm_id=dsm_id)
else:
raise Http404
<|end_body_0|>
<|body_start_1|>
try:
dsm = DataSetMember.objects.get_details_v6(dsm_id)
except DataSet.Doe... | This view is the endpoint for retrieving details of a specific dataset member | DataSetMemberDetailsView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_36k_train_001771 | 24,544 | permissive | [
{
"docstring": "Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param dsm_id: The dataset member id :type dsm_id: int encoded as a str :rtype: :class:`rest_framework.response.Response` :returns: the HT... | 2 | null | Implement the Python class `DataSetMemberDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a specific dataset member
Method signatures and docstrings:
- def get(self, request, dsm_id): Retrieves the details for a data set and return them in JSON form :param request: ... | Implement the Python class `DataSetMemberDetailsView` described below.
Class description:
This view is the endpoint for retrieving details of a specific dataset member
Method signatures and docstrings:
- def get(self, request, dsm_id): Retrieves the details for a data set and return them in JSON form :param request: ... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framewor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataSetMemberDetailsView:
"""This view is the endpoint for retrieving details of a specific dataset member"""
def get(self, request, dsm_id):
"""Retrieves the details for a data set and return them in JSON form :param request: the HTTP GET request :type request: :class:`rest_framework.request.Req... | the_stack_v2_python_sparse | scale/data/views.py | kfconsultant/scale | train | 0 |
545c8eb00e8fccc48337122a49737e786fad4e3f | [
"sql = \"select table_name from user_tables where table_name='%s'\" % table_name.upper()\nrecords = db_query.select(sql)\nif len(records) == 0:\n return False\nreturn True",
"field = attr.name\nif attr.attr_type == type_def.TYPE_UINT32 or attr.attr_type == type_def.TYPE_INT32:\n field = '\"%s\" NUMBER(10, 0... | <|body_start_0|>
sql = "select table_name from user_tables where table_name='%s'" % table_name.upper()
records = db_query.select(sql)
if len(records) == 0:
return False
return True
<|end_body_0|>
<|body_start_1|>
field = attr.name
if attr.attr_type == type_de... | Class: DBOperator Description: ݿṹ Others: | DBOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DBOperator:
"""Class: DBOperator Description: ݿṹ Others:"""
def check_table_exists(self, db_query, table_name):
"""Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:"""
<|body_0|>
def get_field_def(self, attr):
... | stack_v2_sparse_classes_36k_train_001772 | 1,773 | no_license | [
{
"docstring": "Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:",
"name": "check_table_exists",
"signature": "def check_table_exists(self, db_query, table_name)"
},
{
"docstring": "Method: get_field_def Description: õֶεĶַ Parameter: Re... | 2 | null | Implement the Python class `DBOperator` described below.
Class description:
Class: DBOperator Description: ݿṹ Others:
Method signatures and docstrings:
- def check_table_exists(self, db_query, table_name): Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:
- d... | Implement the Python class `DBOperator` described below.
Class description:
Class: DBOperator Description: ݿṹ Others:
Method signatures and docstrings:
- def check_table_exists(self, db_query, table_name): Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:
- d... | e78df71fbc5d73dd93ba9452d4b54183fe1e7e1f | <|skeleton|>
class DBOperator:
"""Class: DBOperator Description: ݿṹ Others:"""
def check_table_exists(self, db_query, table_name):
"""Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:"""
<|body_0|>
def get_field_def(self, attr):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DBOperator:
"""Class: DBOperator Description: ݿṹ Others:"""
def check_table_exists(self, db_query, table_name):
"""Method: check_table_exists Description: Ƿ Parameter: db_query: DBѯ table_name: Return: ڷtrue,false Others:"""
sql = "select table_name from user_tables where table_name='%s... | the_stack_v2_python_sparse | weixin/code/rfid_plt/base_platform/db_sync/db_operator.py | allenforrest/wxbiz | train | 0 |
50bfa94f976ed95b12dd2a8d1f81271675ce2246 | [
"collections = Collection.objects(private=False)\nresponse = [{'_id': str(ObjectId(doc['id'])), 'name': doc['name'], 'owner': doc['owner']['username'], 'snippets': [{'snippet_title': k['title'], 'snippet_id': str(ObjectId(k['id']))} for k in doc['snippets']], 'private': doc['private']} for doc in collections]\nretu... | <|body_start_0|>
collections = Collection.objects(private=False)
response = [{'_id': str(ObjectId(doc['id'])), 'name': doc['name'], 'owner': doc['owner']['username'], 'snippets': [{'snippet_title': k['title'], 'snippet_id': str(ObjectId(k['id']))} for k in doc['snippets']], 'private': doc['private']} fo... | Requests against the Collection model to `api/collections` (plural) | CollectionsApi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollectionsApi:
"""Requests against the Collection model to `api/collections` (plural)"""
def get(self):
"""Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON Flask Response A loose reference list of Collection objec... | stack_v2_sparse_classes_36k_train_001773 | 9,315 | permissive | [
{
"docstring": "Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON Flask Response A loose reference list of Collection objects Note: This endpoint is not the primary endpoint for fetching field details,",
"name": "get",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_001009 | Implement the Python class `CollectionsApi` described below.
Class description:
Requests against the Collection model to `api/collections` (plural)
Method signatures and docstrings:
- def get(self): Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON ... | Implement the Python class `CollectionsApi` described below.
Class description:
Requests against the Collection model to `api/collections` (plural)
Method signatures and docstrings:
- def get(self): Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON ... | 76fa490b6b3e5c4f5d554df4498c485f974c7581 | <|skeleton|>
class CollectionsApi:
"""Requests against the Collection model to `api/collections` (plural)"""
def get(self):
"""Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON Flask Response A loose reference list of Collection objec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CollectionsApi:
"""Requests against the Collection model to `api/collections` (plural)"""
def get(self):
"""Retrieve loose list of all Collections. Yields: jsonify a Query object of the Collection model Returns: [{dict}]: JSON Flask Response A loose reference list of Collection objects Note: This... | the_stack_v2_python_sparse | backend/resources/collection.py | taralika/cheathub | train | 0 |
acbe2a1e5d3c6f9afdb1bd71a23e3a215b175a16 | [
"l = [0] * 26\nfor c in tasks:\n l[ord(c) - ord('A')] += 1\nl.sort()\ntime = 0\nwhile l[25] > 0:\n i = 0\n while i <= n:\n if l[25] == 0:\n break\n if i < 26 and l[25 - i] > 0:\n l[25 - i] -= 1\n time += 1\n i += 1\n l.sort()\nreturn time",
"task_count... | <|body_start_0|>
l = [0] * 26
for c in tasks:
l[ord(c) - ord('A')] += 1
l.sort()
time = 0
while l[25] > 0:
i = 0
while i <= n:
if l[25] == 0:
break
if i < 26 and l[25 - i] > 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leasetInterval2(self, tasks, n):
"""from submission :param tasks: :param n: :return:"""
<|body_1|>
def leasetInterval3(self, tasks, n):
... | stack_v2_sparse_classes_36k_train_001774 | 1,562 | no_license | [
{
"docstring": ":type tasks: List[str] :type n: int :rtype: int",
"name": "leastInterval",
"signature": "def leastInterval(self, tasks, n)"
},
{
"docstring": "from submission :param tasks: :param n: :return:",
"name": "leasetInterval2",
"signature": "def leasetInterval2(self, tasks, n)"
... | 3 | stack_v2_sparse_classes_30k_train_007895 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leasetInterval2(self, tasks, n): from submission :param tasks: :param n: :return:
- def l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def leastInterval(self, tasks, n): :type tasks: List[str] :type n: int :rtype: int
- def leasetInterval2(self, tasks, n): from submission :param tasks: :param n: :return:
- def l... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
<|body_0|>
def leasetInterval2(self, tasks, n):
"""from submission :param tasks: :param n: :return:"""
<|body_1|>
def leasetInterval3(self, tasks, n):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def leastInterval(self, tasks, n):
""":type tasks: List[str] :type n: int :rtype: int"""
l = [0] * 26
for c in tasks:
l[ord(c) - ord('A')] += 1
l.sort()
time = 0
while l[25] > 0:
i = 0
while i <= n:
i... | the_stack_v2_python_sparse | 621. Task Scheduler.py | zhangpengGenedock/leetcode_python | train | 1 | |
942eb998d26bbb8b953c19ed6b3837aae7ed7fce | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google APIs, so that the users aren't directly involved. Service account credentials are used to te... | IAMCredentialsServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IAMCredentialsServicer:
"""A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google APIs, so that the users aren't directly in... | stack_v2_sparse_classes_36k_train_001775 | 5,869 | permissive | [
{
"docstring": "Generates an OAuth 2.0 access token for a service account.",
"name": "GenerateAccessToken",
"signature": "def GenerateAccessToken(self, request, context)"
},
{
"docstring": "Generates an OpenID Connect ID token for a service account.",
"name": "GenerateIdToken",
"signatur... | 4 | stack_v2_sparse_classes_30k_train_010185 | Implement the Python class `IAMCredentialsServicer` described below.
Class description:
A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google API... | Implement the Python class `IAMCredentialsServicer` described below.
Class description:
A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google API... | d897d56bce03d1fda98b79afb08264e51d46c421 | <|skeleton|>
class IAMCredentialsServicer:
"""A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google APIs, so that the users aren't directly in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IAMCredentialsServicer:
"""A service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. Your application assumes the identity of the service account to call Google APIs, so that the users aren't directly involved. Servi... | the_stack_v2_python_sparse | iam/google/cloud/iam_credentials_v1/proto/iamcredentials_pb2_grpc.py | tswast/google-cloud-python | train | 1 |
bd529901dc9404d9a6a5ebd116f61687fa82bd8e | [
"energy_method_names = [func.__name__ for func in energy_funcs]\nif energy_method not in energy_method_names:\n logger.critical(f'Could not generate a cage-susbtrate complex with the {energy_method} method')\n raise CannotBuildCSComplex(f'Not a valid energy method. Available methods are {energy_method_names}'... | <|body_start_0|>
energy_method_names = [func.__name__ for func in energy_funcs]
if energy_method not in energy_method_names:
logger.critical(f'Could not generate a cage-susbtrate complex with the {energy_method} method')
raise CannotBuildCSComplex(f'Not a valid energy method. Ava... | CageSubstrateComplex | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CageSubstrateComplex:
def _set_energy_func(self, energy_method):
"""From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy method to build a cage-substrate complex :return: (function) Energy function"""
<|body_0|>
def _chec... | stack_v2_sparse_classes_36k_train_001776 | 5,100 | permissive | [
{
"docstring": "From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy method to build a cage-substrate complex :return: (function) Energy function",
"name": "_set_energy_func",
"signature": "def _set_energy_func(self, energy_method)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_016401 | Implement the Python class `CageSubstrateComplex` described below.
Class description:
Implement the CageSubstrateComplex class.
Method signatures and docstrings:
- def _set_energy_func(self, energy_method): From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy meth... | Implement the Python class `CageSubstrateComplex` described below.
Class description:
Implement the CageSubstrateComplex class.
Method signatures and docstrings:
- def _set_energy_func(self, energy_method): From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy meth... | cfa47c06a42cd63bef8a9ac6af9c3403773c47ca | <|skeleton|>
class CageSubstrateComplex:
def _set_energy_func(self, energy_method):
"""From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy method to build a cage-substrate complex :return: (function) Energy function"""
<|body_0|>
def _chec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CageSubstrateComplex:
def _set_energy_func(self, energy_method):
"""From an energy_method string get the corresponding function :param energy_method: (str) Name of the energy method to build a cage-substrate complex :return: (function) Energy function"""
energy_method_names = [func.__name__ fo... | the_stack_v2_python_sparse | cgbind/cage_subt.py | duartegroup/cgbind | train | 9 | |
b7798ba3982cbb785043ceee307206c70d4d0f88 | [
"if matrix == None or len(matrix) == 0:\n return None\nself.cum_sums = [[0] + i for i in matrix]\nself.cum_sums.insert(0, [0 for i in range(len(matrix[0]) + 1)])\nfor i in range(1, len(matrix) + 1):\n for j in range(1, len(matrix[0]) + 1):\n self.cum_sums[i][j] = matrix[i - 1][j - 1] + self.cum_sums[i ... | <|body_start_0|>
if matrix == None or len(matrix) == 0:
return None
self.cum_sums = [[0] + i for i in matrix]
self.cum_sums.insert(0, [0 for i in range(len(matrix[0]) + 1)])
for i in range(1, len(matrix) + 1):
for j in range(1, len(matrix[0]) + 1):
... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_001777 | 1,206 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | e8bffeb457936d28c75ecfefb5a1f316c15a9b6c | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if matrix == None or len(matrix) == 0:
return None
self.cum_sums = [[0] + i for i in matrix]
self.cum_sums.insert(0, [0 for i in range(len(matrix[0]) + 1)])
for i in range(1, len(matr... | the_stack_v2_python_sparse | Leetcode/304.range-sum-query-2d-immutable.py | EdwaRen/Competitve-Programming | train | 1 | |
713e4384462aeadde8b4d0195b79dec65301a821 | [
"self.app_id = app_id\nself.error = error\nself.name = name\nself.owner_id = owner_id\nself.status = status\nself.warnings = warnings",
"if dictionary is None:\n return None\napp_id = dictionary.get('appId')\nerror = dictionary.get('error')\nname = dictionary.get('name')\nowner_id = dictionary.get('ownerId')\n... | <|body_start_0|>
self.app_id = app_id
self.error = error
self.name = name
self.owner_id = owner_id
self.status = status
self.warnings = warnings
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
app_id = dictionary.get('appId'... | Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQL, Oracle jobs etc. error (string): Specifies if an error occurred (if any) while running th... | AppEntityBackupStatusInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppEntityBackupStatusInfo:
"""Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQL, Oracle jobs etc. error (string): Spe... | stack_v2_sparse_classes_36k_train_001778 | 3,486 | permissive | [
{
"docstring": "Constructor for the AppEntityBackupStatusInfo class",
"name": "__init__",
"signature": "def __init__(self, app_id=None, error=None, name=None, owner_id=None, status=None, warnings=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dict... | 2 | null | Implement the Python class `AppEntityBackupStatusInfo` described below.
Class description:
Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQ... | Implement the Python class `AppEntityBackupStatusInfo` described below.
Class description:
Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AppEntityBackupStatusInfo:
"""Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQL, Oracle jobs etc. error (string): Spe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppEntityBackupStatusInfo:
"""Implementation of the 'AppEntityBackupStatusInfo' model. Specifies the app level backup status and information. Attributes: app_id (long|int): Specifies the Id of the App entity. This is typically a database entity in case of SQL, Oracle jobs etc. error (string): Specifies if an ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/app_entity_backup_status_info.py | cohesity/management-sdk-python | train | 24 |
d4f974c9075411b7de1bb3323f797da9b7608a53 | [
"image_url1 = getParameter('image_url1')\nimage_file1 = getFile('image_file1')\nimage_base64_1 = getFile('image_base64_1')\nface_rectangle1 = getParameter('face_rectangle1')\nimage_url2 = getParameter('image_url2')\nimage_file2 = getFile('image_file2')\nimage_base64_2 = getFile('image_base64_2')\nface_rectangle2 = ... | <|body_start_0|>
image_url1 = getParameter('image_url1')
image_file1 = getFile('image_file1')
image_base64_1 = getFile('image_base64_1')
face_rectangle1 = getParameter('face_rectangle1')
image_url2 = getParameter('image_url2')
image_file2 = getFile('image_file2')
... | PredictionController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PredictionController:
def compare():
"""1 vs 1 人脸比对"""
<|body_0|>
def search():
"""1 vs n 人脸检索"""
<|body_1|>
def load_recent_prediction():
"""加载最近的识别结果"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
image_url1 = getParameter('i... | stack_v2_sparse_classes_36k_train_001779 | 1,790 | no_license | [
{
"docstring": "1 vs 1 人脸比对",
"name": "compare",
"signature": "def compare()"
},
{
"docstring": "1 vs n 人脸检索",
"name": "search",
"signature": "def search()"
},
{
"docstring": "加载最近的识别结果",
"name": "load_recent_prediction",
"signature": "def load_recent_prediction()"
}
] | 3 | stack_v2_sparse_classes_30k_train_014793 | Implement the Python class `PredictionController` described below.
Class description:
Implement the PredictionController class.
Method signatures and docstrings:
- def compare(): 1 vs 1 人脸比对
- def search(): 1 vs n 人脸检索
- def load_recent_prediction(): 加载最近的识别结果 | Implement the Python class `PredictionController` described below.
Class description:
Implement the PredictionController class.
Method signatures and docstrings:
- def compare(): 1 vs 1 人脸比对
- def search(): 1 vs n 人脸检索
- def load_recent_prediction(): 加载最近的识别结果
<|skeleton|>
class PredictionController:
def compar... | 3c756d00c83cd0a8dd745fd32a074c9121977ab8 | <|skeleton|>
class PredictionController:
def compare():
"""1 vs 1 人脸比对"""
<|body_0|>
def search():
"""1 vs n 人脸检索"""
<|body_1|>
def load_recent_prediction():
"""加载最近的识别结果"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PredictionController:
def compare():
"""1 vs 1 人脸比对"""
image_url1 = getParameter('image_url1')
image_file1 = getFile('image_file1')
image_base64_1 = getFile('image_base64_1')
face_rectangle1 = getParameter('face_rectangle1')
image_url2 = getParameter('image_url2... | the_stack_v2_python_sparse | web/prediction_controller.py | esfamely/es_face_server | train | 0 | |
e87b4df3c0f50e1ea52af2f404ba45c786bbfb51 | [
"s = set()\nfor p in points:\n s.add((p[0], p[1]))\n\ndef ok(p1, p2, p3):\n row, col = (False, False)\n if p1[0] == p2[0] or p1[0] == p3[0] or p2[0] == p3[0]:\n row = True\n if p1[1] == p2[1] or p1[1] == p3[1] or p2[1] == p3[1]:\n col = True\n return row and col\nans = 40000 * 40001\nfo... | <|body_start_0|>
s = set()
for p in points:
s.add((p[0], p[1]))
def ok(p1, p2, p3):
row, col = (False, False)
if p1[0] == p2[0] or p1[0] == p3[0] or p2[0] == p3[0]:
row = True
if p1[1] == p2[1] or p1[1] == p3[1] or p2[1] == p3[1]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def minAreaRect2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = set()
for p ... | stack_v2_sparse_classes_36k_train_001780 | 10,493 | no_license | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "minAreaRect",
"signature": "def minAreaRect(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "minAreaRect2",
"signature": "def minAreaRect2(self, points)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAreaRect(self, points): :type points: List[List[int]] :rtype: int
- def minAreaRect2(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minAreaRect(self, points): :type points: List[List[int]] :rtype: int
- def minAreaRect2(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|>
class Solution:... | 85128e7d26157b3c36eb43868269de42ea2fcb98 | <|skeleton|>
class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def minAreaRect2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minAreaRect(self, points):
""":type points: List[List[int]] :rtype: int"""
s = set()
for p in points:
s.add((p[0], p[1]))
def ok(p1, p2, p3):
row, col = (False, False)
if p1[0] == p2[0] or p1[0] == p3[0] or p2[0] == p3[0]:
... | the_stack_v2_python_sparse | src/Minimum Area Rectangle.py | jsdiuf/leetcode | train | 1 | |
765d2e82b4d3771d3c7b1527633f53f51d364325 | [
"self.name = xls_name\nself.sheets = []\nif not os.path.exists(self.name):\n self.workbook = xlwt.Workbook()\nelse:\n logging.warning(\"Appending to XLS file '%s'\" % self.name)\n rb = xlrd.open_workbook(self.name, formatting_info=True)\n self.workbook = xlutils.copy.copy(rb)\n i = 0\n for s in rb... | <|body_start_0|>
self.name = xls_name
self.sheets = []
if not os.path.exists(self.name):
self.workbook = xlwt.Workbook()
else:
logging.warning("Appending to XLS file '%s'" % self.name)
rb = xlrd.open_workbook(self.name, formatting_info=True)
... | Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances). | Workbook | [
"Artistic-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workbook:
"""Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances)."""
def __init__(self, xls_name=''):
"""Create a new Workbook instance. If the name of an existing XLS file is specified t... | stack_v2_sparse_classes_36k_train_001781 | 30,690 | permissive | [
{
"docstring": "Create a new Workbook instance. If the name of an existing XLS file is specified then the new content will be appended to whatever is already in that spreadsheet (note that the original spreadsheet will only be overwritten if the same name is provided in the 'save' method). Otherwise a new (empt... | 4 | null | Implement the Python class `Workbook` described below.
Class description:
Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances).
Method signatures and docstrings:
- def __init__(self, xls_name=''): Create a new Workbook ins... | Implement the Python class `Workbook` described below.
Class description:
Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances).
Method signatures and docstrings:
- def __init__(self, xls_name=''): Create a new Workbook ins... | ca0c7c239b0f04353e2f2fa897db9c24a1211596 | <|skeleton|>
class Workbook:
"""Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances)."""
def __init__(self, xls_name=''):
"""Create a new Workbook instance. If the name of an existing XLS file is specified t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Workbook:
"""Class for writing data to an XLS spreadsheet. A Workbook represents an XLS spreadsheet, which conists of sheets (represented by Worksheet instances)."""
def __init__(self, xls_name=''):
"""Create a new Workbook instance. If the name of an existing XLS file is specified then the new c... | the_stack_v2_python_sparse | bcftbx/Spreadsheet.py | golharam/genomics | train | 0 |
2e716c9092eef5dc28a9ee729531c7dcfb517cea | [
"self.watch_file = watch_file\nself._section_data = []\nself._fhandle = None\nself._last_pos = None",
"try:\n self._fhandle = open(self.watch_file, 'r')\n self._last_pos = None\n self._section_data = []\nexcept IOError:\n self._fhandle = None",
"hostname_override = None\nlease = dict()\nlease['addre... | <|body_start_0|>
self.watch_file = watch_file
self._section_data = []
self._fhandle = None
self._last_pos = None
<|end_body_0|>
<|body_start_1|>
try:
self._fhandle = open(self.watch_file, 'r')
self._last_pos = None
self._section_data = []
... | DHCPDLease | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DHCPDLease:
def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases'):
"""init watcher :param watch_file: filename to watch :return: watcher object"""
<|body_0|>
def _open(self):
"""(re)open watched file :return: None"""
<|body_1|>
def parse_lease(... | stack_v2_sparse_classes_36k_train_001782 | 4,825 | permissive | [
{
"docstring": "init watcher :param watch_file: filename to watch :return: watcher object",
"name": "__init__",
"signature": "def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases')"
},
{
"docstring": "(re)open watched file :return: None",
"name": "_open",
"signature": "def _open... | 4 | stack_v2_sparse_classes_30k_train_018805 | Implement the Python class `DHCPDLease` described below.
Class description:
Implement the DHCPDLease class.
Method signatures and docstrings:
- def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases'): init watcher :param watch_file: filename to watch :return: watcher object
- def _open(self): (re)open watched... | Implement the Python class `DHCPDLease` described below.
Class description:
Implement the DHCPDLease class.
Method signatures and docstrings:
- def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases'): init watcher :param watch_file: filename to watch :return: watcher object
- def _open(self): (re)open watched... | a702cf9fb3300e125cd7acc8af3813474606e509 | <|skeleton|>
class DHCPDLease:
def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases'):
"""init watcher :param watch_file: filename to watch :return: watcher object"""
<|body_0|>
def _open(self):
"""(re)open watched file :return: None"""
<|body_1|>
def parse_lease(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DHCPDLease:
def __init__(self, watch_file='/var/dhcpd/var/db/dhcpd.leases'):
"""init watcher :param watch_file: filename to watch :return: watcher object"""
self.watch_file = watch_file
self._section_data = []
self._fhandle = None
self._last_pos = None
def _open(se... | the_stack_v2_python_sparse | src/opnsense/site-python/watchers/dhcpd.py | opnsense/core | train | 2,778 | |
e8e05023d5d3a4d7d689422fe3aae4b55299e097 | [
"new_names_dict = {'old_name_1': 'new_name_1', 'old_name_2': 'new_name_2'}\ndict_to_change = {'old_name_1': 'some_value_1', 'old_name_2': 'some_value_2'}\nchanged_dict = change_dict_keys(new_names_dict, dict_to_change)\nassert changed_dict['new_name_1']\nassert changed_dict['new_name_2']\nassert 'old_name_1' not in... | <|body_start_0|>
new_names_dict = {'old_name_1': 'new_name_1', 'old_name_2': 'new_name_2'}
dict_to_change = {'old_name_1': 'some_value_1', 'old_name_2': 'some_value_2'}
changed_dict = change_dict_keys(new_names_dict, dict_to_change)
assert changed_dict['new_name_1']
assert change... | TestChangeDictKeys | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestChangeDictKeys:
def test_change_dict_keys_expected_format(self):
"""Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted Then - return the dictionary with the new keys"""
<|body_0|>
def test_change_dict_keys_missin... | stack_v2_sparse_classes_36k_train_001783 | 44,285 | permissive | [
{
"docstring": "Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted Then - return the dictionary with the new keys",
"name": "test_change_dict_keys_expected_format",
"signature": "def test_change_dict_keys_expected_format(self)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_009907 | Implement the Python class `TestChangeDictKeys` described below.
Class description:
Implement the TestChangeDictKeys class.
Method signatures and docstrings:
- def test_change_dict_keys_expected_format(self): Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted... | Implement the Python class `TestChangeDictKeys` described below.
Class description:
Implement the TestChangeDictKeys class.
Method signatures and docstrings:
- def test_change_dict_keys_expected_format(self): Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestChangeDictKeys:
def test_change_dict_keys_expected_format(self):
"""Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted Then - return the dictionary with the new keys"""
<|body_0|>
def test_change_dict_keys_missin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestChangeDictKeys:
def test_change_dict_keys_expected_format(self):
"""Given - dictionary to be changed - dictionary with new keys' names When - the dictionaries are well formatted Then - return the dictionary with the new keys"""
new_names_dict = {'old_name_1': 'new_name_1', 'old_name_2': 'n... | the_stack_v2_python_sparse | Packs/qualys/Integrations/Qualysv2/Qualysv2_test.py | demisto/content | train | 1,023 | |
0bc268e0959ebd52db661aadc09388190f61175c | [
"super(Linker_separate, self).__init__()\nself.config = config\nself.encoder = encoder\nself.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nself.entity_embeddings_struct = nn.Embedding(self.config.entity_size, self.config.embedding_dim)\nif self.config.priors:\n self.char_f... | <|body_start_0|>
super(Linker_separate, self).__init__()
self.config = config
self.encoder = encoder
self.entity_embeddings = nn.Embedding(self.config.entity_size, self.config.embedding_dim)
self.entity_embeddings_struct = nn.Embedding(self.config.entity_size, self.config.embeddi... | Linker_separate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Linker_separate:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_s... | stack_v2_sparse_classes_36k_train_001784 | 42,719 | permissive | [
{
"docstring": ":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions",
"name": "__init__",
"signature": "def __init__(self, config, encoder)"
},
{
"docstring": ":return: unnormalized log probabilities (logits) of gold enti... | 2 | stack_v2_sparse_classes_30k_train_001928 | Implement the Python class `Linker_separate` described below.
Class description:
Implement the Linker_separate class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
... | Implement the Python class `Linker_separate` described below.
Class description:
Implement the Linker_separate class.
Method signatures and docstrings:
- def __init__(self, config, encoder): :param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions
... | 6a7dcd7d3756327c61ef949e5b4f6af6e2849187 | <|skeleton|>
class Linker_separate:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
<|body_0|>
def forward(self, entity_candidates, mention_representation, sentence, char_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Linker_separate:
def __init__(self, config, encoder):
""":param config: A config object that specifies the hyperparameters of the model :param encoder: A Encoder for encoding mentions"""
super(Linker_separate, self).__init__()
self.config = config
self.encoder = encoder
... | the_stack_v2_python_sparse | typenet/src/model.py | dhruvdcoder/dl-with-constraints | train | 0 | |
1738ed8d4580f1107dfbee9373698fe766ade0ac | [
"ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, user_id=user_id))\ninherited = self._check_if_inherited()\nPROVIDERS.assignment_api.get_grant(role_id=role_id, user_id=user_id, project_id=project_id, inh... | <|body_start_0|>
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target_attr, role_id=role_id, project_id=project_id, user_id=user_id))
inherited = self._check_if_inherited()
PROVIDERS.assignment_api.get_grant(role_id=role_id, user_id=u... | ProjectUserGrantResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, user_id, role_id):
"""Grant role for user on proje... | stack_v2_sparse_classes_36k_train_001785 | 22,149 | permissive | [
{
"docstring": "Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}",
"name": "get",
"signature": "def get(self, project_id, user_id, role_id)"
},
{
"docstring": "Grant role for user on project. PUT /v3/projects/{project_id}/users/{user_id}/role... | 3 | stack_v2_sparse_classes_30k_train_011935 | Implement the Python class `ProjectUserGrantResource` described below.
Class description:
Implement the ProjectUserGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id... | Implement the Python class `ProjectUserGrantResource` described below.
Class description:
Implement the ProjectUserGrantResource class.
Method signatures and docstrings:
- def get(self, project_id, user_id, role_id): Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id... | 03a0a8146a78682ede9eca12a5a7fdacde2035c8 | <|skeleton|>
class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
<|body_0|>
def put(self, project_id, user_id, role_id):
"""Grant role for user on proje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectUserGrantResource:
def get(self, project_id, user_id, role_id):
"""Check grant for project, user, role. GET/HEAD /v3/projects/{project_id/users/{user_id}/roles/{role_id}"""
ENFORCER.enforce_call(action='identity:check_grant', build_target=functools.partial(self._build_enforcement_target... | the_stack_v2_python_sparse | keystone/api/projects.py | sapcc/keystone | train | 0 | |
5c85fc922e0059ec27317e1943c1db14c51b2252 | [
"bigger_R = []\nfor i, a in enumerate(A):\n if a > R:\n bigger_R.append(i)\nstart = 0\nsub_range = []\nfor high in bigger_R:\n if high > start:\n sub_range.append((start, high))\n start = high + 1\nif start < len(A):\n sub_range.append((start, len(A)))\nprint(sub_range)\nans = 0\nfor one_r... | <|body_start_0|>
bigger_R = []
for i, a in enumerate(A):
if a > R:
bigger_R.append(i)
start = 0
sub_range = []
for high in bigger_R:
if high > start:
sub_range.append((start, high))
start = high + 1
if st... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int 123ms"""
<|body_0|>
def numSubarrayBoundedMax_1(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int 111ms"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_001786 | 2,148 | no_license | [
{
"docstring": ":type A: List[int] :type L: int :type R: int :rtype: int 123ms",
"name": "numSubarrayBoundedMax",
"signature": "def numSubarrayBoundedMax(self, A, L, R)"
},
{
"docstring": ":type A: List[int] :type L: int :type R: int :rtype: int 111ms",
"name": "numSubarrayBoundedMax_1",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A, L, R): :type A: List[int] :type L: int :type R: int :rtype: int 123ms
- def numSubarrayBoundedMax_1(self, A, L, R): :type A: List[int] :type L:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, A, L, R): :type A: List[int] :type L: int :type R: int :rtype: int 123ms
- def numSubarrayBoundedMax_1(self, A, L, R): :type A: List[int] :type L:... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int 123ms"""
<|body_0|>
def numSubarrayBoundedMax_1(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int 111ms"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayBoundedMax(self, A, L, R):
""":type A: List[int] :type L: int :type R: int :rtype: int 123ms"""
bigger_R = []
for i, a in enumerate(A):
if a > R:
bigger_R.append(i)
start = 0
sub_range = []
for high in bigger_... | the_stack_v2_python_sparse | NumberOfSubarraysWithBoundedMaximum_MID_795.py | 953250587/leetcode-python | train | 2 | |
49859a53889ba1a49b220c3003c601464249bd9c | [
"GrpcClient.__init__(self, encryptionHeader)\nif kubemq_address:\n self._kubemq_address = kubemq_address",
"ping_result = self.get_kubemq_client().Ping(Empty())\nlogger.debug(\"Initiator KubeMQ address:%s ping result:%s'\" % (self._kubemq_address, ping_result))\nreturn ping_result",
"def process_response(cal... | <|body_start_0|>
GrpcClient.__init__(self, encryptionHeader)
if kubemq_address:
self._kubemq_address = kubemq_address
<|end_body_0|>
<|body_start_1|>
ping_result = self.get_kubemq_client().Ping(Empty())
logger.debug("Initiator KubeMQ address:%s ping result:%s'" % (self._kube... | Represents the instance that is responsible to send requests to the kubemq. | Initiator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initiator:
"""Represents the instance that is responsible to send requests to the kubemq."""
def __init__(self, kubemq_address=None, encryptionHeader=None):
"""Initialize a new Initiator. :param str kubemq_address: KubeMQ server address. if None will be parsed from Config or environm... | stack_v2_sparse_classes_36k_train_001787 | 3,013 | permissive | [
{
"docstring": "Initialize a new Initiator. :param str kubemq_address: KubeMQ server address. if None will be parsed from Config or environment parameter.",
"name": "__init__",
"signature": "def __init__(self, kubemq_address=None, encryptionHeader=None)"
},
{
"docstring": "ping check connection ... | 4 | stack_v2_sparse_classes_30k_test_000553 | Implement the Python class `Initiator` described below.
Class description:
Represents the instance that is responsible to send requests to the kubemq.
Method signatures and docstrings:
- def __init__(self, kubemq_address=None, encryptionHeader=None): Initialize a new Initiator. :param str kubemq_address: KubeMQ serve... | Implement the Python class `Initiator` described below.
Class description:
Represents the instance that is responsible to send requests to the kubemq.
Method signatures and docstrings:
- def __init__(self, kubemq_address=None, encryptionHeader=None): Initialize a new Initiator. :param str kubemq_address: KubeMQ serve... | aedd8a25e2f78f2cf145c88fc922a05363aa01b5 | <|skeleton|>
class Initiator:
"""Represents the instance that is responsible to send requests to the kubemq."""
def __init__(self, kubemq_address=None, encryptionHeader=None):
"""Initialize a new Initiator. :param str kubemq_address: KubeMQ server address. if None will be parsed from Config or environm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Initiator:
"""Represents the instance that is responsible to send requests to the kubemq."""
def __init__(self, kubemq_address=None, encryptionHeader=None):
"""Initialize a new Initiator. :param str kubemq_address: KubeMQ server address. if None will be parsed from Config or environment parameter... | the_stack_v2_python_sparse | kubemq/commandquery/lowlevel/initiator.py | kubemq-io/kubemq-Python | train | 26 |
c4de042972838a31477a47c77acd4e2739e461c6 | [
"self._fontDict = {}\nfor pair in listOfFontNamesAndSizesAsTuple:\n assert len(pair) == 2, \"Pair must be composed of a font name and a size - ('arial', 24)\"\n if pair[0]:\n fontFullFileName = pygame.font.match_font(pair[0])\n assert fontFullFileName, 'Font: %s Size: %d is not available.' % pai... | <|body_start_0|>
self._fontDict = {}
for pair in listOfFontNamesAndSizesAsTuple:
assert len(pair) == 2, "Pair must be composed of a font name and a size - ('arial', 24)"
if pair[0]:
fontFullFileName = pygame.font.match_font(pair[0])
assert fontFull... | A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelson | FontManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FontManager:
"""A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelson"""
def __init__(self, listOfFont... | stack_v2_sparse_classes_36k_train_001788 | 3,613 | permissive | [
{
"docstring": "Pass in a tuple of 2-item tuples. Each 2-item tuple is a fontname / size pair. To use the default font, pass in a None for the font name. Font objects are created for each of the pairs and can then be used to draw text with the Draw() method below. Ex: fontMgr = FontManager(((None, 24), ('arial'... | 2 | null | Implement the Python class `FontManager` described below.
Class description:
A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelso... | Implement the Python class `FontManager` described below.
Class description:
A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelso... | 5a07e02588b1b7c8ebf7458b10e81b8ecf84ad13 | <|skeleton|>
class FontManager:
"""A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelson"""
def __init__(self, listOfFont... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FontManager:
"""A simple class used to manage Font objects and provide a simple way to use them to draw text on any surface. Directly import this file to use the class, or run this file from the command line to see a trivial sample. Written by Scott O. Nelson"""
def __init__(self, listOfFontNamesAndSizes... | the_stack_v2_python_sparse | bigtime/fontmgr.py | baluneboy/pims | train | 0 |
94880096830b0a08809de5820f30b32d920b04f0 | [
"self.size = size\nself.dq = deque([])\nself.acum = 0",
"self.dq.append(val)\nself.acum += val\nif len(self.dq) > self.size:\n left = self.dq.popleft()\n self.suma -= left\nreturn float(self.suma) / len(self.dq)"
] | <|body_start_0|>
self.size = size
self.dq = deque([])
self.acum = 0
<|end_body_0|>
<|body_start_1|>
self.dq.append(val)
self.acum += val
if len(self.dq) > self.size:
left = self.dq.popleft()
self.suma -= left
return float(self.suma) / len(... | MovingAverage | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.dq = de... | stack_v2_sparse_classes_36k_train_001789 | 1,478 | permissive | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | ffe317f9a984319fbb3c1811e2a438306fc4eee9 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.dq = deque([])
self.acum = 0
def next(self, val):
""":type val: int :rtype: float"""
self.dq.append(val)
self.acum += val
... | the_stack_v2_python_sparse | LeetCode/01_Easy/lc_346.py | zubie7a/Algorithms | train | 10 | |
dfeedcb25d1f72a5a9d5c16f35c7df933d23f8cc | [
"self.host = host\nself.user = user\nself.port = port\nself.pwd = pwd\nself.db = db\ndb = pymysql.connect(host=self.host, user=self.user, passwd=self.pwd, port=self.port, db=self.db)\nself.db = db",
"query = 'SELECT * FROM job WHERE analysis_id= %d ' % id\nif limit is not None:\n query += 'LIMIT {0}'.format(li... | <|body_start_0|>
self.host = host
self.user = user
self.port = port
self.pwd = pwd
self.db = db
db = pymysql.connect(host=self.host, user=self.user, passwd=self.pwd, port=self.port, db=self.db)
self.db = db
<|end_body_0|>
<|body_start_1|>
query = 'SELECT ... | Class representing a Hive MySQL DB | HiveDB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiveDB:
"""Class representing a Hive MySQL DB"""
def __init__(self, host=None, user=None, port=0, pwd=None, db=None):
"""Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port : str, default=0 DB port. pwd : str, optional DB passwor... | stack_v2_sparse_classes_36k_train_001790 | 5,592 | permissive | [
{
"docstring": "Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port : str, default=0 DB port. pwd : str, optional DB password. db : str, optional database to connect.",
"name": "__init__",
"signature": "def __init__(self, host=None, user=None, port=... | 4 | stack_v2_sparse_classes_30k_train_013367 | Implement the Python class `HiveDB` described below.
Class description:
Class representing a Hive MySQL DB
Method signatures and docstrings:
- def __init__(self, host=None, user=None, port=0, pwd=None, db=None): Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port... | Implement the Python class `HiveDB` described below.
Class description:
Class representing a Hive MySQL DB
Method signatures and docstrings:
- def __init__(self, host=None, user=None, port=0, pwd=None, db=None): Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port... | ffea4885227c2299f886a4f41e70b6e1f6bb43da | <|skeleton|>
class HiveDB:
"""Class representing a Hive MySQL DB"""
def __init__(self, host=None, user=None, port=0, pwd=None, db=None):
"""Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port : str, default=0 DB port. pwd : str, optional DB passwor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiveDB:
"""Class representing a Hive MySQL DB"""
def __init__(self, host=None, user=None, port=0, pwd=None, db=None):
"""Constructor Parameters ---------- host : str, optional DB hostname. user : str, optional DB username. port : str, default=0 DB port. pwd : str, optional DB password. db : str, ... | the_stack_v2_python_sparse | PyHive/Hive.py | igsr/igsr_analysis | train | 3 |
b072f942459d14c76721b60efc655843cd0dbe68 | [
"data_model = self._sdc_definitions.data_model\nrequest = data_model.msg_types.GetMdib()\ninf = HeaderInformationBlock(action=request.action, addr_to=self.endpoint_reference.Address)\nmessage = self._msg_factory.mk_soap_message(inf, payload=request)\nreceived_message_data = self.post_message(message, request_manipu... | <|body_start_0|>
data_model = self._sdc_definitions.data_model
request = data_model.msg_types.GetMdib()
inf = HeaderInformationBlock(action=request.action, addr_to=self.endpoint_reference.Address)
message = self._msg_factory.mk_soap_message(inf, payload=request)
received_message_... | Client for GetService. | GetServiceClient | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetServiceClient:
"""Client for GetService."""
def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult:
"""Send a GetMdib request."""
<|body_0|>
def get_md_description(self, requested_handles: list[str] | None=None, request_man... | stack_v2_sparse_classes_36k_train_001791 | 3,355 | permissive | [
{
"docstring": "Send a GetMdib request.",
"name": "get_mdib",
"signature": "def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult"
},
{
"docstring": "Send a GetMdDescription request. :param requested_handles: None if all states shall be requested, ot... | 3 | stack_v2_sparse_classes_30k_train_021633 | Implement the Python class `GetServiceClient` described below.
Class description:
Client for GetService.
Method signatures and docstrings:
- def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult: Send a GetMdib request.
- def get_md_description(self, requested_handles: li... | Implement the Python class `GetServiceClient` described below.
Class description:
Client for GetService.
Method signatures and docstrings:
- def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult: Send a GetMdib request.
- def get_md_description(self, requested_handles: li... | dab57b38ed9a9e70e6bc6a9cf44140b96fd95851 | <|skeleton|>
class GetServiceClient:
"""Client for GetService."""
def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult:
"""Send a GetMdib request."""
<|body_0|>
def get_md_description(self, requested_handles: list[str] | None=None, request_man... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetServiceClient:
"""Client for GetService."""
def get_mdib(self, request_manipulator: RequestManipulatorProtocol | None=None) -> GetRequestResult:
"""Send a GetMdib request."""
data_model = self._sdc_definitions.data_model
request = data_model.msg_types.GetMdib()
inf = He... | the_stack_v2_python_sparse | src/sdc11073/consumer/serviceclients/getservice.py | deichmab-draeger/sdc11073 | train | 0 |
20f658c5be84d6dbc4c99b6e7c2ef2a11d4d53eb | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SimulationReportOverview()",
"from .recommended_action import RecommendedAction\nfrom .simulation_events_content import SimulationEventsContent\nfrom .training_events_content import TrainingEventsContent\nfrom .recommended_action impor... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SimulationReportOverview()
<|end_body_0|>
<|body_start_1|>
from .recommended_action import RecommendedAction
from .simulation_events_content import SimulationEventsContent
from .... | SimulationReportOverview | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulationReportOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationReportOverview:
"""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 cre... | stack_v2_sparse_classes_36k_train_001792 | 4,392 | 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: SimulationReportOverview",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimi... | 3 | stack_v2_sparse_classes_30k_test_000793 | Implement the Python class `SimulationReportOverview` described below.
Class description:
Implement the SimulationReportOverview class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationReportOverview: Creates a new instance of the appropriate c... | Implement the Python class `SimulationReportOverview` described below.
Class description:
Implement the SimulationReportOverview class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationReportOverview: Creates a new instance of the appropriate c... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SimulationReportOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationReportOverview:
"""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 cre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulationReportOverview:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SimulationReportOverview:
"""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... | the_stack_v2_python_sparse | msgraph/generated/models/simulation_report_overview.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ff2eb38382398b4926ef8802245a55d0470497fd | [
"length = len(s)\nmarker = 0\nfor former in s:\n if not former.isalnum():\n continue\n for j in range(marker, length):\n latter = s[-1 - j]\n if latter.isalnum():\n if former.lower() == latter.lower():\n marker = j + 1\n break\n else:\n ... | <|body_start_0|>
length = len(s)
marker = 0
for former in s:
if not former.isalnum():
continue
for j in range(marker, length):
latter = s[-1 - j]
if latter.isalnum():
if former.lower() == latter.lower():
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s: str) -> bool:
"""avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐"""
<|body_0|>
def is_palindrome_deque(self, s: str) -> bool:
"""풀이 2 - 데크 자료형을 이용한 최적화 runtime: 44ms"""
... | stack_v2_sparse_classes_36k_train_001793 | 1,751 | no_license | [
{
"docstring": "avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s: str) -> bool"
},
{
"docstring": "풀이 2 - 데크 자료형을 이용한 최적화 runtime: 44ms",
"name": "is_palindrome_deque",
... | 3 | stack_v2_sparse_classes_30k_train_002850 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s: str) -> bool: avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐
- def is_palindrome_deque(self,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s: str) -> bool: avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐
- def is_palindrome_deque(self,... | 01fdc354aedd240936d35c2b0e2dff8a57e35eec | <|skeleton|>
class Solution:
def isPalindrome(self, s: str) -> bool:
"""avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐"""
<|body_0|>
def is_palindrome_deque(self, s: str) -> bool:
"""풀이 2 - 데크 자료형을 이용한 최적화 runtime: 44ms"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s: str) -> bool:
"""avg runtime (5 attempts): 69.6ms runtime beats: about 18% memory usage beats: 65% '풀이 4 - C 구현'과 유사한 부분 가짐"""
length = len(s)
marker = 0
for former in s:
if not former.isalnum():
continue
... | the_stack_v2_python_sparse | algorithm-interview/ch6/01/davin111_valid_palindrome.py | wafflestudio/waffle-algorithm | train | 8 | |
548bd0c95c9774f2920849080ee3229c9b8cf9ad | [
"q = deque([root])\nlev = 0\nwhile q:\n nxt = deque()\n filled = True\n n = len(q)\n for i in range(len(q)):\n node = q.popleft()\n if node.left:\n if not filled:\n return False\n nxt.append(node.left)\n else:\n filled = False\n ... | <|body_start_0|>
q = deque([root])
lev = 0
while q:
nxt = deque()
filled = True
n = len(q)
for i in range(len(q)):
node = q.popleft()
if node.left:
if not filled:
return Fa... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isCompleteTreeAC(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
q = deque([root])
lev = 0
... | stack_v2_sparse_classes_36k_train_001794 | 2,907 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isCompleteTree",
"signature": "def isCompleteTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isCompleteTreeAC",
"signature": "def isCompleteTreeAC(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018734 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCompleteTree(self, root): :type root: TreeNode :rtype: bool
- def isCompleteTreeAC(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isCompleteTree(self, root): :type root: TreeNode :rtype: bool
- def isCompleteTreeAC(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def isC... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isCompleteTreeAC(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isCompleteTree(self, root):
""":type root: TreeNode :rtype: bool"""
q = deque([root])
lev = 0
while q:
nxt = deque()
filled = True
n = len(q)
for i in range(len(q)):
node = q.popleft()
... | the_stack_v2_python_sparse | C/CheckCompletenessofaBinaryTree.py | bssrdf/pyleet | train | 2 | |
5976a2dd80d24ba694dad84da69c4cae4b9f5dd8 | [
"super().__init__(n_feat, n_head, dropout)\nself.zero_triu = zero_triu\nself.linear_pos = nn.Linear(n_feat, n_feat, bias=False)\nself.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))\nself.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))\ntorch.nn.init.xavier_uniform_(self.pos_bias_u)\ntorch.nn.in... | <|body_start_0|>
super().__init__(n_feat, n_head, dropout)
self.zero_triu = zero_triu
self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
torc... | Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the upper triangular part of attention matrix. | RelPositionMultiHeadedAttention | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the upper triangular part of attention matri... | stack_v2_sparse_classes_36k_train_001795 | 9,673 | permissive | [
{
"docstring": "Construct an RelPositionMultiHeadedAttention object.",
"name": "__init__",
"signature": "def __init__(self, n_feat, n_head, dropout, zero_triu=False)"
},
{
"docstring": "Compute relative positional encoding. Args: x: Input tensor B X n_head X T X 2T-1 Returns: torch.Tensor: Outpu... | 3 | stack_v2_sparse_classes_30k_train_020482 | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the u... | Implement the Python class `RelPositionMultiHeadedAttention` described below.
Class description:
Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the u... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the upper triangular part of attention matri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelPositionMultiHeadedAttention:
"""Multi-Head Attention layer with relative position encoding. Paper: https://arxiv.org/abs/1901.02860 Args: n_head: The number of heads. n_feat: The number of features. dropout: Dropout rate. zero_triu: Whether to zero the upper triangular part of attention matrix."""
de... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/espnet_multihead_attention.py | microsoft/unilm | train | 15,313 |
a8c28e5d58738e0f6f13cd04f3e5cc5879dec5b6 | [
"super(Encoder, self).__init__()\nself.embedding = nn.Embedding(num_encoder_tokens, char_dim)\nself.lstm = nn.LSTM(char_dim, latent_dim)",
"embedded = self.embedding(input_var)\noutputs, hidden = self.lstm(embedded, hidden)\nreturn (outputs, hidden)"
] | <|body_start_0|>
super(Encoder, self).__init__()
self.embedding = nn.Embedding(num_encoder_tokens, char_dim)
self.lstm = nn.LSTM(char_dim, latent_dim)
<|end_body_0|>
<|body_start_1|>
embedded = self.embedding(input_var)
outputs, hidden = self.lstm(embedded, hidden)
retur... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def __init__(self, num_encoder_tokens, char_dim, latent_dim):
"""Define layers for encoder"""
<|body_0|>
def forward(self, input_var, hidden=None):
"""input_var: (time_steps, batch_size) embedded: (time_steps, batch_size, char_dim) outputs, hidden: (time_ste... | stack_v2_sparse_classes_36k_train_001796 | 695 | no_license | [
{
"docstring": "Define layers for encoder",
"name": "__init__",
"signature": "def __init__(self, num_encoder_tokens, char_dim, latent_dim)"
},
{
"docstring": "input_var: (time_steps, batch_size) embedded: (time_steps, batch_size, char_dim) outputs, hidden: (time_steps, batch_size, latent_dim)",
... | 2 | null | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, num_encoder_tokens, char_dim, latent_dim): Define layers for encoder
- def forward(self, input_var, hidden=None): input_var: (time_steps, batch_size) embedded: (... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def __init__(self, num_encoder_tokens, char_dim, latent_dim): Define layers for encoder
- def forward(self, input_var, hidden=None): input_var: (time_steps, batch_size) embedded: (... | 43c322504cd992e1c01412c8a04a37e2d14356b8 | <|skeleton|>
class Encoder:
def __init__(self, num_encoder_tokens, char_dim, latent_dim):
"""Define layers for encoder"""
<|body_0|>
def forward(self, input_var, hidden=None):
"""input_var: (time_steps, batch_size) embedded: (time_steps, batch_size, char_dim) outputs, hidden: (time_ste... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
def __init__(self, num_encoder_tokens, char_dim, latent_dim):
"""Define layers for encoder"""
super(Encoder, self).__init__()
self.embedding = nn.Embedding(num_encoder_tokens, char_dim)
self.lstm = nn.LSTM(char_dim, latent_dim)
def forward(self, input_var, hidden=... | the_stack_v2_python_sparse | 2.Deep_Learning/3.RNN/encoder-decoder/encoder.py | waynewu6250/My-Sample-Projects | train | 5 | |
32e6ce0da0451f86a0fb1e2713026908362fed0f | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')\ntotal_url = 'https://data.cityofboston.gov/resource/vwsn-4yhi.json'\nresponse = urllib.request.urlopen(total_url).read().decode('utf-8')\nr = json.loads(response... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7')
total_url = 'https://data.cityofboston.gov/resource/vwsn-4yhi.json'
response = urllib.request.urlopen(tot... | cornerstores | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cornerstores:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_36k_train_001797 | 3,458 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_008253 | Implement the Python class `cornerstores` described below.
Class description:
Implement the cornerstores class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `cornerstores` described below.
Class description:
Implement the cornerstores class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class cornerstores:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cornerstores:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('jguerero_mgarcia7', 'jguerero_mgarcia7... | the_stack_v2_python_sparse | jguerero_mgarcia7/cornerstores.py | lingyigu/course-2017-spr-proj | train | 0 | |
420be07774e250b1b3349a22a54715b27b101592 | [
"gen = ind + FigureControl.minPossibleGenNumber\nfor cplot in gs.cloud_plots:\n fitness = cplot.update_annot(gen)\ntext = '{}'.format(gen)\ngs.fitness_plot.floating_annot.xy = (gen, fitness)\ngs.fitness_plot.floating_annot.set_text(text)",
"for cplot in gs.cloud_plots:\n cplot.annot.set_visible(vis)\ngs.fit... | <|body_start_0|>
gen = ind + FigureControl.minPossibleGenNumber
for cplot in gs.cloud_plots:
fitness = cplot.update_annot(gen)
text = '{}'.format(gen)
gs.fitness_plot.floating_annot.xy = (gen, fitness)
gs.fitness_plot.floating_annot.set_text(text)
<|end_body_0|>
<|bo... | mouse move event on plots | MouseMove | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MouseMove:
"""mouse move event on plots"""
def update_annot(cls, ind):
"""update the parent floating annotations"""
<|body_0|>
def update_plot(cls, vis):
"""update the plots"""
<|body_1|>
def update(cls, event, curve, preferred_idx):
"""updat... | stack_v2_sparse_classes_36k_train_001798 | 4,481 | permissive | [
{
"docstring": "update the parent floating annotations",
"name": "update_annot",
"signature": "def update_annot(cls, ind)"
},
{
"docstring": "update the plots",
"name": "update_plot",
"signature": "def update_plot(cls, vis)"
},
{
"docstring": "update the plots and/or annotations"... | 4 | stack_v2_sparse_classes_30k_train_015539 | Implement the Python class `MouseMove` described below.
Class description:
mouse move event on plots
Method signatures and docstrings:
- def update_annot(cls, ind): update the parent floating annotations
- def update_plot(cls, vis): update the plots
- def update(cls, event, curve, preferred_idx): update the plots and... | Implement the Python class `MouseMove` described below.
Class description:
mouse move event on plots
Method signatures and docstrings:
- def update_annot(cls, ind): update the parent floating annotations
- def update_plot(cls, vis): update the plots
- def update(cls, event, curve, preferred_idx): update the plots and... | d0132c8a64516fbb45eb1e645c6312bbe56a7bc5 | <|skeleton|>
class MouseMove:
"""mouse move event on plots"""
def update_annot(cls, ind):
"""update the parent floating annotations"""
<|body_0|>
def update_plot(cls, vis):
"""update the plots"""
<|body_1|>
def update(cls, event, curve, preferred_idx):
"""updat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MouseMove:
"""mouse move event on plots"""
def update_annot(cls, ind):
"""update the parent floating annotations"""
gen = ind + FigureControl.minPossibleGenNumber
for cplot in gs.cloud_plots:
fitness = cplot.update_annot(gen)
text = '{}'.format(gen)
gs.... | the_stack_v2_python_sparse | visual_inspector/figure_base/mouse_event.py | justin-nguyen-1996/deep-neuroevolution | train | 1 |
e827095f507f7cdee9e561f33e4e7f3ade52dfae | [
"start = 0\nend = len(s) - 1\nfor i in range(len(s) // 2):\n temp = s[start]\n s[start] = s[end]\n s[end] = temp\n start += 1\n end -= 1",
"if len(s) == 1:\n return s\nleft = 0\nright = len(s) - 1\nwhile left < right:\n s[left], s[right] = (s[right], s[left])\n left += 1\n right -= 1\nr... | <|body_start_0|>
start = 0
end = len(s) - 1
for i in range(len(s) // 2):
temp = s[start]
s[start] = s[end]
s[end] = temp
start += 1
end -= 1
<|end_body_0|>
<|body_start_1|>
if len(s) == 1:
return s
left = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseString(self, s: List[str]) -> None:
"""Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s: List[str]) -> None:
"""Do not return anything, modify s in-place instead."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_001799 | 799 | no_license | [
{
"docstring": "Do not return anything, modify s in-place instead.",
"name": "reverseString",
"signature": "def reverseString(self, s: List[str]) -> None"
},
{
"docstring": "Do not return anything, modify s in-place instead.",
"name": "reverseString",
"signature": "def reverseString(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s: List[str]) -> None: Do not return anything, modify s in-place instead.
- def reverseString(self, s: List[str]) -> None: Do not return anything, modify ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s: List[str]) -> None: Do not return anything, modify s in-place instead.
- def reverseString(self, s: List[str]) -> None: Do not return anything, modify ... | 3d7ec221ff610d42cf18bb2e1130172b55072ac1 | <|skeleton|>
class Solution:
def reverseString(self, s: List[str]) -> None:
"""Do not return anything, modify s in-place instead."""
<|body_0|>
def reverseString(self, s: List[str]) -> None:
"""Do not return anything, modify s in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseString(self, s: List[str]) -> None:
"""Do not return anything, modify s in-place instead."""
start = 0
end = len(s) - 1
for i in range(len(s) // 2):
temp = s[start]
s[start] = s[end]
s[end] = temp
start += 1
... | the_stack_v2_python_sparse | leetcode-problems/344-reverse-string.py | aprilxyc/coding-interview-practice | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.