blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5b1ef5fd6c7696f62358d1765a07c5d4915cdd5e | [
"import re\ninput = re.split('(\\\\+|\\\\-|\\\\*|\\\\/)', input)\nn = len(input)\ndp = [[[] for _ in xrange(n)] for _ in xrange(n)]\nfor i in xrange(1, n + 1, 2):\n for j in xrange(0, n + 1 - i, 2):\n if i == 1:\n dp[j][j + i - 1].append(eval(input[j]))\n else:\n for k in xran... | <|body_start_0|>
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(n)]
for i in xrange(1, n + 1, 2):
for j in xrange(0, n + 1 - i, 2):
if i == 1:
dp[j][j + i - 1].app... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_10k_train_007400 | 2,376 | permissive | [
{
"docstring": "define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position",
"name": "diffWaysToCompute",
"signature": "def diffWaysToCompute(self, input)"
},
{
"docstring": ":type input: str :rtype: List[int]",
"name": "diffWaysToCompute_rec",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def diffWaysToCompute(self, input): define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position
- def diffWaysToCompute_rec(self, input)... | 86f1cb98de801f58c39d9a48ce9de12df7303d20 | <|skeleton|>
class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
<|body_0|>
def diffWaysToCompute_rec(self, input):
""":type input: str :rtype: List[int]"""
<|body_1|>
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def diffWaysToCompute(self, input):
"""define dp[i][j] is the result from the expression from i to j dp[j][j]=input[j] for j in odd position"""
import re
input = re.split('(\\+|\\-|\\*|\\/)', input)
n = len(input)
dp = [[[] for _ in xrange(n)] for _ in xrange(... | the_stack_v2_python_sparse | 241-Different-Ways-to-Add-Parentheses/solution.py | Tanych/CodeTracking | train | 0 | |
53108f54cb2a9967363dede539dfd5bd736d7542 | [
"seen = set()\nfor n in nums:\n if n in seen:\n return n\n else:\n seen.add(n)",
"slow = nums[0]\nfast = nums[nums[0]]\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\nfast = 0\nwhile slow != fast:\n slow = nums[slow]\n fast = nums[fast]\nreturn slow"
] | <|body_start_0|>
seen = set()
for n in nums:
if n in seen:
return n
else:
seen.add(n)
<|end_body_0|>
<|body_start_1|>
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""constant space, non mutable array, only works with positive, Floyd's algorithm"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_10k_train_007401 | 700 | no_license | [
{
"docstring": "allowing extra space",
"name": "findDuplicate",
"signature": "def findDuplicate(self, nums: List[int]) -> int"
},
{
"docstring": "constant space, non mutable array, only works with positive, Floyd's algorithm",
"name": "findDuplicate",
"signature": "def findDuplicate(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: allowing extra space
- def findDuplicate(self, nums: List[int]) -> int: constant space, non mutable array, only works with positi... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, nums: List[int]) -> int: allowing extra space
- def findDuplicate(self, nums: List[int]) -> int: constant space, non mutable array, only works with positi... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
<|body_0|>
def findDuplicate(self, nums: List[int]) -> int:
"""constant space, non mutable array, only works with positive, Floyd's algorithm"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""allowing extra space"""
seen = set()
for n in nums:
if n in seen:
return n
else:
seen.add(n)
def findDuplicate(self, nums: List[int]) -> int:
"""constant s... | the_stack_v2_python_sparse | Leetcode/287. Find the Diplicate Element.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
922da98e0e51957d2207a2a9067a1cc756e7fb26 | [
"if n < 10 and n > pow(2, 32) - 1:\n return -1\nns = list(str(n))\ni = len(ns) - 1\nwhile i > 0:\n if ns[i - 1] < ns[i]:\n j, p = (i, i)\n while j < len(ns) and ns[j] > ns[i - 1]:\n if ns[p] > ns[j]:\n p = j\n j += 1\n ns[i - 1], ns[p] = (ns[p], ns[i -... | <|body_start_0|>
if n < 10 and n > pow(2, 32) - 1:
return -1
ns = list(str(n))
i = len(ns) - 1
while i > 0:
if ns[i - 1] < ns[i]:
j, p = (i, i)
while j < len(ns) and ns[j] > ns[i - 1]:
if ns[p] > ns[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 10 and n > pow(2, 32) - 1:
return -... | stack_v2_sparse_classes_10k_train_007402 | 1,348 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement1",
"signature": "def nextGreaterElement1(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "nextGreaterElement",
"signature": "def nextGreaterElement(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement1(self, n): :type n: int :rtype: int
- def nextGreaterElement(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def nextGreaterElement1(self, n): :type n: int :rtype: int
- def nextGreaterElement(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def nextGreaterElement1(... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def nextGreaterElement(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def nextGreaterElement1(self, n):
""":type n: int :rtype: int"""
if n < 10 and n > pow(2, 32) - 1:
return -1
ns = list(str(n))
i = len(ns) - 1
while i > 0:
if ns[i - 1] < ns[i]:
j, p = (i, i)
while j < le... | the_stack_v2_python_sparse | py/leetcode/556.py | wfeng1991/learnpy | train | 0 | |
9827f2c266d245838a42a58f95f3892cb4e371e9 | [
"log = logging.getLogger(__name__)\napp = cls.objects.order_by('-created_at').first()\nif app and settings.DEBUG:\n log.debug(f'PagerDuty Access Token:{app.access_token}')\nsession = None\nif app:\n session = APISession(app.access_token, auth_type='oauth2')\nreturn session",
"session = cls.client()\nif not ... | <|body_start_0|>
log = logging.getLogger(__name__)
app = cls.objects.order_by('-created_at').first()
if app and settings.DEBUG:
log.debug(f'PagerDuty Access Token:{app.access_token}')
session = None
if app:
session = APISession(app.access_token, auth_type=... | Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process. | PagerDutyApp | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will ... | stack_v2_sparse_classes_10k_train_007403 | 15,122 | permissive | [
{
"docstring": "Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will be returned.",
"name": "client",
"signature": "def client(cls)"
},
{
"docstring": "Return the primary and secondary on call contacts. :retu... | 2 | stack_v2_sparse_classes_30k_train_002618 | Implement the Python class `PagerDutyApp` described below.
Class description:
Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process.
Method signatures and docstrings:
- def client(cls): Returns a client instance ready for use. :returns: The APISession instance for pager... | Implement the Python class `PagerDutyApp` described below.
Class description:
Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process.
Method signatures and docstrings:
- def client(cls): Returns a client instance ready for use. :returns: The APISession instance for pager... | 0fc00331851db8a37803a95acf8dde83ddbf8be8 | <|skeleton|>
class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PagerDutyApp:
"""Used to store Pager Duty OAuth client / app details after successfull completion of the OAuth process."""
def client(cls):
"""Returns a client instance ready for use. :returns: The APISession instance for pager duty. If the OAuth app is not yet set up then None will be returned."... | the_stack_v2_python_sparse | zenslackchat/models.py | oisinmulvihill/django-zenslackchat | train | 0 |
eff2b63b5159fd291bdb55b07e69b3c1de36e96f | [
"self.CapsuleGuid = self.EFI_FIRMWARE_MANAGEMENT_CAPSULE_ID_GUID\nself.HeaderSize = self._StructSize\nself.OemFlags = 0\nself.PersistAcrossReset = False\nself.PopulateSystemTable = False\nself.InitiateReset = False\nself.CapsuleImageSize = self.HeaderSize\nself.Payload = b''\nself.FmpCapsuleHeader = None",
"Flags... | <|body_start_0|>
self.CapsuleGuid = self.EFI_FIRMWARE_MANAGEMENT_CAPSULE_ID_GUID
self.HeaderSize = self._StructSize
self.OemFlags = 0
self.PersistAcrossReset = False
self.PopulateSystemTable = False
self.InitiateReset = False
self.CapsuleImageSize = self.HeaderSiz... | An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER since CapsuleGuid may imply extended header entries OemFlags (int): Bit-mapped list describ... | UefiCapsuleHeaderClass | [
"BSD-2-Clause-Patent"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UefiCapsuleHeaderClass:
"""An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER since CapsuleGuid may imply extended head... | stack_v2_sparse_classes_10k_train_007404 | 6,514 | permissive | [
{
"docstring": "Inits an empty object.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Serializes the Header + payload. Returns: (str): string representing packed data as bytes (i.e. b'\\\\x01\\\\x00\\\\x03')",
"name": "Encode",
"signature": "def Encode(self)"
... | 4 | stack_v2_sparse_classes_30k_test_000031 | Implement the Python class `UefiCapsuleHeaderClass` described below.
Class description:
An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER si... | Implement the Python class `UefiCapsuleHeaderClass` described below.
Class description:
An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER si... | 78295929b37af62a8cfc4c28eab72ed0c468f350 | <|skeleton|>
class UefiCapsuleHeaderClass:
"""An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER since CapsuleGuid may imply extended head... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UefiCapsuleHeaderClass:
"""An object representing a UEFI_CAPSULE_HEADER. Attributes: CapsuleGuid (uuid.UUID): 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A HeaderSize (int): The size of the capsule header. This may be larger than the size of the EFI_CAPSULE_HEADER since CapsuleGuid may imply extended header entries Oe... | the_stack_v2_python_sparse | edk2toollib/uefi/uefi_capsule_header.py | tianocore/edk2-pytool-library | train | 47 |
07a54f3e17701f1aa41e2455cee9cf3ac94ca323 | [
"def del_invalid_parentheses(string: str, open_parentheses: str, close_parentheses: str) -> str:\n string_builder = []\n balance = 0\n for char in string:\n if char == open_parentheses:\n balance += 1\n elif char == close_parentheses:\n if balance == 0:\n ... | <|body_start_0|>
def del_invalid_parentheses(string: str, open_parentheses: str, close_parentheses: str) -> str:
string_builder = []
balance = 0
for char in string:
if char == open_parentheses:
balance += 1
elif char == clos... | Parentheses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parentheses:
def minimum_remove_to_make_valid(self, s: str) -> str:
"""Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
<|body_0|>
def minimum_remove_to_make_valid_without_reverse(self, s: str) -> str:
"""Approach... | stack_v2_sparse_classes_10k_train_007405 | 2,276 | no_license | [
{
"docstring": "Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:",
"name": "minimum_remove_to_make_valid",
"signature": "def minimum_remove_to_make_valid(self, s: str) -> str"
},
{
"docstring": "Approach: Two Pass without reversing Time Complexi... | 2 | null | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def minimum_remove_to_make_valid(self, s: str) -> str: Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:
- def minimum_rem... | Implement the Python class `Parentheses` described below.
Class description:
Implement the Parentheses class.
Method signatures and docstrings:
- def minimum_remove_to_make_valid(self, s: str) -> str: Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:
- def minimum_rem... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Parentheses:
def minimum_remove_to_make_valid(self, s: str) -> str:
"""Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
<|body_0|>
def minimum_remove_to_make_valid_without_reverse(self, s: str) -> str:
"""Approach... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parentheses:
def minimum_remove_to_make_valid(self, s: str) -> str:
"""Approach: Two Pass + String Builder Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
def del_invalid_parentheses(string: str, open_parentheses: str, close_parentheses: str) -> str:
string_build... | the_stack_v2_python_sparse | goldman_sachs/minimum_remove_to_make_valid_parantheses.py | Shiv2157k/leet_code | train | 1 | |
8c42522c263eb8d0c4d6be04b4102fab36834681 | [
"try:\n failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()\nexcept NoResultFound:\n raise NotFoundError('could not find entry with ID %i' % failed_entry_id)\nreturn jsonify(failed_entry.to_dict())",
"try:\n failed_entry = session.query(db.FailedEntry).filter(d... | <|body_start_0|>
try:
failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()
except NoResultFound:
raise NotFoundError('could not find entry with ID %i' % failed_entry_id)
return jsonify(failed_entry.to_dict())
<|end_body_0|>
<|bo... | RetryFailedID | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
<|body_0|>
def delete(self, failed_entry_id, session=None):
"""Delete failed entry by ID"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
faile... | stack_v2_sparse_classes_10k_train_007406 | 4,968 | permissive | [
{
"docstring": "Get failed entry by ID",
"name": "get",
"signature": "def get(self, failed_entry_id, session=None)"
},
{
"docstring": "Delete failed entry by ID",
"name": "delete",
"signature": "def delete(self, failed_entry_id, session=None)"
}
] | 2 | null | Implement the Python class `RetryFailedID` described below.
Class description:
Implement the RetryFailedID class.
Method signatures and docstrings:
- def get(self, failed_entry_id, session=None): Get failed entry by ID
- def delete(self, failed_entry_id, session=None): Delete failed entry by ID | Implement the Python class `RetryFailedID` described below.
Class description:
Implement the RetryFailedID class.
Method signatures and docstrings:
- def get(self, failed_entry_id, session=None): Get failed entry by ID
- def delete(self, failed_entry_id, session=None): Delete failed entry by ID
<|skeleton|>
class Re... | 2b7e8314d103c94cf4552bd0152699eeca0ad159 | <|skeleton|>
class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
<|body_0|>
def delete(self, failed_entry_id, session=None):
"""Delete failed entry by ID"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RetryFailedID:
def get(self, failed_entry_id, session=None):
"""Get failed entry by ID"""
try:
failed_entry = session.query(db.FailedEntry).filter(db.FailedEntry.id == failed_entry_id).one()
except NoResultFound:
raise NotFoundError('could not find entry with ID... | the_stack_v2_python_sparse | flexget/components/failed/api.py | BrutuZ/Flexget | train | 1 | |
25262f39b7ed73a520188e7724426f33d3fa670e | [
"self.is_empty = threading.Event()\nself.is_empty.set()\nself._lock = threading.RLock()\nself._task_wrappers_in_graph = {}\nself._top_level_task_semaphore = threading.Semaphore(top_level_task_limit)",
"if dependent_task_ids is None:\n self._top_level_task_semaphore.acquire()\nwith self._lock:\n if task.para... | <|body_start_0|>
self.is_empty = threading.Event()
self.is_empty.set()
self._lock = threading.RLock()
self._task_wrappers_in_graph = {}
self._top_level_task_semaphore = threading.Semaphore(top_level_task_limit)
<|end_body_0|>
<|body_start_1|>
if dependent_task_ids is Non... | Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in it. | TaskGraph | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in... | stack_v2_sparse_classes_10k_train_007407 | 8,008 | permissive | [
{
"docstring": "Initializes a TaskGraph instance. Args: top_level_task_limit (int): A top-level task is a task that no other tasks depend on for completion (i.e. dependent_task_ids is None). Adding top-level tasks with TaskGraph.add will block until there are fewer than this number of top-level tasks in the gra... | 3 | stack_v2_sparse_classes_30k_train_006635 | Implement the Python class `TaskGraph` described below.
Class description:
Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set()... | Implement the Python class `TaskGraph` described below.
Class description:
Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set()... | 849d09dd7863efecbdf4072a504e1554e119f6ae | <|skeleton|>
class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TaskGraph:
"""Tracks dependencies between Task instances. See googlecloudsdk.command_lib.storage.tasks.task.Task for the definition of the Task class. The public methods in this class are thread safe. Attributes: is_empty (threading.Event): is_empty.is_set() is True when the graph has no tasks in it."""
... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/tasks/task_graph.py | PrateekKhatri/gcloud_cli | train | 0 |
53d8c8b24bf0eb0ba4633ee36abcd71612b8b05f | [
"h5_filename = tdc_Filenames.get_full_filename(calc_id, self.__default_Filename)\nfile_id = h5py.h5f.open(h5_filename, flags=h5py.h5f.ACC_RDONLY)\ndset_name = '/Mesh/CellBoundaries'\ndset = h5py.h5d.open(file_id, dset_name)\ndtype = dset.get_type()\ndspace = dset.get_space()\nself.nx, = dspace.get_simple_extent_dim... | <|body_start_0|>
h5_filename = tdc_Filenames.get_full_filename(calc_id, self.__default_Filename)
file_id = h5py.h5f.open(h5_filename, flags=h5py.h5f.ACC_RDONLY)
dset_name = '/Mesh/CellBoundaries'
dset = h5py.h5d.open(file_id, dset_name)
dtype = dset.get_type()
dspace = ds... | This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1] | tdc_Mesh | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tdc_Mesh:
"""This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1]"""
def __init__(self, calc_id, **kwargs):
"""Opens mesh.h5 file, ... | stack_v2_sparse_classes_10k_train_007408 | 2,002 | no_license | [
{
"docstring": "Opens mesh.h5 file, reads positions",
"name": "__init__",
"signature": "def __init__(self, calc_id, **kwargs)"
},
{
"docstring": "Transforms positions x into cell boundaries numbers xx Positions ()=> Cell #s",
"name": "x2cell",
"signature": "def x2cell(self, xx)"
},
{... | 3 | null | Implement the Python class `tdc_Mesh` described below.
Class description:
This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1]
Method signatures and docstrings:
- de... | Implement the Python class `tdc_Mesh` described below.
Class description:
This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1]
Method signatures and docstrings:
- de... | 775dc841b1d8538584c8c68a5f75ae997191e685 | <|skeleton|>
class tdc_Mesh:
"""This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1]"""
def __init__(self, calc_id, **kwargs):
"""Opens mesh.h5 file, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class tdc_Mesh:
"""This class contains coordinates of cell boundaries and function for transforming x coordinate in to a cell number Members: -------- x_b coordinates of cell boundaries dx cell width xmin x_b[0] xmax x_b[-1]"""
def __init__(self, calc_id, **kwargs):
"""Opens mesh.h5 file, reads positio... | the_stack_v2_python_sparse | Auxiliary/tdc_mesh.py | atimokhin/tdc_vis | train | 0 |
d57b3824bdfca75f2c31c7c6116607f269eb7e22 | [
"if geo_opt:\n self.settings.input.Geometry\nself.settings.input.Basis.type = 'DZP'\nself.settings.input.Basis.core = 'None'\nself.settings.input.XC.GGA = 'BP86'\nself.settings.input.AnalyticalFreq\nself.settings.input.SYMMETRY = 'NOSYM'\nself.settings.input.VCD = 'Yes'",
"if init:\n if path is None:\n ... | <|body_start_0|>
if geo_opt:
self.settings.input.Geometry
self.settings.input.Basis.type = 'DZP'
self.settings.input.Basis.core = 'None'
self.settings.input.XC.GGA = 'BP86'
self.settings.input.AnalyticalFreq
self.settings.input.SYMMETRY = 'NOSYM'
self.... | Class used for geometry optimization + frequency jobs using DFT | DFTJob | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, path=None):
"""... | stack_v2_sparse_classes_10k_train_007409 | 3,480 | no_license | [
{
"docstring": "Method that specifies standard settings for a DFT geometry optimization + freqs job",
"name": "_set_std_settings",
"signature": "def _set_std_settings(self, geo_opt=False)"
},
{
"docstring": "Method that runs this job",
"name": "run",
"signature": "def run(self, init=True... | 2 | stack_v2_sparse_classes_30k_train_007023 | Implement the Python class `DFTJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DFT
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFT geometry optimization + freqs job
- def run(self, in... | Implement the Python class `DFTJob` described below.
Class description:
Class used for geometry optimization + frequency jobs using DFT
Method signatures and docstrings:
- def _set_std_settings(self, geo_opt=False): Method that specifies standard settings for a DFT geometry optimization + freqs job
- def run(self, in... | 30b64bd89023b8b7cdd37270bb8970b04c7a7081 | <|skeleton|>
class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
<|body_0|>
def run(self, init=True, path=None):
"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DFTJob:
"""Class used for geometry optimization + frequency jobs using DFT"""
def _set_std_settings(self, geo_opt=False):
"""Method that specifies standard settings for a DFT geometry optimization + freqs job"""
if geo_opt:
self.settings.input.Geometry
self.settings.in... | the_stack_v2_python_sparse | comparion data and code/modules/jobs.py | YHordijk/bachelorproject | train | 0 |
2f1c549672138c80aaf2d9e599d57cb36b458a89 | [
"self.db = config['mongo']['database']\nself.collection = config['mongo']['COLLECTION']\nself.mongo_config = config['mongo']\nif self.mongo_config == False:\n return None\nself.user = self.mongo_config.get('user', '')\nself.password = self.mongo_config.get('password', '')\nself.host = self.mongo_config.get('host... | <|body_start_0|>
self.db = config['mongo']['database']
self.collection = config['mongo']['COLLECTION']
self.mongo_config = config['mongo']
if self.mongo_config == False:
return None
self.user = self.mongo_config.get('user', '')
self.password = self.mongo_confi... | ZenMongoDB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZenMongoDB:
def __init__(self):
"""コンストラクタ"""
<|body_0|>
def connect_db(self):
"""モンゴブ接続機能"""
<|body_1|>
def insert_data(self, data, collection):
"""Insert data into Collection :param data :(dictionary) format {"field_key": "field_value"} :param ... | stack_v2_sparse_classes_10k_train_007410 | 4,730 | no_license | [
{
"docstring": "コンストラクタ",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "モンゴブ接続機能",
"name": "connect_db",
"signature": "def connect_db(self)"
},
{
"docstring": "Insert data into Collection :param data :(dictionary) format {\"field_key\": \"field_value\"}... | 5 | stack_v2_sparse_classes_30k_train_006598 | Implement the Python class `ZenMongoDB` described below.
Class description:
Implement the ZenMongoDB class.
Method signatures and docstrings:
- def __init__(self): コンストラクタ
- def connect_db(self): モンゴブ接続機能
- def insert_data(self, data, collection): Insert data into Collection :param data :(dictionary) format {"field_k... | Implement the Python class `ZenMongoDB` described below.
Class description:
Implement the ZenMongoDB class.
Method signatures and docstrings:
- def __init__(self): コンストラクタ
- def connect_db(self): モンゴブ接続機能
- def insert_data(self, data, collection): Insert data into Collection :param data :(dictionary) format {"field_k... | ec32afdb2a17acbcb21089008a37526195dd39f1 | <|skeleton|>
class ZenMongoDB:
def __init__(self):
"""コンストラクタ"""
<|body_0|>
def connect_db(self):
"""モンゴブ接続機能"""
<|body_1|>
def insert_data(self, data, collection):
"""Insert data into Collection :param data :(dictionary) format {"field_key": "field_value"} :param ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZenMongoDB:
def __init__(self):
"""コンストラクタ"""
self.db = config['mongo']['database']
self.collection = config['mongo']['COLLECTION']
self.mongo_config = config['mongo']
if self.mongo_config == False:
return None
self.user = self.mongo_config.get('user... | the_stack_v2_python_sparse | Python test/Project/Project/src/bbin/zen/db/mongo.py | sacki123/django_training | train | 1 | |
9a271f9b08b3c1b6fd0d99f87872cbeb78d93115 | [
"if db_field.name == 'user':\n kwargs['queryset'] = User.objects.filter(id=request.user.id)\n kwargs['initial'] = request.user.id\nelif db_field.name == 'topic' and (not request.user.is_superuser):\n kwargs['queryset'] = Topic.objects.filter(id__in=request.user.profile.topics.all())\nreturn super(MaterialA... | <|body_start_0|>
if db_field.name == 'user':
kwargs['queryset'] = User.objects.filter(id=request.user.id)
kwargs['initial'] = request.user.id
elif db_field.name == 'topic' and (not request.user.is_superuser):
kwargs['queryset'] = Topic.objects.filter(id__in=request.us... | MaterialAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaterialAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Limits the choices of prof... | stack_v2_sparse_classes_10k_train_007411 | 9,167 | permissive | [
{
"docstring": "Assigns default value for User field. limits Topics field to user's topics.",
"name": "formfield_for_foreignkey",
"signature": "def formfield_for_foreignkey(self, db_field, request, **kwargs)"
},
{
"docstring": "Limits the choices of professors for the limit of user.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000465 | Implement the Python class `MaterialAdmin` described below.
Class description:
Implement the MaterialAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics.
- def formfield_for_manytom... | Implement the Python class `MaterialAdmin` described below.
Class description:
Implement the MaterialAdmin class.
Method signatures and docstrings:
- def formfield_for_foreignkey(self, db_field, request, **kwargs): Assigns default value for User field. limits Topics field to user's topics.
- def formfield_for_manytom... | 70638c121ea85ff0e6a650c5f2641b0b3b04d6d0 | <|skeleton|>
class MaterialAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
<|body_0|>
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""Limits the choices of prof... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MaterialAdmin:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Assigns default value for User field. limits Topics field to user's topics."""
if db_field.name == 'user':
kwargs['queryset'] = User.objects.filter(id=request.user.id)
kwargs['initial'] =... | the_stack_v2_python_sparse | cms/admin.py | Ibrahem3amer/bala7 | train | 0 | |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super(SoftExponential, self).__init__()\nif alpha is None:\n self.alpha = nn.Parameter(torch.tensor(0.0))\nelse:\n self.alpha = nn.Parameter(torch.tensor(alpha))\nself.alpha.requiresGrad = True",
"if self.alpha == 0.0:\n return x\nif self.alpha < 0.0:\n return -torch.log(1 - self.alpha * (x + self.al... | <|body_start_0|>
super(SoftExponential, self).__init__()
if alpha is None:
self.alpha = nn.Parameter(torch.tensor(0.0))
else:
self.alpha = nn.Parameter(torch.tensor(alpha))
self.alpha.requiresGrad = True
<|end_body_0|>
<|body_start_1|>
if self.alpha == 0.... | SoftExponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftExponential:
def __init__(self, alpha=None):
"""Init method."""
<|body_0|>
def forward(self, x):
"""Forward pass of the function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(SoftExponential, self).__init__()
if alpha is None:
... | stack_v2_sparse_classes_10k_train_007412 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, alpha=None)"
},
{
"docstring": "Forward pass of the function",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007370 | Implement the Python class `SoftExponential` described below.
Class description:
Implement the SoftExponential class.
Method signatures and docstrings:
- def __init__(self, alpha=None): Init method.
- def forward(self, x): Forward pass of the function | Implement the Python class `SoftExponential` described below.
Class description:
Implement the SoftExponential class.
Method signatures and docstrings:
- def __init__(self, alpha=None): Init method.
- def forward(self, x): Forward pass of the function
<|skeleton|>
class SoftExponential:
def __init__(self, alpha... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SoftExponential:
def __init__(self, alpha=None):
"""Init method."""
<|body_0|>
def forward(self, x):
"""Forward pass of the function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SoftExponential:
def __init__(self, alpha=None):
"""Init method."""
super(SoftExponential, self).__init__()
if alpha is None:
self.alpha = nn.Parameter(torch.tensor(0.0))
else:
self.alpha = nn.Parameter(torch.tensor(alpha))
self.alpha.requiresGra... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
cf654818c3d4fa50d3cee837f7942e3dd7ac4725 | [
"self.ls = []\nself.rs = []\nself.val = None\nself.empty = True",
"if self.val == None:\n if self.empty or (num >= self.ls[-1] and self.rs[-1] >= num):\n self.val = num\n elif num < self.ls[-1]:\n self.val = self.ls[-1]\n self.ls[-1] = num\n else:\n self.val = self.rs[-1]\n ... | <|body_start_0|>
self.ls = []
self.rs = []
self.val = None
self.empty = True
<|end_body_0|>
<|body_start_1|>
if self.val == None:
if self.empty or (num >= self.ls[-1] and self.rs[-1] >= num):
self.val = num
elif num < self.ls[-1]:
... | MedianFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k_train_007413 | 3,350 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a num into the data structure. :type num: int :rtype: void",
"name": "addNum",
"signature": "def addNum(self, num)"
},
{
"docstring": "Returns the ... | 3 | stack_v2_sparse_classes_30k_train_001968 | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | Implement the Python class `MedianFinder` described below.
Class description:
Implement the MedianFinder class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addNum(self, num): Adds a num into the data structure. :type num: int :rtype: void
- def findMedian(self): ... | 737b9bac5a73c319e46cda8c3e9d729f734d7792 | <|skeleton|>
class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
<|body_1|>
def findMedian(self):
"""Returns the median of current... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MedianFinder:
def __init__(self):
"""Initialize your data structure here."""
self.ls = []
self.rs = []
self.val = None
self.empty = True
def addNum(self, num):
"""Adds a num into the data structure. :type num: int :rtype: void"""
if self.val == None... | the_stack_v2_python_sparse | leetcode/python/295-find-median-from-data-stream.py | iampkuhz/OnlineJudge_cpp | train | 0 | |
5a1d929fbe7760d78228296c93ec42c9708bb274 | [
"self.drive_vec = drive_vec\nself.id = id\nself.is_full_channel_restore = is_full_channel_restore\nself.name = name",
"if dictionary is None:\n return None\ndrive_vec = None\nif dictionary.get('driveVec') != None:\n drive_vec = list()\n for structure in dictionary.get('driveVec'):\n drive_vec.appe... | <|body_start_0|>
self.drive_vec = drive_vec
self.id = id
self.is_full_channel_restore = is_full_channel_restore
self.name = name
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
drive_vec = None
if dictionary.get('driveVec') != None:... | Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_channel_restore is true. id (string): Id of the source channel for re... | RestoreO365TeamsParams_SourceChannel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365TeamsParams_SourceChannel:
"""Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_chann... | stack_v2_sparse_classes_10k_train_007414 | 2,610 | permissive | [
{
"docstring": "Constructor for the RestoreO365TeamsParams_SourceChannel class",
"name": "__init__",
"signature": "def __init__(self, drive_vec=None, id=None, is_full_channel_restore=None, name=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | null | Implement the Python class `RestoreO365TeamsParams_SourceChannel` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restore... | Implement the Python class `RestoreO365TeamsParams_SourceChannel` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restore... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365TeamsParams_SourceChannel:
"""Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_chann... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreO365TeamsParams_SourceChannel:
"""Implementation of the 'RestoreO365TeamsParams_SourceChannel' model. TODO: type description here. Attributes: drive_vec (list of RestoreSiteParams_SiteOwner_Drive): Drives of this channel whose items have to be restored. This will be empty iff is_full_channel_restore is... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_teams_params_source_channel.py | cohesity/management-sdk-python | train | 24 |
1659815983518b689ffbbeb70455e7b1f4bf4598 | [
"self.history = [homepage]\nself.curr = 0\nself.length = 1",
"self.history = self.history[:self.curr + 1]\nself.history.append(url)\nself.length = len(self.history)\nself.curr = self.length - 1",
"if self.curr - steps < 0:\n self.curr = 0\nelse:\n self.curr -= steps\nreturn self.history[self.curr]",
"if... | <|body_start_0|>
self.history = [homepage]
self.curr = 0
self.length = 1
<|end_body_0|>
<|body_start_1|>
self.history = self.history[:self.curr + 1]
self.history.append(url)
self.length = len(self.history)
self.curr = self.length - 1
<|end_body_1|>
<|body_start_... | BrowserHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str"""
<|body_2|>
def forward(se... | stack_v2_sparse_classes_10k_train_007415 | 1,103 | no_license | [
{
"docstring": ":type homepage: str",
"name": "__init__",
"signature": "def __init__(self, homepage)"
},
{
"docstring": ":type url: str :rtype: None",
"name": "visit",
"signature": "def visit(self, url)"
},
{
"docstring": ":type steps: int :rtype: str",
"name": "back",
"s... | 4 | stack_v2_sparse_classes_30k_train_004237 | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str
- def forw... | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str
- def forw... | 0886b4f9ed587507257611f1ad11d3bf03494a91 | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str"""
<|body_2|>
def forward(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
self.history = [homepage]
self.curr = 0
self.length = 1
def visit(self, url):
""":type url: str :rtype: None"""
self.history = self.history[:self.curr + 1]
self.history.append(u... | the_stack_v2_python_sparse | leetcode/Medium/design browser history.py | simhonchourasia/leetcodesolutions | train | 0 | |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super().__init__()\nself.alpha = alpha\nself.isrlu = isrlu",
"if self.isrlu is not False:\n return (input < 0).float() * isru(input, self.apha) + (input >= 0).float() * input\nelse:\n return isru(input, self.apha)"
] | <|body_start_0|>
super().__init__()
self.alpha = alpha
self.isrlu = isrlu
<|end_body_0|>
<|body_start_1|>
if self.isrlu is not False:
return (input < 0).float() * isru(input, self.apha) + (input >= 0).float() * input
else:
return isru(input, self.apha)
<|... | ISRU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.alpha = alpha
self.isr... | stack_v2_sparse_classes_10k_train_007416 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, alpha=1.0, isrlu=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000408 | Implement the Python class `ISRU` described below.
Class description:
Implement the ISRU class.
Method signatures and docstrings:
- def __init__(self, alpha=1.0, isrlu=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `ISRU` described below.
Class description:
Implement the ISRU class.
Method signatures and docstrings:
- def __init__(self, alpha=1.0, isrlu=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=Fals... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
super().__init__()
self.alpha = alpha
self.isrlu = isrlu
def forward(self, input):
"""Forward pass of the function."""
if self.isrlu is not False:
return (input < 0).float() * ... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
3a8b2cf6d3f36cfe05234b8088f2db3fb8254e99 | [
"self._logger = logger\nself._no_run = False\nif not is_exe(exe_path):\n self._logger.error('No convert_format script available (exiting)')\n sys.exit(1)\nself._exe_path = exe_path\nself.informat = 'fastq'\nself.outformat = 'fasta'",
"self._outdirname = os.path.join(outdir)\nif not os.path.exists(self._outd... | <|body_start_0|>
self._logger = logger
self._no_run = False
if not is_exe(exe_path):
self._logger.error('No convert_format script available (exiting)')
sys.exit(1)
self._exe_path = exe_path
self.informat = 'fastq'
self.outformat = 'fasta'
<|end_bod... | Class for working with convert_format | Convert_Format | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Convert_Format:
"""Class for working with convert_format"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname, outdir, logger=None):
"""Run convert_format on the passed file"""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_007417 | 3,597 | permissive | [
{
"docstring": "Instantiate with location of executable",
"name": "__init__",
"signature": "def __init__(self, exe_path, logger)"
},
{
"docstring": "Run convert_format on the passed file",
"name": "run",
"signature": "def run(self, infname, outdir, logger=None)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_001543 | Implement the Python class `Convert_Format` described below.
Class description:
Class for working with convert_format
Method signatures and docstrings:
- def __init__(self, exe_path, logger): Instantiate with location of executable
- def run(self, infname, outdir, logger=None): Run convert_format on the passed file
-... | Implement the Python class `Convert_Format` described below.
Class description:
Class for working with convert_format
Method signatures and docstrings:
- def __init__(self, exe_path, logger): Instantiate with location of executable
- def run(self, infname, outdir, logger=None): Run convert_format on the passed file
-... | a3c64198aad3709a5c4d969f48ae0af11fdc25db | <|skeleton|>
class Convert_Format:
"""Class for working with convert_format"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
<|body_0|>
def run(self, infname, outdir, logger=None):
"""Run convert_format on the passed file"""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Convert_Format:
"""Class for working with convert_format"""
def __init__(self, exe_path, logger):
"""Instantiate with location of executable"""
self._logger = logger
self._no_run = False
if not is_exe(exe_path):
self._logger.error('No convert_format script avai... | the_stack_v2_python_sparse | metapy/pycits/seq_crumbs.py | peterthorpe5/public_scripts | train | 35 |
105572cacce8cd3c9884e1c37d137915ff8d0be2 | [
"self.p0 = p0\nself.p1 = p1\nself.p2 = p2\nself.rowid = rowid",
"volume = self.p0.x * (self.p1.z * self.p2.y - self.p1.y * self.p2.z)\nvolume += self.p0.y * (self.p1.x * self.p2.z - self.p1.z * self.p2.x)\nvolume += self.p0.z * (self.p1.y * self.p2.x - self.p1.x * self.p2.y)\nreturn volume / 6",
"D0 = [[centroi... | <|body_start_0|>
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.rowid = rowid
<|end_body_0|>
<|body_start_1|>
volume = self.p0.x * (self.p1.z * self.p2.y - self.p1.y * self.p2.z)
volume += self.p0.y * (self.p1.x * self.p2.z - self.p1.z * self.p2.x)
volume += self.p0... | Tetrahedron3d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tetrahedron3d:
def __init__(self, p0, p1, p2, rowid=-1):
"""@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d"""
<|body_0|>
def tetrahedronVolume(self):
"""Funcion que obtiene el volumen del tetraedro formado entre el tri... | stack_v2_sparse_classes_10k_train_007418 | 2,652 | no_license | [
{
"docstring": "@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d",
"name": "__init__",
"signature": "def __init__(self, p0, p1, p2, rowid=-1)"
},
{
"docstring": "Funcion que obtiene el volumen del tetraedro formado entre el triangulo exterior y el c... | 3 | stack_v2_sparse_classes_30k_train_002447 | Implement the Python class `Tetrahedron3d` described below.
Class description:
Implement the Tetrahedron3d class.
Method signatures and docstrings:
- def __init__(self, p0, p1, p2, rowid=-1): @param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d
- def tetrahedronVolume(self):... | Implement the Python class `Tetrahedron3d` described below.
Class description:
Implement the Tetrahedron3d class.
Method signatures and docstrings:
- def __init__(self, p0, p1, p2, rowid=-1): @param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d
- def tetrahedronVolume(self):... | a93de278ea92ad8d57d66fcb76744d394400bd11 | <|skeleton|>
class Tetrahedron3d:
def __init__(self, p0, p1, p2, rowid=-1):
"""@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d"""
<|body_0|>
def tetrahedronVolume(self):
"""Funcion que obtiene el volumen del tetraedro formado entre el tri... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tetrahedron3d:
def __init__(self, p0, p1, p2, rowid=-1):
"""@param p0: instancia de Point3d @param p1: instancia de Point3d @param p2: instancia de Point3d"""
self.p0 = p0
self.p1 = p1
self.p2 = p2
self.rowid = rowid
def tetrahedronVolume(self):
"""Funcion ... | the_stack_v2_python_sparse | geometry/controller/geometry_3d/tetrahedron_3d.py | nvergarayi/Cubicador | train | 0 | |
1ac0ef75dbb36aaf0434179755d81ac04d5e078e | [
"password1 = self.cleaned_data.get('password1')\npassword2 = self.cleaned_data.get('password2')\nif password1 and password2:\n if password1 != password2:\n raise forms.ValidationError(\"Passwords are n't the same\")\nelse:\n raise forms.ValidationError(\"Passwords can't be empty\")\nreturn password2",
... | <|body_start_0|>
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2:
if password1 != password2:
raise forms.ValidationError("Passwords are n't the same")
else:
raise forms.Valida... | A form for registering new users with all required field | UserCreationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationForm:
"""A form for registering new users with all required field"""
def clean_password2(self):
"""Check to ensure passwords are the same"""
<|body_0|>
def save(self, commit=True):
"""Save password in hashed form"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_007419 | 2,376 | no_license | [
{
"docstring": "Check to ensure passwords are the same",
"name": "clean_password2",
"signature": "def clean_password2(self)"
},
{
"docstring": "Save password in hashed form",
"name": "save",
"signature": "def save(self, commit=True)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005336 | Implement the Python class `UserCreationForm` described below.
Class description:
A form for registering new users with all required field
Method signatures and docstrings:
- def clean_password2(self): Check to ensure passwords are the same
- def save(self, commit=True): Save password in hashed form | Implement the Python class `UserCreationForm` described below.
Class description:
A form for registering new users with all required field
Method signatures and docstrings:
- def clean_password2(self): Check to ensure passwords are the same
- def save(self, commit=True): Save password in hashed form
<|skeleton|>
cla... | dbee8cab22d83e8b5d29c5172b5c3b1cdd729610 | <|skeleton|>
class UserCreationForm:
"""A form for registering new users with all required field"""
def clean_password2(self):
"""Check to ensure passwords are the same"""
<|body_0|>
def save(self, commit=True):
"""Save password in hashed form"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserCreationForm:
"""A form for registering new users with all required field"""
def clean_password2(self):
"""Check to ensure passwords are the same"""
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2... | the_stack_v2_python_sparse | webproject/src/accounts/forms.py | Ajitesh27/SuperMarket-Management-System | train | 19 |
55a2cd8eccbbd05f72e82f8b640dc7225f97235f | [
"args = self.parser.parse_args()\nmaster = args.master_url\nremove = args.remove\nwarning = ''\nif remove:\n if 0 == redis.srem(MASTER_BLACKLIST_KEY, master):\n warning = 'The master was already not on the blacklist'\nelif 0 == redis.sadd(MASTER_BLACKLIST_KEY, master):\n warning = 'The master was alrea... | <|body_start_0|>
args = self.parser.parse_args()
master = args.master_url
remove = args.remove
warning = ''
if remove:
if 0 == redis.srem(MASTER_BLACKLIST_KEY, master):
warning = 'The master was already not on the blacklist'
elif 0 == redis.sad... | Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project configs. | JenkinsMasterBlacklistAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JenkinsMasterBlacklistAPIView:
"""Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project configs."""
def post(self):
""... | stack_v2_sparse_classes_10k_train_007420 | 2,202 | permissive | [
{
"docstring": "Adds or removes a master from the blacklist. The post params should include the `master_url` to be added or removed. By default, the master will be added to the blacklist. Set `remove` to be true to remove the master. Responds with the current blacklist and a warning message if it was a noop.",
... | 2 | stack_v2_sparse_classes_30k_train_007310 | Implement the Python class `JenkinsMasterBlacklistAPIView` described below.
Class description:
Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project conf... | Implement the Python class `JenkinsMasterBlacklistAPIView` described below.
Class description:
Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project conf... | ae5159498f239a48184accf811cf36be2eab1e96 | <|skeleton|>
class JenkinsMasterBlacklistAPIView:
"""Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project configs."""
def post(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JenkinsMasterBlacklistAPIView:
"""Endpoint for managing the Jenkins master blacklist. The blacklist is a set of Jenkins masters that Changes won't give jobs to. This is useful for gracefully removing a master temporarily without having to modify project configs."""
def post(self):
"""Adds or remo... | the_stack_v2_python_sparse | changes/api/jenkins_master_blacklist.py | getsentry/changes | train | 6 |
88b6b065e81269ed88733245e0c345e6b387d765 | [
"try:\n self.session_duration = int(getenv('SESSION_DURATION', 0))\nexcept ValueError:\n self.session_duration = 0",
"session_id = super().create_session(user_id)\nif session_id is None:\n return None\nSessionExpAuth.user_id_by_session_id[session_id] = {'user_id': user_id, 'created_at': datetime.now()}\n... | <|body_start_0|>
try:
self.session_duration = int(getenv('SESSION_DURATION', 0))
except ValueError:
self.session_duration = 0
<|end_body_0|>
<|body_start_1|>
session_id = super().create_session(user_id)
if session_id is None:
return None
Sessi... | Extend behavior of SessionAuth class for session expiry. | SessionExpAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
<|body_0|>
def create_session(self, user_id=None):
"""Create session associated with specified user id."""
<|bo... | stack_v2_sparse_classes_10k_train_007421 | 1,760 | no_license | [
{
"docstring": "Initialize instance of SessionExpAuth.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create session associated with specified user id.",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_005825 | Implement the Python class `SessionExpAuth` described below.
Class description:
Extend behavior of SessionAuth class for session expiry.
Method signatures and docstrings:
- def __init__(self): Initialize instance of SessionExpAuth.
- def create_session(self, user_id=None): Create session associated with specified use... | Implement the Python class `SessionExpAuth` described below.
Class description:
Extend behavior of SessionAuth class for session expiry.
Method signatures and docstrings:
- def __init__(self): Initialize instance of SessionExpAuth.
- def create_session(self, user_id=None): Create session associated with specified use... | 609a1679d2c31400979d96523565db8c2d12d794 | <|skeleton|>
class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
<|body_0|>
def create_session(self, user_id=None):
"""Create session associated with specified user id."""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SessionExpAuth:
"""Extend behavior of SessionAuth class for session expiry."""
def __init__(self):
"""Initialize instance of SessionExpAuth."""
try:
self.session_duration = int(getenv('SESSION_DURATION', 0))
except ValueError:
self.session_duration = 0
... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_exp_auth.py | agzsoftsi/holbertonschool-web_back_end | train | 2 |
092bdb9a602ae0f2f00413fa5729592b6f90b7ca | [
"query = typeFor(self)\nassert isinstance(query, TypeQuery), 'Invalid query %s' % self\nfor name, value in keyargs.items():\n if name not in query.properties:\n raise ValueError(\"Invalid criteria name '%s' for %s\" % (name, query))\n setattr(self, name, value)",
"entry = typeFor(ref)\nif not isinsta... | <|body_start_0|>
query = typeFor(self)
assert isinstance(query, TypeQuery), 'Invalid query %s' % self
for name, value in keyargs.items():
if name not in query.properties:
raise ValueError("Invalid criteria name '%s' for %s" % (name, query))
setattr(self, n... | Support class for queries. | Query | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Query:
"""Support class for queries."""
def __init__(self, **keyargs):
"""Construct the instance of the query by automatically setting as criterias the values provides as key arguments."""
<|body_0|>
def __contains__(self, ref):
"""Checks if the object contains a... | stack_v2_sparse_classes_10k_train_007422 | 16,647 | no_license | [
{
"docstring": "Construct the instance of the query by automatically setting as criterias the values provides as key arguments.",
"name": "__init__",
"signature": "def __init__(self, **keyargs)"
},
{
"docstring": "Checks if the object contains a value for the property even if that value is None.... | 2 | null | Implement the Python class `Query` described below.
Class description:
Support class for queries.
Method signatures and docstrings:
- def __init__(self, **keyargs): Construct the instance of the query by automatically setting as criterias the values provides as key arguments.
- def __contains__(self, ref): Checks if ... | Implement the Python class `Query` described below.
Class description:
Support class for queries.
Method signatures and docstrings:
- def __init__(self, **keyargs): Construct the instance of the query by automatically setting as criterias the values provides as key arguments.
- def __contains__(self, ref): Checks if ... | e0b3466b34d31548996d57be4a9dac134d904380 | <|skeleton|>
class Query:
"""Support class for queries."""
def __init__(self, **keyargs):
"""Construct the instance of the query by automatically setting as criterias the values provides as key arguments."""
<|body_0|>
def __contains__(self, ref):
"""Checks if the object contains a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Query:
"""Support class for queries."""
def __init__(self, **keyargs):
"""Construct the instance of the query by automatically setting as criterias the values provides as key arguments."""
query = typeFor(self)
assert isinstance(query, TypeQuery), 'Invalid query %s' % self
... | the_stack_v2_python_sparse | components/ally-api/ally/api/operator/descriptor.py | cristidomsa/Ally-Py | train | 0 |
8f2f6fb1cd424736e57cdbd7f8ef1403faec28e8 | [
"if root is None:\n return ''\nq = deque([root])\nres = []\nq.append('#')\nwhile q:\n sz = len(q)\n for _ in range(sz):\n node = q.popleft()\n if node == '#':\n res.append('#')\n continue\n res.append(str(node.val))\n for c in node.children:\n q.... | <|body_start_0|>
if root is None:
return ''
q = deque([root])
res = []
q.append('#')
while q:
sz = len(q)
for _ in range(sz):
node = q.popleft()
if node == '#':
res.append('#')
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_007423 | 1,727 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_test_000074 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | de2727f1cc52ce08a06d63cff77b6ef6bb9d2528 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
if root is None:
return ''
q = deque([root])
res = []
q.append('#')
while q:
sz = len(q)
for _ in range(sz)... | the_stack_v2_python_sparse | 428-serialize-and-deserialize-n-ary-tree/428-serialize-and-deserialize-n-ary-tree.py | vinija/LeetCode | train | 116 | |
1dccf0b67990e9391a4ea6813d28c7c13881a034 | [
"self.xi = np.asarray(xi)\nself.T = T\nself.n_waypoints = xi.shape[0]\ntimesteps = np.linspace(0, self.T, self.n_waypoints)\nself.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')\nself.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')\nself.f3 = interp1d(timesteps, self.xi[:, 2], kind='cubic')\nself.f4 = i... | <|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], kind='cubic')
self.f2 = interp1d(timesteps, self.xi[:, 1], kind='cubic')
self.f3 =... | Trajectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.xi = np.asarray(xi)
self.T = T
... | stack_v2_sparse_classes_10k_train_007424 | 6,389 | permissive | [
{
"docstring": "create cublic interpolators between waypoints",
"name": "__init__",
"signature": "def __init__(self, xi, T)"
},
{
"docstring": "get interpolated position",
"name": "get",
"signature": "def get(self, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002268 | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position | Implement the Python class `Trajectory` described below.
Class description:
Implement the Trajectory class.
Method signatures and docstrings:
- def __init__(self, xi, T): create cublic interpolators between waypoints
- def get(self, t): get interpolated position
<|skeleton|>
class Trajectory:
def __init__(self,... | 65695ac0ad4ffc28474f1920c2d2ff484481caf3 | <|skeleton|>
class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
<|body_0|>
def get(self, t):
"""get interpolated position"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Trajectory:
def __init__(self, xi, T):
"""create cublic interpolators between waypoints"""
self.xi = np.asarray(xi)
self.T = T
self.n_waypoints = xi.shape[0]
timesteps = np.linspace(0, self.T, self.n_waypoints)
self.f1 = interp1d(timesteps, self.xi[:, 0], kind='... | the_stack_v2_python_sparse | robot-experiment/play_task2.py | VT-Collab/choice-sets | train | 1 | |
12f6d297a51620e72d78390169a7d4db9818e091 | [
"self.robot = robot\nself.us = ev3.UltrasonicSensor('in3')\nself.us.mode = 'US-DIST-CM'\nself.state = 'seeking'\nself.robot.forward(0.3)",
"if self.state == 'seeking' and self.us.distance_centimeters <= 10:\n self.state = 'found'\n self.robot.stop()\nelif self.state == 'found' and self.us.distance_centimete... | <|body_start_0|>
self.robot = robot
self.us = ev3.UltrasonicSensor('in3')
self.us.mode = 'US-DIST-CM'
self.state = 'seeking'
self.robot.forward(0.3)
<|end_body_0|>
<|body_start_1|>
if self.state == 'seeking' and self.us.distance_centimeters <= 10:
self.state ... | This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving. | Timid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Timid:
"""This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving."""
def __init__(self, robot=None):
"""Set up motors/robot and sensors here, set state to 'seeking' and forward sp... | stack_v2_sparse_classes_10k_train_007425 | 6,005 | no_license | [
{
"docstring": "Set up motors/robot and sensors here, set state to 'seeking' and forward speed to nonzero",
"name": "__init__",
"signature": "def __init__(self, robot=None)"
},
{
"docstring": "Updates the FSM by reading sensor data, then choosing based on the state",
"name": "run",
"sign... | 2 | stack_v2_sparse_classes_30k_train_007057 | Implement the Python class `Timid` described below.
Class description:
This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving.
Method signatures and docstrings:
- def __init__(self, robot=None): Set up motors/robo... | Implement the Python class `Timid` described below.
Class description:
This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving.
Method signatures and docstrings:
- def __init__(self, robot=None): Set up motors/robo... | 59bd3e0825e8009ba60ad629962944f135e79c88 | <|skeleton|>
class Timid:
"""This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving."""
def __init__(self, robot=None):
"""Set up motors/robot and sensors here, set state to 'seeking' and forward sp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Timid:
"""This behavior should move forward at a fixed, not-too-fast speed if no object is close enough in front of it. When an object is detected, it should stop moving."""
def __init__(self, robot=None):
"""Set up motors/robot and sensors here, set state to 'seeking' and forward speed to nonzer... | the_stack_v2_python_sparse | fsmCodeA.py | dletk/COMP380-Spring-2018 | train | 0 |
bc10e9eacb2d563140cf7f234e651f8f373a9352 | [
"email = self.cleaned_data['email']\nself.users_cache = User.objects.filter(email__iexact=email, is_active=True)\nif not len(self.users_cache):\n raise forms.ValidationError(self.error_messages['unknown'])\nif any((user.password == UNUSABLE_PASSWORD for user in self.users_cache)):\n raise forms.ValidationErro... | <|body_start_0|>
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise forms.ValidationError(self.error_messages['unknown'])
if any((user.password == UNUSABLE_PASSWORD for user in sel... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g... | stack_v2_sparse_classes_10k_train_007426 | 11,762 | no_license | [
{
"docstring": "Validates that an active user exists with the given email address.",
"name": "clean_email",
"signature": "def clean_email(self)"
},
{
"docstring": "Generates a one-use only link for resetting password and sends to the user.",
"name": "save",
"signature": "def save(self, p... | 2 | stack_v2_sparse_classes_30k_train_002663 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, project, subject_template_name='password_reset_subjec... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def clean_email(self): Validates that an active user exists with the given email address.
- def save(self, project, subject_template_name='password_reset_subjec... | 5633b8c777ffa04e3372c7c5af4a86f672724d71 | <|skeleton|>
class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
<|body_0|>
def save(self, project, subject_template_name='password_reset_subject.txt', email_template_name='password_reset_email.html', use_https=False, token_g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def clean_email(self):
"""Validates that an active user exists with the given email address."""
email = self.cleaned_data['email']
self.users_cache = User.objects.filter(email__iexact=email, is_active=True)
if not len(self.users_cache):
raise form... | the_stack_v2_python_sparse | invites/forms.py | fabiosussetto/holiday | train | 1 | |
4fded86a013927c0c8dc12cd2d6ed17a66037a6d | [
"self.error = gtol\nif weight != None:\n self.weight = weight\nelse:\n self.weight = 1",
"gradient = state['function'].gradient(state['new_parameters'])\nvalue = (self.weight * numpy.abs(gradient) < self.error).all()\nif value:\n state['istop'] = defaults.SMALL_DF\nreturn value"
] | <|body_start_0|>
self.error = gtol
if weight != None:
self.weight = weight
else:
self.weight = 1
<|end_body_0|>
<|body_start_1|>
gradient = state['function'].gradient(state['new_parameters'])
value = (self.weight * numpy.abs(gradient) < self.error).all()
... | The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance | GradientCriterion | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
... | stack_v2_sparse_classes_10k_train_007427 | 4,758 | permissive | [
{
"docstring": "Initializes the criterion with an error fraction and the weight assigned for each parameter",
"name": "__init__",
"signature": "def __init__(self, gtol, weight=None)"
},
{
"docstring": "Computes the stopping criterion",
"name": "__call__",
"signature": "def __call__(self,... | 2 | stack_v2_sparse_classes_30k_train_005247 | Implement the Python class `GradientCriterion` described below.
Class description:
The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance
Method signatures and docstrings:
- def __init__(self, gtol, weight=None): Initializes the criterion with an error frac... | Implement the Python class `GradientCriterion` described below.
Class description:
The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance
Method signatures and docstrings:
- def __init__(self, gtol, weight=None): Initializes the criterion with an error frac... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GradientCriterion:
"""The gradient criterion stops the optimization when the gradient at the current point is less that a given tolerance"""
def __init__(self, gtol, weight=None):
"""Initializes the criterion with an error fraction and the weight assigned for each parameter"""
self.error ... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/criterion/criteria.py | mdlama/pydstool | train | 2 |
27804157bd4866469b89c0294fee607aa4b4d174 | [
"polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]\nfeat = Segmentation()\nencoded, parsed = encode_decode(feat=feat, poly_or_rle=polygons, mask_shape=(200, 200))\nassert encoded.keys() == feat.encoded_features.keys()\nparsed = parsed[... | <|body_start_0|>
polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]
feat = Segmentation()
encoded, parsed = encode_decode(feat=feat, poly_or_rle=polygons, mask_shape=(200, 200))
assert encoded.keys() == feat.... | TestSegmentationFeature | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
<|body_0|>
def test_encode_decode_rle(self):
"""Test Segmentation feature in run-length-encode format"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_10k_train_007428 | 8,391 | no_license | [
{
"docstring": "Test Segmentation feature in polygon format",
"name": "test_encode_decode_polygon",
"signature": "def test_encode_decode_polygon(self)"
},
{
"docstring": "Test Segmentation feature in run-length-encode format",
"name": "test_encode_decode_rle",
"signature": "def test_enco... | 2 | stack_v2_sparse_classes_30k_train_002264 | Implement the Python class `TestSegmentationFeature` described below.
Class description:
Implement the TestSegmentationFeature class.
Method signatures and docstrings:
- def test_encode_decode_polygon(self): Test Segmentation feature in polygon format
- def test_encode_decode_rle(self): Test Segmentation feature in r... | Implement the Python class `TestSegmentationFeature` described below.
Class description:
Implement the TestSegmentationFeature class.
Method signatures and docstrings:
- def test_encode_decode_polygon(self): Test Segmentation feature in polygon format
- def test_encode_decode_rle(self): Test Segmentation feature in r... | 5da5317cedd380c244f20a96213e883d6ef29de2 | <|skeleton|>
class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
<|body_0|>
def test_encode_decode_rle(self):
"""Test Segmentation feature in run-length-encode format"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSegmentationFeature:
def test_encode_decode_polygon(self):
"""Test Segmentation feature in polygon format"""
polygons = [PolyGon(pts=[(50, 40), (152, 34), (103, 90), (40, 60)], cls_idx=1), PolyGon(pts=[(0, 0), (10, 5), (4, 8)], cls_idx=2)]
feat = Segmentation()
encoded, par... | the_stack_v2_python_sparse | Database/_unittests/test_features.py | MingRuey/mlbox | train | 2 | |
2a344cde064c4f6dc55cc8913569fddb19537382 | [
"self.color = color\nif fill is None:\n fill = color\nself.fill = fill\nself.length = length\nif width is None:\n width = length / 2\nself.width = width\nself.rotation = rotation",
"table_str = f'Ball2dTable:{self.color}'\ntable_str += f' length:{self.length} x {self.width} ft'\nreturn table_str"
] | <|body_start_0|>
self.color = color
if fill is None:
fill = color
self.fill = fill
self.length = length
if width is None:
width = length / 2
self.width = width
self.rotation = rotation
<|end_body_0|>
<|body_start_1|>
table_str = f'... | Ball2dTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length... | stack_v2_sparse_classes_10k_train_007429 | 1,423 | no_license | [
{
"docstring": "Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length/2 :rotation: length orientation in degrees default: No rotation",
"name": "__init__",
"signature":... | 2 | null | Implement the Python class `Ball2dTable` described below.
Class description:
Implement the Ball2dTable class.
Method signatures and docstrings:
- def __init__(self, color='green', fill=None, length=9, width=None, rotation=None): Define/Setup Tables's attributes :color: table's color default: green :fill: table fill c... | Implement the Python class `Ball2dTable` described below.
Class description:
Implement the Ball2dTable class.
Method signatures and docstrings:
- def __init__(self, color='green', fill=None, length=9, width=None, rotation=None): Define/Setup Tables's attributes :color: table's color default: green :fill: table fill c... | bedc16eb5f6db0ad3b313355df6d51b5161c3835 | <|skeleton|>
class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Ball2dTable:
def __init__(self, color='green', fill=None, length=9, width=None, rotation=None):
"""Define/Setup Tables's attributes :color: table's color default: green :fill: table fill color default: same as color :length: length in feet default: 9 :width: width in feet default: length/2 :rotation: ... | the_stack_v2_python_sparse | exercises/classes/ball_classes/ball_2d_table.py | raysmith619/Introduction-To-Programming | train | 3 | |
e0880581d64c978acf267852b35dd723a4c6b0f3 | [
"super().__init__()\nself.session = requests.Session()\nlogin_page = self.session.get('https://ers.cr.usgs.gov/login/')\nhtml_root = html.fromstring(login_page.content)\ncsrf, = html_root.xpath('//*[@id=\"csrf_token\"]')\nncforminfo, = html_root.xpath('//*[@id=\"loginForm\"]/input[2]')\ncsrf_token = csrf.get('value... | <|body_start_0|>
super().__init__()
self.session = requests.Session()
login_page = self.session.get('https://ers.cr.usgs.gov/login/')
html_root = html.fromstring(login_page.content)
csrf, = html_root.xpath('//*[@id="csrf_token"]')
ncforminfo, = html_root.xpath('//*[@id="l... | USGSCrawler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class USGSCrawler:
def __init__(self):
"""login is required to download files from USGS. we are simulating a login with session here"""
<|body_0|>
def crawl(self, target_date: date) -> Optional[str]:
"""this func will download a single file :param target_date: date :return... | stack_v2_sparse_classes_10k_train_007430 | 3,922 | no_license | [
{
"docstring": "login is required to download files from USGS. we are simulating a login with session here",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "this func will download a single file :param target_date: date :return: full-path of downloaded file. None if not ... | 2 | stack_v2_sparse_classes_30k_train_000522 | Implement the Python class `USGSCrawler` described below.
Class description:
Implement the USGSCrawler class.
Method signatures and docstrings:
- def __init__(self): login is required to download files from USGS. we are simulating a login with session here
- def crawl(self, target_date: date) -> Optional[str]: this f... | Implement the Python class `USGSCrawler` described below.
Class description:
Implement the USGSCrawler class.
Method signatures and docstrings:
- def __init__(self): login is required to download files from USGS. we are simulating a login with session here
- def crawl(self, target_date: date) -> Optional[str]: this f... | 9d0dc17e0e5a60fc0507475cd5ef0975beb8b397 | <|skeleton|>
class USGSCrawler:
def __init__(self):
"""login is required to download files from USGS. we are simulating a login with session here"""
<|body_0|>
def crawl(self, target_date: date) -> Optional[str]:
"""this func will download a single file :param target_date: date :return... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class USGSCrawler:
def __init__(self):
"""login is required to download files from USGS. we are simulating a login with session here"""
super().__init__()
self.session = requests.Session()
login_page = self.session.get('https://ers.cr.usgs.gov/login/')
html_root = html.fromst... | the_stack_v2_python_sparse | backend/data_preparation/crawler/usgs_crawler.py | totemprotocol/Wildfires | train | 0 | |
58483fd26ded2eef48506baf01f41c8d30f8086e | [
"if not 0 <= dim_mask <= rbf_hparam['num_feat_per_dim'] // 2:\n raise pyrado.ValueErr(given=dim_mask, ge_constraint='0', le_constraint=f\"{rbf_hparam['num_feat_per_dim'] // 2}\")\nself._feats = RBFFeat(**rbf_hparam)\nsuper().__init__(spec, FeatureStack([self._feats]), init_param_kwargs, use_cuda)\nif not self._n... | <|body_start_0|>
if not 0 <= dim_mask <= rbf_hparam['num_feat_per_dim'] // 2:
raise pyrado.ValueErr(given=dim_mask, ge_constraint='0', le_constraint=f"{rbf_hparam['num_feat_per_dim'] // 2}")
self._feats = RBFFeat(**rbf_hparam)
super().__init__(spec, FeatureStack([self._feats]), init_... | A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we reduce the number of parameters, while... | DualRBFLinearPolicy | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_10k_train_007431 | 25,612 | permissive | [
{
"docstring": "Constructor :param spec: specification of environment :param rbf_hparam: hyper-parameters for the RBF-features, see `RBFFeat` :param dim_mask: number of RBF features to mask out at the beginning and the end of every dimension, pass 1 to remove the first and the last features for the policy, pass... | 2 | null | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | Implement the Python class `DualRBFLinearPolicy` described below.
Class description:
A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a ro... | a6c982862e2ab39a9f65d1c09aa59d9a8b7ac6c5 | <|skeleton|>
class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DualRBFLinearPolicy:
"""A linear policy with RBF features which are also used to get the derivative of the features. The use-case in mind is a simple policy which generates the joint position and joint velocity commands for the internal PD-controller of a robot (e.g. Barrett WAM). By re-using the RBF, we redu... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/environment_specific.py | jacarvalho/SimuRLacra | train | 0 |
31fd7437f52594e6d0b30a81e980c4c7fd6bf603 | [
"track_event = TrackEvent.create(**attr)\nif track_event is None:\n raise BusinessError('创建失败')\nreturn True",
"track_event_qs = TrackEvent.query(**search_info)\ntrack_event_qs.order_by('-create_time')\nreturn Splitor(current_page, track_event_qs)",
"track_event_qs = TrackEvent.search(create_time__range=(sal... | <|body_start_0|>
track_event = TrackEvent.create(**attr)
if track_event is None:
raise BusinessError('创建失败')
return True
<|end_body_0|>
<|body_start_1|>
track_event_qs = TrackEvent.query(**search_info)
track_event_qs.order_by('-create_time')
return Splitor(cu... | TrackEventServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrackEventServer:
def generate(cls, **attr):
"""创建跟踪"""
<|body_0|>
def search(cls, current_page, **search_info):
"""查询跟踪列表"""
<|body_1|>
def search_by_sale_chance(cls, sale_chance):
"""根据机会查询跟踪列表"""
<|body_2|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_007432 | 1,190 | no_license | [
{
"docstring": "创建跟踪",
"name": "generate",
"signature": "def generate(cls, **attr)"
},
{
"docstring": "查询跟踪列表",
"name": "search",
"signature": "def search(cls, current_page, **search_info)"
},
{
"docstring": "根据机会查询跟踪列表",
"name": "search_by_sale_chance",
"signature": "def... | 3 | null | Implement the Python class `TrackEventServer` described below.
Class description:
Implement the TrackEventServer class.
Method signatures and docstrings:
- def generate(cls, **attr): 创建跟踪
- def search(cls, current_page, **search_info): 查询跟踪列表
- def search_by_sale_chance(cls, sale_chance): 根据机会查询跟踪列表 | Implement the Python class `TrackEventServer` described below.
Class description:
Implement the TrackEventServer class.
Method signatures and docstrings:
- def generate(cls, **attr): 创建跟踪
- def search(cls, current_page, **search_info): 查询跟踪列表
- def search_by_sale_chance(cls, sale_chance): 根据机会查询跟踪列表
<|skeleton|>
cla... | f572830aa996cfe619fc4dd8279972a2f567c94c | <|skeleton|>
class TrackEventServer:
def generate(cls, **attr):
"""创建跟踪"""
<|body_0|>
def search(cls, current_page, **search_info):
"""查询跟踪列表"""
<|body_1|>
def search_by_sale_chance(cls, sale_chance):
"""根据机会查询跟踪列表"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TrackEventServer:
def generate(cls, **attr):
"""创建跟踪"""
track_event = TrackEvent.create(**attr)
if track_event is None:
raise BusinessError('创建失败')
return True
def search(cls, current_page, **search_info):
"""查询跟踪列表"""
track_event_qs = TrackEven... | the_stack_v2_python_sparse | codes/personal_backend/tuoen/abs/service/track/manager.py | MaseraTiGo/4U | train | 0 | |
eec162e62d7481b26c41010b187e808c90d05ed2 | [
"if not n:\n return n\nprv_1, prv_2 = (1, 0)\nfor i in range(n):\n prv_1, prv_2 = (prv_1 + prv_2, prv_1)\nreturn prv_1",
"if n < 3:\n return n\nreturn self.climbStairs(n - 2) + self.climbStairs(n - 1)"
] | <|body_start_0|>
if not n:
return n
prv_1, prv_2 = (1, 0)
for i in range(n):
prv_1, prv_2 = (prv_1 + prv_2, prv_1)
return prv_1
<|end_body_0|>
<|body_start_1|>
if n < 3:
return n
return self.climbStairs(n - 2) + self.climbStairs(n - 1)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not n:
return n
prv_1, prv_2 = (1, 0)
... | stack_v2_sparse_classes_10k_train_007433 | 547 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs",
"signature": "def climbStairs(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "climbStairs2",
"signature": "def climbStairs2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005606 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs2(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def climbStairs(self, n): :type n: int :rtype: int
- def climbStairs2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def climbStairs(self, n):
""":... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def climbStairs2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def climbStairs(self, n):
""":type n: int :rtype: int"""
if not n:
return n
prv_1, prv_2 = (1, 0)
for i in range(n):
prv_1, prv_2 = (prv_1 + prv_2, prv_1)
return prv_1
def climbStairs2(self, n):
""":type n: int :rtype: int"... | the_stack_v2_python_sparse | cs_notes/dynamic_programming/climbing_stairs.py | hwc1824/LeetCodeSolution | train | 0 | |
8eee21d964f3eb2247c9a01ec7ee5685ad6fa52b | [
"events = []\nstack_traces = []\nwhile self.stack_trace_re.match(line):\n event = self.parse_stack_trace_line(line)\n if event:\n events.append(event)\n stack_traces.append(line)\n line = get_next(it)\nevents.reverse()\nreturn (stack_traces, events, line)",
"match = self.line_re.match(line)\nif... | <|body_start_0|>
events = []
stack_traces = []
while self.stack_trace_re.match(line):
event = self.parse_stack_trace_line(line)
if event:
events.append(event)
stack_traces.append(line)
line = get_next(it)
events.reverse()
... | Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7... | Parser | [
"LLVM-exception",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
<|body_0|>
def parse_sanitizer_messag... | stack_v2_sparse_classes_10k_train_007434 | 7,773 | permissive | [
{
"docstring": "Iterate over lines and parse stack traces.",
"name": "parse_stack_trace",
"signature": "def parse_stack_trace(self, it, line)"
},
{
"docstring": "Parses UndefinedBehaviorSanitizer output message.",
"name": "parse_sanitizer_message",
"signature": "def parse_sanitizer_messa... | 2 | stack_v2_sparse_classes_30k_train_002445 | Implement the Python class `Parser` described below.
Class description:
Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7...
Method signatures and docstrings:
- def parse_stack_trace(self, it, line): Iterate over lines and parse stack trac... | Implement the Python class `Parser` described below.
Class description:
Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7...
Method signatures and docstrings:
- def parse_stack_trace(self, it, line): Iterate over lines and parse stack trac... | f912cf0ccc7059240ae389823faf35225e6cabc8 | <|skeleton|>
class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
<|body_0|>
def parse_sanitizer_messag... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
events = []
stack_traces = []
while sel... | the_stack_v2_python_sparse | tools/report-converter/codechecker_report_converter/analyzers/sanitizers/ub/parser.py | Ericsson/codechecker | train | 2,028 |
6949bdf6ca55ebad1ea60dd73eef4c0d4fb4b958 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ImportedWindowsAutopilotDeviceIdentity()",
"from .entity import Entity\nfrom .imported_windows_autopilot_device_identity_state import ImportedWindowsAutopilotDeviceIdentityState\nfrom .entity import Entity\nfrom .imported_windows_autop... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ImportedWindowsAutopilotDeviceIdentity()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .imported_windows_autopilot_device_identity_state import ImportedWindowsAutopilot... | Imported windows autopilot devices. | ImportedWindowsAutopilotDeviceIdentity | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImportedWindowsAutopilotDeviceIdentity:
"""Imported windows autopilot devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity:
"""Creates a new instance of the appropriate class based on discriminator value Args:... | stack_v2_sparse_classes_10k_train_007435 | 4,071 | 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: ImportedWindowsAutopilotDeviceIdentity",
"name": "create_from_discriminator_value",
"signature": "def create... | 3 | stack_v2_sparse_classes_30k_train_002315 | Implement the Python class `ImportedWindowsAutopilotDeviceIdentity` described below.
Class description:
Imported windows autopilot devices.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: Creates a new instance of... | Implement the Python class `ImportedWindowsAutopilotDeviceIdentity` described below.
Class description:
Imported windows autopilot devices.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ImportedWindowsAutopilotDeviceIdentity:
"""Imported windows autopilot devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity:
"""Creates a new instance of the appropriate class based on discriminator value Args:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImportedWindowsAutopilotDeviceIdentity:
"""Imported windows autopilot devices."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ImportedWindowsAutopilotDeviceIdentity:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: ... | the_stack_v2_python_sparse | msgraph/generated/models/imported_windows_autopilot_device_identity.py | microsoftgraph/msgraph-sdk-python | train | 135 |
eeb4c56bcccdc2601c29e1a4e22008a0350c0952 | [
"if cls is cxx:\n if sys.platform == 'win32':\n from .msvc import msvc\n msvc.instances(fs)\nreturn super(cxx, cls).instances(fs)",
"fs = set.instantiate(fs)\nif cls is cxx and (not cxx.instantiated(fs)):\n logger.info('trying to instantiate a default C++ compiler')\n if sys.platform == 'wi... | <|body_start_0|>
if cls is cxx:
if sys.platform == 'win32':
from .msvc import msvc
msvc.instances(fs)
return super(cxx, cls).instances(fs)
<|end_body_0|>
<|body_start_1|>
fs = set.instantiate(fs)
if cls is cxx and (not cxx.instantiated(fs)):
... | C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to build). | cxx | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to buil... | stack_v2_sparse_classes_10k_train_007436 | 2,259 | permissive | [
{
"docstring": "Return all known C++ compiler instances for the current platform.",
"name": "instances",
"signature": "def instances(cls, fs=None)"
},
{
"docstring": "Try to find a compiler instance for the current platform.",
"name": "instance",
"signature": "def instance(cls, fs=None)"... | 2 | stack_v2_sparse_classes_30k_train_004989 | Implement the Python class `cxx` described below.
Class description:
C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler ... | Implement the Python class `cxx` described below.
Class description:
C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler ... | 0f369a8a9e4de305e5379d9662b2e79bffd43910 | <|skeleton|>
class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to buil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class cxx:
"""C++ compiler base-class. As an abstract base-class it declares the actions all subclasses need to provide, without implementing them. Build scripts thus can reference `cxx.compile` et al., which the runtime will substitute by an appropriate compiler instance, if available (or fail to build)."""
d... | the_stack_v2_python_sparse | src/faber/tools/cxx.py | stefanseefeld/faber | train | 15 |
840e7b9ec9da1bfb6e1ea03702b21c13e531bb2e | [
"layout = self.layout\ncolumn = layout.column()\ncolumn.label(text=self.target + ':')\nModifierButtons.main(ModifierButtons, context, layout, bpy.data.objects[self.object].modifiers[self.target], bpy.data.objects[self.object])",
"if self.properties:\n for area in context.screen.areas:\n if area.type in ... | <|body_start_0|>
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
ModifierButtons.main(ModifierButtons, context, layout, bpy.data.objects[self.object].modifiers[self.target], bpy.data.objects[self.object])
<|end_body_0|>
<|body_start_1|>
if self... | This is operator is used to create the required pop-up panel. | modifier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class modifier:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the modifier options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event):
... | stack_v2_sparse_classes_10k_train_007437 | 17,024 | no_license | [
{
"docstring": "Draw the modifier options.",
"name": "draw",
"signature": "def draw(self, context)"
},
{
"docstring": "Execute the operator.",
"name": "execute",
"signature": "def execute(self, context)"
},
{
"docstring": "Invoke the operator panel/menu, control its width.",
... | 3 | stack_v2_sparse_classes_30k_train_004864 | Implement the Python class `modifier` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the modifier options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): Invoke... | Implement the Python class `modifier` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the modifier options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): Invoke... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class modifier:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the modifier options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class modifier:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the modifier options."""
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
ModifierButtons.main(ModifierButtons, context,... | the_stack_v2_python_sparse | All_In_One/addons/name_panel/scripts/operator/icon.py | 2434325680/Learnbgame | train | 0 |
05e9fc04cecf5935ddee67bc03ec1cb03d36d5b2 | [
"helpers.abort_if_invalid_parameters(pid, sid)\nproject = Project.query.get(pid)\nannotations = UserAnnotationModel.query.filter_by(session_id=sid).all()\nannotations = UserAnnotationSchema(many=True).dump(annotations)\nif project.is_public:\n return custom_response(200, data=annotations)\nhelpers.abort_if_unaut... | <|body_start_0|>
helpers.abort_if_invalid_parameters(pid, sid)
project = Project.query.get(pid)
annotations = UserAnnotationModel.query.filter_by(session_id=sid).all()
annotations = UserAnnotationSchema(many=True).dump(annotations)
if project.is_public:
return custom_... | Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/ | UserAnnotations | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
<|body_0|>
def post(self, pid, sid):
"""Create a new annotation on an existing se... | stack_v2_sparse_classes_10k_train_007438 | 3,199 | no_license | [
{
"docstring": "Returns a list of all annotations for an existing session",
"name": "get",
"signature": "def get(self, pid, sid)"
},
{
"docstring": "Create a new annotation on an existing session",
"name": "post",
"signature": "def post(self, pid, sid)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000326 | Implement the Python class `UserAnnotations` described below.
Class description:
Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/
Method signatures and docstrings:
- def get(self, pid, sid): Returns a list of all annotations for an existing session
- def post(self, pid, sid): Create a new annotat... | Implement the Python class `UserAnnotations` described below.
Class description:
Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/
Method signatures and docstrings:
- def get(self, pid, sid): Returns a list of all annotations for an existing session
- def post(self, pid, sid): Create a new annotat... | 716fa5a6e905380cb206c57868e87556805f2b7f | <|skeleton|>
class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
<|body_0|>
def post(self, pid, sid):
"""Create a new annotation on an existing se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserAnnotations:
"""Mapped to: /api/projects/<int:pid>/sessions/<string:sid>/annotations/"""
def get(self, pid, sid):
"""Returns a list of all annotations for an existing session"""
helpers.abort_if_invalid_parameters(pid, sid)
project = Project.query.get(pid)
annotations ... | the_stack_v2_python_sparse | gabber/api/annotations.py | joseplj/GabberAPI | train | 0 |
a8241398debc19315baae079557560fd4e858535 | [
"self.rules.add(rule_name)\nfor member in members:\n if member.id not in self.members:\n self.members[member.id] = member\nfor message in messages:\n if message.id not in self.messages:\n self.messages[message.id] = message\n destination = message.guild.get_channel(Channels.attachment_log... | <|body_start_0|>
self.rules.add(rule_name)
for member in members:
if member.id not in self.members:
self.members[member.id] = member
for message in messages:
if message.id not in self.messages:
self.messages[message.id] = message
... | Represents a Deletion Context for a single spam event. | DeletionContext | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeletionContext:
"""Represents a Deletion Context for a single spam event."""
async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None:
"""Adds new rule violation events to the deletion context."""
<|body_0|>
async def upload_me... | stack_v2_sparse_classes_10k_train_007439 | 12,281 | permissive | [
{
"docstring": "Adds new rule violation events to the deletion context.",
"name": "add",
"signature": "async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None"
},
{
"docstring": "Method that takes care of uploading the queue and posting modlog alert.",... | 2 | stack_v2_sparse_classes_30k_train_004599 | Implement the Python class `DeletionContext` described below.
Class description:
Represents a Deletion Context for a single spam event.
Method signatures and docstrings:
- async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None: Adds new rule violation events to the deletio... | Implement the Python class `DeletionContext` described below.
Class description:
Represents a Deletion Context for a single spam event.
Method signatures and docstrings:
- async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None: Adds new rule violation events to the deletio... | 232cc68b0a0ef210027beacb9b4f50ffeeaddd00 | <|skeleton|>
class DeletionContext:
"""Represents a Deletion Context for a single spam event."""
async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None:
"""Adds new rule violation events to the deletion context."""
<|body_0|>
async def upload_me... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeletionContext:
"""Represents a Deletion Context for a single spam event."""
async def add(self, rule_name: str, members: Iterable[Member], messages: Iterable[Message]) -> None:
"""Adds new rule violation events to the deletion context."""
self.rules.add(rule_name)
for member in ... | the_stack_v2_python_sparse | bot/cogs/antispam.py | pormes/bot | train | 2 |
7452dc58b3c7e74971d3e42b8cc42295beefec10 | [
"self.app_env = app_env\nself.error = error\nself.finished = finished\nself.target_entity = target_entity\nself.target_entity_credentials = target_entity_credentials",
"if dictionary is None:\n return None\napp_env = dictionary.get('appEnv')\nerror = cohesity_management_sdk.models.error_proto.ErrorProto.from_d... | <|body_start_0|>
self.app_env = app_env
self.error = error
self.finished = finished
self.target_entity = target_entity
self.target_entity_credentials = target_entity_credentials
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
app_en... | Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto extension Location Extension =================================================================... | DestroyCloneAppTaskInfoProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DestroyCloneAppTaskInfoProto:
"""Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto extension Location Extension =========... | stack_v2_sparse_classes_10k_train_007440 | 3,721 | permissive | [
{
"docstring": "Constructor for the DestroyCloneAppTaskInfoProto class",
"name": "__init__",
"signature": "def __init__(self, app_env=None, error=None, finished=None, target_entity=None, target_entity_credentials=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args:... | 2 | null | Implement the Python class `DestroyCloneAppTaskInfoProto` described below.
Class description:
Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto... | Implement the Python class `DestroyCloneAppTaskInfoProto` described below.
Class description:
Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DestroyCloneAppTaskInfoProto:
"""Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto extension Location Extension =========... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DestroyCloneAppTaskInfoProto:
"""Implementation of the 'DestroyCloneAppTaskInfoProto' model. Each available extension is listed below along with the location of the proto file (relative to magneto/connectors) where it is defined. DestroyCloneAppTaskInfoProto extension Location Extension ======================... | the_stack_v2_python_sparse | cohesity_management_sdk/models/destroy_clone_app_task_info_proto.py | cohesity/management-sdk-python | train | 24 |
b341a80d0b98d20bd612ab580d168513811c5f8f | [
"attr_d = source.AttrDict(zip('aeiou', range(1, 6)))\nattr_d.a = 0\nself.assertTrue('a' not in attr_d.__dict__, 'Wrong attribute assignment in AttrDict')\nself.assertEqual(attr_d['a'], 0, 'Wrong attribute assignment in AttrDict')\nself.assertEqual(attr_d.a, 0, 'Wrong attribute assignment in AttrDict')",
"attr_d =... | <|body_start_0|>
attr_d = source.AttrDict(zip('aeiou', range(1, 6)))
attr_d.a = 0
self.assertTrue('a' not in attr_d.__dict__, 'Wrong attribute assignment in AttrDict')
self.assertEqual(attr_d['a'], 0, 'Wrong attribute assignment in AttrDict')
self.assertEqual(attr_d.a, 0, 'Wrong ... | Test exercise mod 06 AttrDict | TestAttrDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAttrDict:
"""Test exercise mod 06 AttrDict"""
def test_setattr_existent(self):
"""Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists"""
<|body_0|>
def test_setattr_new(self):
"""Check __setattr__ customization of At... | stack_v2_sparse_classes_10k_train_007441 | 8,327 | no_license | [
{
"docstring": "Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists",
"name": "test_setattr_existent",
"signature": "def test_setattr_existent(self)"
},
{
"docstring": "Check __setattr__ customization of AttrDict. It must update a dictionary key only if... | 4 | stack_v2_sparse_classes_30k_train_006876 | Implement the Python class `TestAttrDict` described below.
Class description:
Test exercise mod 06 AttrDict
Method signatures and docstrings:
- def test_setattr_existent(self): Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists
- def test_setattr_new(self): Check __setattr_... | Implement the Python class `TestAttrDict` described below.
Class description:
Test exercise mod 06 AttrDict
Method signatures and docstrings:
- def test_setattr_existent(self): Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists
- def test_setattr_new(self): Check __setattr_... | 8f082201e24f0f2b991d9388500fdbf95d6f073d | <|skeleton|>
class TestAttrDict:
"""Test exercise mod 06 AttrDict"""
def test_setattr_existent(self):
"""Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists"""
<|body_0|>
def test_setattr_new(self):
"""Check __setattr__ customization of At... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestAttrDict:
"""Test exercise mod 06 AttrDict"""
def test_setattr_existent(self):
"""Check __setattr__ customization of AttrDict. It must update a dictionary key only if it exists"""
attr_d = source.AttrDict(zip('aeiou', range(1, 6)))
attr_d.a = 0
self.assertTrue('a' not ... | the_stack_v2_python_sparse | intermediate/exercises/mod_04_data_model/tests_mod_04.py | garciacastano09/pycourse | train | 0 |
f30002293ee00204ae238b21a688fe15c48ed755 | [
"try:\n num = float(data[0])\nexcept ValueError as verr:\n print(verr)\n num = -1.0\nif len(data) > 1:\n unit = data[1]\n metric += '_' + str(unit)\nreturn (metric, num)",
"line = line.split(':')\nmetric = line[0].strip()\ndata = line[1].strip()\nurl_pattern = re.compile(ALPHANUMERIC_URL_REGEX)\nif... | <|body_start_0|>
try:
num = float(data[0])
except ValueError as verr:
print(verr)
num = -1.0
if len(data) > 1:
unit = data[1]
metric += '_' + str(unit)
return (metric, num)
<|end_body_0|>
<|body_start_1|>
line = line.sp... | Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DONE WARNING: Got 39 HTTP codes differ... | DjangoWorkloadParser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_10k_train_007442 | 4,783 | permissive | [
{
"docstring": "Helper method to handle errors when extracting metrics and values",
"name": "parse_dw_data",
"signature": "def parse_dw_data(self, data, metric)"
},
{
"docstring": "Helper method to parse django-workload output into key-value data structure",
"name": "parse_dw_key_val",
"... | 3 | stack_v2_sparse_classes_30k_train_006908 | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | Implement the Python class `DjangoWorkloadParser` described below.
Class description:
Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege... | 70bc9fcb8dcc02c4ee70675c965c746fad7e4165 | <|skeleton|>
class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iterat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DjangoWorkloadParser:
"""Example output: Running iteration 1 --- DONE WARNING: Got 12 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_1 Running iteration 2 --- DONE WARNING: Got 15 HTTP codes different than 200 Please see full Siege log in /tmp/siege_out_2 Running iteration 3 --- DON... | the_stack_v2_python_sparse | benchpress/benchpress/plugins/parsers/django_workload.py | meteorfox/fbkutils | train | 1 |
245e26466fbd216eda585cfef1abd3c865c92162 | [
"super(ValueChange, self).__init__(env, realign_fn)\nself.state_var = state_var\nself.normalize_by_steps = normalize_by_steps",
"history = self._extract_history(env)\ninitial_state = history[0].state\nfinal_state = history[-1].state\ndelta = getattr(final_state, self.state_var) - getattr(initial_state, self.state... | <|body_start_0|>
super(ValueChange, self).__init__(env, realign_fn)
self.state_var = state_var
self.normalize_by_steps = normalize_by_steps
<|end_body_0|>
<|body_start_1|>
history = self._extract_history(env)
initial_state = history[0].state
final_state = history[-1].sta... | Metric that returns how much a value has changed over the experiment. | ValueChange | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_10k_train_007443 | 7,087 | permissive | [
{
"docstring": "Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. normalize_by_steps: Whether to divide by number of steps to get an average change. realign_fn: Optional. If not None, defines how to realign history for use by a metric.",
... | 2 | stack_v2_sparse_classes_30k_train_005426 | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | Implement the Python class `ValueChange` described below.
Class description:
Metric that returns how much a value has changed over the experiment.
Method signatures and docstrings:
- def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None): Initializes the ValueChange metric. Args: env: A `core.Fa... | 38eaf4514062892e0c3ce5d7cff4b4c1a7e49242 | <|skeleton|>
class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValueChange:
"""Metric that returns how much a value has changed over the experiment."""
def __init__(self, env, state_var, normalize_by_steps=True, realign_fn=None):
"""Initializes the ValueChange metric. Args: env: A `core.FairnessEnv`. state_var: string name of a state variable to track. norma... | the_stack_v2_python_sparse | metrics/value_tracking_metrics.py | google/ml-fairness-gym | train | 310 |
0132dc083eb758960dcacd643c9800d0a004ba22 | [
"residual = cls.conv_bn(input_x, filters, **conv_params)\nresidual = cls.activation(residual)\nmix_residuals = list()\nmix_kernel_nums = filters * cls.MIX_KERNEL_RATIO\nmix_kernel_nums = mix_kernel_nums.astype(np.int)\nfor i, kernel_size in enumerate(cls.MIX_KERNEL_SIZES):\n mix_residual = keras.layers.Lambda(la... | <|body_start_0|>
residual = cls.conv_bn(input_x, filters, **conv_params)
residual = cls.activation(residual)
mix_residuals = list()
mix_kernel_nums = filters * cls.MIX_KERNEL_RATIO
mix_kernel_nums = mix_kernel_nums.astype(np.int)
for i, kernel_size in enumerate(cls.MIX_KE... | MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了 | MixNet18 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MixNet18:
"""MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了"""
def _mix_residual_block(cls, input_x, filters, is_nin=True, **conv_params):
"""一个残差模块里的 block input-> conv+bn->relu-> conv+bn-> add->relu-> |-----> conv(1 X 1)+bn... | stack_v2_sparse_classes_10k_train_007444 | 3,734 | permissive | [
{
"docstring": "一个残差模块里的 block input-> conv+bn->relu-> conv+bn-> add->relu-> |-----> conv(1 X 1)+bn ------>| :param input_x: 残差block的输入 :param filters: 卷积核数,残差运算后的channel数 :param is_nin: shortcut是否需要进行NIN运算 :param conv_params: 卷积参数,参见 BasicBackbone.convolution :return: 卷积块运算之后的tensor",
"name": "_mix_residua... | 3 | stack_v2_sparse_classes_30k_train_004190 | Implement the Python class `MixNet18` described below.
Class description:
MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了
Method signatures and docstrings:
- def _mix_residual_block(cls, input_x, filters, is_nin=True, **conv_params): 一个残差模块里的 block input-> con... | Implement the Python class `MixNet18` described below.
Class description:
MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了
Method signatures and docstrings:
- def _mix_residual_block(cls, input_x, filters, is_nin=True, **conv_params): 一个残差模块里的 block input-> con... | 8f2d722e4067aef0c8a9cc29f76d958c0f97fb9f | <|skeleton|>
class MixNet18:
"""MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了"""
def _mix_residual_block(cls, input_x, filters, is_nin=True, **conv_params):
"""一个残差模块里的 block input-> conv+bn->relu-> conv+bn-> add->relu-> |-----> conv(1 X 1)+bn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MixNet18:
"""MixNet 18:不是论文中的MixNet的结构 只是借鉴了MixNet的不同kernel size mix到一起的想法,同时也使用depthwise 不使用depthwise的话,就是resnext 18了"""
def _mix_residual_block(cls, input_x, filters, is_nin=True, **conv_params):
"""一个残差模块里的 block input-> conv+bn->relu-> conv+bn-> add->relu-> |-----> conv(1 X 1)+bn ------>| :pa... | the_stack_v2_python_sparse | backbone/mixnet18.py | zheng-yuwei/YOLOv3-tensorflow | train | 5 |
2b985e52be982d5294acdb410ef0087d463c9e4e | [
"sstream = RosettaFunctionConstructs._ATOMPAIR\nsstream += 'BOUNDED {lower_bound: >.3f} {upper_bound: >.3f} 1 0.5 #'\nreturn sstream",
"sstream = RosettaFunctionConstructs._ATOMPAIR\nsstream += RosettaFunctionConstructs._SCALARWEIGHTED\nsstream += 'BOUNDED 0 {lower_bound: >.3f} 1 0.5'\nreturn sstream",
"sstream... | <|body_start_0|>
sstream = RosettaFunctionConstructs._ATOMPAIR
sstream += 'BOUNDED {lower_bound: >.3f} {upper_bound: >.3f} 1 0.5 #'
return sstream
<|end_body_0|>
<|body_start_1|>
sstream = RosettaFunctionConstructs._ATOMPAIR
sstream += RosettaFunctionConstructs._SCALARWEIGHTED
... | Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/rosetta_basics/file_types/constraint-file>`_ | RosettaFunctionConstructs | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/r... | stack_v2_sparse_classes_10k_train_007445 | 4,869 | permissive | [
{
"docstring": "Simple bounded energy function",
"name": "BOUNDED_default",
"signature": "def BOUNDED_default(self)"
},
{
"docstring": "Energy function according to [#]_ References ---------- .. [#] Ovchinnekov et al. (2015). Large-scale determination of previously unsolved protein structures us... | 6 | stack_v2_sparse_classes_30k_train_000060 | Implement the Python class `RosettaFunctionConstructs` described below.
Class description:
Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https... | Implement the Python class `RosettaFunctionConstructs` described below.
Class description:
Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https... | 926f194a660d95350e9172d236c9c002e8a921a3 | <|skeleton|>
class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RosettaFunctionConstructs:
"""Storage for string formats of different Rosetta energy function constructs For more information on the different energy functions, please refer to the corresponding references or the official `RosettaCommons documentation <https://www.rosettacommons.org/docs/latest/rosetta_basics... | the_stack_v2_python_sparse | conkit/misc/energyfunction.py | rigdenlab/conkit | train | 19 |
80b5951479a69718770006f817275fc7c576e8f3 | [
"super(LinearRegression, self).setUp()\ndataset = self.get_file('linear_regression_gen.csv')\nschema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)]\nself.frame = self.context.frame.import_csv(dataset, schema=schema)",
"model = self.context.models.regression.linear_regression.trai... | <|body_start_0|>
super(LinearRegression, self).setUp()
dataset = self.get_file('linear_regression_gen.csv')
schema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)]
self.frame = self.context.frame.import_csv(dataset, schema=schema)
<|end_body_0|>
<|body_st... | LinearRegression | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearRegression:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_model_scoring(self):
"""Test publishing a linear regression model"""
<|body_1|>
def test_revise_model(self):
"""Tests revise api in scoring engine"""
<|body_2|>... | stack_v2_sparse_classes_10k_train_007446 | 3,490 | permissive | [
{
"docstring": "Build test frame",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test publishing a linear regression model",
"name": "test_model_scoring",
"signature": "def test_model_scoring(self)"
},
{
"docstring": "Tests revise api in scoring engine",
... | 3 | null | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_model_scoring(self): Test publishing a linear regression model
- def test_revise_model(self): Tests revise api in sco... | Implement the Python class `LinearRegression` described below.
Class description:
Implement the LinearRegression class.
Method signatures and docstrings:
- def setUp(self): Build test frame
- def test_model_scoring(self): Test publishing a linear regression model
- def test_revise_model(self): Tests revise api in sco... | 5548fc925b5c278263cbdebbd9e8c7593320c2f4 | <|skeleton|>
class LinearRegression:
def setUp(self):
"""Build test frame"""
<|body_0|>
def test_model_scoring(self):
"""Test publishing a linear regression model"""
<|body_1|>
def test_revise_model(self):
"""Tests revise api in scoring engine"""
<|body_2|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearRegression:
def setUp(self):
"""Build test frame"""
super(LinearRegression, self).setUp()
dataset = self.get_file('linear_regression_gen.csv')
schema = [('c1', float), ('c2', float), ('c3', float), ('c4', float), ('label', float)]
self.frame = self.context.frame.i... | the_stack_v2_python_sparse | regression-tests/sparktkregtests/testcases/scoretests/linear_regression_test.py | trustedanalytics/spark-tk | train | 35 | |
4782f5becbace547088b04f348a2229a268ced5f | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ajr10_williami', 'ajr10_williami')\nrepo.dropCollection('ajr10_williami.cleaned_energy_cambridge')\nrepo.createCollection('ajr10_williami.cleaned_energy_cambridge')\nrepo.dropCollection('ajr10_williami.c... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropCollection('ajr10_williami.cleaned_energy_cambridge')
repo.createCollection('ajr10_williami.cleaned_en... | clean_energy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_10k_train_007447 | 5,514 | no_license | [
{
"docstring": "Retrieve some data sets and store in mongodb collections.",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing ... | 2 | stack_v2_sparse_classes_30k_train_004788 | Implement the Python class `clean_energy` described below.
Class description:
Implement the clean_energy class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ... | Implement the Python class `clean_energy` described below.
Class description:
Implement the clean_energy class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets and store in mongodb collections.
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Create ... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happening in this s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class clean_energy:
def execute(trial=False):
"""Retrieve some data sets and store in mongodb collections."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ajr10_williami', 'ajr10_williami')
repo.dropColle... | the_stack_v2_python_sparse | ajr10_williami/clean_energy.py | lingyigu/course-2017-spr-proj | train | 0 | |
d73db0d469c9ef6549e05e9f8e33365764b552e0 | [
"mode = 'r'\nif byte:\n mode += 'b'\ntry:\n with open(src, mode) as file:\n content = file.read()\n file.close()\n return content\nexcept FileNotFoundError:\n return None",
"with open(src, 'w') as file:\n file.write(content)\n file.close()"
] | <|body_start_0|>
mode = 'r'
if byte:
mode += 'b'
try:
with open(src, mode) as file:
content = file.read()
file.close()
return content
except FileNotFoundError:
return None
<|end_body_0|>
<|body_start_1|>... | Class to handle file opening and saving in operating system. | FileRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileRepository:
"""Class to handle file opening and saving in operating system."""
def open_file(self, src, byte=False):
"""open_file handles opening files for importing memos as markdown files and importing images to database. Handles interaction with OS. Args: src: location for fil... | stack_v2_sparse_classes_10k_train_007448 | 1,312 | no_license | [
{
"docstring": "open_file handles opening files for importing memos as markdown files and importing images to database. Handles interaction with OS. Args: src: location for file to be opened byte: optional, used to read images as bytes to be coverted to base64-string. If True, function will add byte indicator i... | 2 | stack_v2_sparse_classes_30k_train_003253 | Implement the Python class `FileRepository` described below.
Class description:
Class to handle file opening and saving in operating system.
Method signatures and docstrings:
- def open_file(self, src, byte=False): open_file handles opening files for importing memos as markdown files and importing images to database.... | Implement the Python class `FileRepository` described below.
Class description:
Class to handle file opening and saving in operating system.
Method signatures and docstrings:
- def open_file(self, src, byte=False): open_file handles opening files for importing memos as markdown files and importing images to database.... | 816990c4432d4e9db0818f6747a9ee482bb9f192 | <|skeleton|>
class FileRepository:
"""Class to handle file opening and saving in operating system."""
def open_file(self, src, byte=False):
"""open_file handles opening files for importing memos as markdown files and importing images to database. Handles interaction with OS. Args: src: location for fil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FileRepository:
"""Class to handle file opening and saving in operating system."""
def open_file(self, src, byte=False):
"""open_file handles opening files for importing memos as markdown files and importing images to database. Handles interaction with OS. Args: src: location for file to be opene... | the_stack_v2_python_sparse | src/repositories/file_repository.py | FinThunderstorm/ohte | train | 0 |
1b0f74feca4f6fe4f71e4405f11880a178f4e31c | [
"query = full_query = self.db.query(orm.Group)\nsub_scope = self.parsed_scopes['list:groups']\nif sub_scope != Scope.ALL:\n if not set(sub_scope).issubset({'group'}):\n self.log.warning(f'Invalid filter on list:group for {self.current_user}: {sub_scope}')\n raise web.HTTPError(403)\n query = que... | <|body_start_0|>
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
self.log.warning(f'Invalid filter on list:group for {self.current_user}: {sub_scope}')
... | GroupListAPIHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List groups"""
<|body_0|>
async def post(self):
"""POST creates Multiple groups"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scop... | stack_v2_sparse_classes_10k_train_007449 | 8,154 | permissive | [
{
"docstring": "List groups",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "POST creates Multiple groups",
"name": "post",
"signature": "async def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005108 | Implement the Python class `GroupListAPIHandler` described below.
Class description:
Implement the GroupListAPIHandler class.
Method signatures and docstrings:
- def get(self): List groups
- async def post(self): POST creates Multiple groups | Implement the Python class `GroupListAPIHandler` described below.
Class description:
Implement the GroupListAPIHandler class.
Method signatures and docstrings:
- def get(self): List groups
- async def post(self): POST creates Multiple groups
<|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List... | 7757dea8a463e75d8a540e85deee45c1635dd273 | <|skeleton|>
class GroupListAPIHandler:
def get(self):
"""List groups"""
<|body_0|>
async def post(self):
"""POST creates Multiple groups"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GroupListAPIHandler:
def get(self):
"""List groups"""
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
self.log.warning(f'Invalid filter ... | the_stack_v2_python_sparse | jupyterhub/apihandlers/groups.py | jupyterhub/jupyterhub | train | 6,751 | |
7c1ca75a4f218e02e1c9b99c1c60a43e56d3f8f6 | [
"difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))\nif wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):\n self.emulator.click_button(self.stage_selector_ui)\n if '_2_' in difficulty_ui.name:\n logger.debug('Difficulty is referring from the bottom o... | <|body_start_0|>
difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))
if wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):
self.emulator.click_button(self.stage_selector_ui)
if '_2_' in difficulty_ui.name:
logger.... | TenStageWithDifficultyEpicQuest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
<|body_0|>
def _select_mission(self):
"""Selects missions in Epic Quest."""
<|body_1|>
def _get_difficulty_ui(self, difficulty):
... | stack_v2_sparse_classes_10k_train_007450 | 26,035 | permissive | [
{
"docstring": "Selects stage in missions in Epic Quest.",
"name": "_select_stage",
"signature": "def _select_stage(self, difficulty=6)"
},
{
"docstring": "Selects missions in Epic Quest.",
"name": "_select_mission",
"signature": "def _select_mission(self)"
},
{
"docstring": "Get... | 5 | stack_v2_sparse_classes_30k_train_006752 | Implement the Python class `TenStageWithDifficultyEpicQuest` described below.
Class description:
Implement the TenStageWithDifficultyEpicQuest class.
Method signatures and docstrings:
- def _select_stage(self, difficulty=6): Selects stage in missions in Epic Quest.
- def _select_mission(self): Selects missions in Epi... | Implement the Python class `TenStageWithDifficultyEpicQuest` described below.
Class description:
Implement the TenStageWithDifficultyEpicQuest class.
Method signatures and docstrings:
- def _select_stage(self, difficulty=6): Selects stage in missions in Epic Quest.
- def _select_mission(self): Selects missions in Epi... | fd3f0bd45aea45e2e8ad8e8fc73a8953c96d350a | <|skeleton|>
class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
<|body_0|>
def _select_mission(self):
"""Selects missions in Epic Quest."""
<|body_1|>
def _get_difficulty_ui(self, difficulty):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TenStageWithDifficultyEpicQuest:
def _select_stage(self, difficulty=6):
"""Selects stage in missions in Epic Quest."""
difficulty_ui = ui.get_by_name(self._get_difficulty_ui(difficulty))
if wait_until(self.emulator.is_ui_element_on_screen, ui_element=self.stage_selector_ui):
... | the_stack_v2_python_sparse | lib/game/missions/epic_quest.py | th3f1v3/mff_auto | train | 0 | |
32c1571a62386f6d4fb490056be5dc4bfd9763d7 | [
"super(MXNetGraphConverter, self).__init__(framework, base_path)\nprint('{} bmodel converter init'.format(model_name))\nself.model_name = model_name\nself.models_path = models_path\nself.weights_path = weights_path\nself.shapes = shapes\nself.dyns = dyns\nself.outdirs = outdirs\nself.nets_name = nets_name\nself.inp... | <|body_start_0|>
super(MXNetGraphConverter, self).__init__(framework, base_path)
print('{} bmodel converter init'.format(model_name))
self.model_name = model_name
self.models_path = models_path
self.weights_path = weights_path
self.shapes = shapes
self.dyns = dyns... | mxnet graph bmodel converter | MXNetGraphConverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
<|body_0|>
def converter(self):
... | stack_v2_sparse_classes_10k_train_007451 | 15,723 | permissive | [
{
"docstring": "Init mxnet graph bmodel converter",
"name": "__init__",
"signature": "def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target)"
},
{
"docstring": "convert mxnet graph",
"name": "converter",
"sig... | 2 | stack_v2_sparse_classes_30k_train_004265 | Implement the Python class `MXNetGraphConverter` described below.
Class description:
mxnet graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target): Init mxnet graph bmodel converte... | Implement the Python class `MXNetGraphConverter` described below.
Class description:
mxnet graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target): Init mxnet graph bmodel converte... | c9fa07851da663dda4953dba72e1d3937299a4ea | <|skeleton|>
class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
<|body_0|>
def converter(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MXNetGraphConverter:
"""mxnet graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, weights_path, shapes, dyns, outdirs, nets_name, input_names, framework, target):
"""Init mxnet graph bmodel converter"""
super(MXNetGraphConverter, self).__init__(framework, base... | the_stack_v2_python_sparse | modules/utils/bmodel_converter.py | sophon-ai-algo/sophon-inference | train | 32 |
178d7d8221ac670b1c450b8bde4f7a65b20a414d | [
"self.schemas = dict()\nfor url in schema_urls:\n name = url.split('/')[-1]\n self.schemas[name] = {'$ref': url, 'id': url}\nself.resolver = self.resolver_factory()\nself._json_gen = JsonGenerator(resolver=self.resolver)",
"if name is None:\n name = random.choice(list(self.schemas.keys()))\n schema = ... | <|body_start_0|>
self.schemas = dict()
for url in schema_urls:
name = url.split('/')[-1]
self.schemas[name] = {'$ref': url, 'id': url}
self.resolver = self.resolver_factory()
self._json_gen = JsonGenerator(resolver=self.resolver)
<|end_body_0|>
<|body_start_1|>
... | Used to generate random JSON from a from a list of URLs containing JSON schemas. | HCAJsonGenerator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HCAJsonGenerator:
"""Used to generate random JSON from a from a list of URLs containing JSON schemas."""
def __init__(self, schema_urls):
""":param schema_urls: a list of JSON schema URLs."""
<|body_0|>
def generate(self, name: str=None) -> str:
"""Chooses a rand... | stack_v2_sparse_classes_10k_train_007452 | 2,792 | permissive | [
{
"docstring": ":param schema_urls: a list of JSON schema URLs.",
"name": "__init__",
"signature": "def __init__(self, schema_urls)"
},
{
"docstring": "Chooses a random JSON schema from self.schemas and generates JSON data. :param name: the name of a JSON schema to generate. If None, then a rand... | 4 | stack_v2_sparse_classes_30k_train_005547 | Implement the Python class `HCAJsonGenerator` described below.
Class description:
Used to generate random JSON from a from a list of URLs containing JSON schemas.
Method signatures and docstrings:
- def __init__(self, schema_urls): :param schema_urls: a list of JSON schema URLs.
- def generate(self, name: str=None) -... | Implement the Python class `HCAJsonGenerator` described below.
Class description:
Used to generate random JSON from a from a list of URLs containing JSON schemas.
Method signatures and docstrings:
- def __init__(self, schema_urls): :param schema_urls: a list of JSON schema URLs.
- def generate(self, name: str=None) -... | 3722323d4eed3089d25f6d6c9cbfb1672b7de939 | <|skeleton|>
class HCAJsonGenerator:
"""Used to generate random JSON from a from a list of URLs containing JSON schemas."""
def __init__(self, schema_urls):
""":param schema_urls: a list of JSON schema URLs."""
<|body_0|>
def generate(self, name: str=None) -> str:
"""Chooses a rand... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HCAJsonGenerator:
"""Used to generate random JSON from a from a list of URLs containing JSON schemas."""
def __init__(self, schema_urls):
""":param schema_urls: a list of JSON schema URLs."""
self.schemas = dict()
for url in schema_urls:
name = url.split('/')[-1]
... | the_stack_v2_python_sparse | attic/hca_generator.py | DataBiosphere/azul | train | 23 |
f3068639bc83c5ede84c28d0f3c5b1ddb7e1ee8d | [
"super().__init__()\nif path:\n use_pretrained = False\nelse:\n use_pretrained = True\nresnet = models.resnet50(pretrained=use_pretrained)\nself.pretrained = nn.Module()\nself.scratch = nn.Module()\nself.pretrained.layer1 = nn.Sequential(resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1)\ns... | <|body_start_0|>
super().__init__()
if path:
use_pretrained = False
else:
use_pretrained = True
resnet = models.resnet50(pretrained=use_pretrained)
self.pretrained = nn.Module()
self.scratch = nn.Module()
self.pretrained.layer1 = nn.Sequent... | Network for monocular depth estimation. | RetrievalNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RetrievalNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256."""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_10k_train_007453 | 4,484 | permissive | [
{
"docstring": "Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256.",
"name": "__init__",
"signature": "def __init__(self, path=None, features=256)"
},
{
"docstring": "Forward pass. Argsn: x (tensor): input data ... | 3 | stack_v2_sparse_classes_30k_train_002475 | Implement the Python class `RetrievalNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. ... | Implement the Python class `RetrievalNet` described below.
Class description:
Network for monocular depth estimation.
Method signatures and docstrings:
- def __init__(self, path=None, features=256): Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. ... | a00c3619bf4042e446e1919087f0b09fe9fa3a65 | <|skeleton|>
class RetrievalNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256."""
<|body_0|>
def forward(s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RetrievalNet:
"""Network for monocular depth estimation."""
def __init__(self, path=None, features=256):
"""Init. Args: path (str, optional): Path to saved model. Defaults to None. features (int, optional): Number of features. Defaults to 256."""
super().__init__()
if path:
... | the_stack_v2_python_sparse | nasws/cnn/search_space/monodepth/models/retrieval_net.py | kcyu2014/nas-landmarkreg | train | 10 |
0bbb4bb944817aae58064d26b3668e31b914da70 | [
"self.starturl = 'http://www.kuaidaili.com/free/inha/'\nself.urls = self.get_urls()\nself.proxylist = self.get_proxy_list(self.urls)\nself.filename = 'proxy.txt'\nself.saveFile(self.filename, self.proxylist)",
"urls = []\nfor i in range(1, 2):\n url = self.starturl + str(i)\n urls.append(url)\nreturn urls",... | <|body_start_0|>
self.starturl = 'http://www.kuaidaili.com/free/inha/'
self.urls = self.get_urls()
self.proxylist = self.get_proxy_list(self.urls)
self.filename = 'proxy.txt'
self.saveFile(self.filename, self.proxylist)
<|end_body_0|>
<|body_start_1|>
urls = []
f... | 获取代理的类 | GetProxy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetProxy:
"""获取代理的类"""
def __init__(self):
"""初始化整个类"""
<|body_0|>
def get_urls(self):
"""返回一个代理url的列表 :return:"""
<|body_1|>
def get_proxy_list(self, urls):
"""返回抓去到代理的列表 整个爬虫的关键 :param urls: :return:"""
<|body_2|>
def saveFile(... | stack_v2_sparse_classes_10k_train_007454 | 2,798 | no_license | [
{
"docstring": "初始化整个类",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "返回一个代理url的列表 :return:",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "返回抓去到代理的列表 整个爬虫的关键 :param urls: :return:",
"name": "get_proxy_list",
"signatu... | 4 | stack_v2_sparse_classes_30k_train_003823 | Implement the Python class `GetProxy` described below.
Class description:
获取代理的类
Method signatures and docstrings:
- def __init__(self): 初始化整个类
- def get_urls(self): 返回一个代理url的列表 :return:
- def get_proxy_list(self, urls): 返回抓去到代理的列表 整个爬虫的关键 :param urls: :return:
- def saveFile(self, filename, proxy_list): 将爬取到的代理写到文件... | Implement the Python class `GetProxy` described below.
Class description:
获取代理的类
Method signatures and docstrings:
- def __init__(self): 初始化整个类
- def get_urls(self): 返回一个代理url的列表 :return:
- def get_proxy_list(self, urls): 返回抓去到代理的列表 整个爬虫的关键 :param urls: :return:
- def saveFile(self, filename, proxy_list): 将爬取到的代理写到文件... | 06d1a652d7238081708e56be87edb4d4abc8f066 | <|skeleton|>
class GetProxy:
"""获取代理的类"""
def __init__(self):
"""初始化整个类"""
<|body_0|>
def get_urls(self):
"""返回一个代理url的列表 :return:"""
<|body_1|>
def get_proxy_list(self, urls):
"""返回抓去到代理的列表 整个爬虫的关键 :param urls: :return:"""
<|body_2|>
def saveFile(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GetProxy:
"""获取代理的类"""
def __init__(self):
"""初始化整个类"""
self.starturl = 'http://www.kuaidaili.com/free/inha/'
self.urls = self.get_urls()
self.proxylist = self.get_proxy_list(self.urls)
self.filename = 'proxy.txt'
self.saveFile(self.filename, self.proxylist... | the_stack_v2_python_sparse | spyder/selenium_demo/kuaiproxy.py | 1019350030wfj/python_demo | train | 0 |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"super(Matern52, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)\nlogger.debug('Initializing %s kernel.' % self.name)\nself.variance = np.float64(variance)\nself.lengthscale = np.float64(lengthscale)\nself.parameter_list = ['variance', 'lengthscale']\nself.constraint_map = {'variance': '+ve', 'len... | <|body_start_0|>
super(Matern52, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)
logger.debug('Initializing %s kernel.' % self.name)
self.variance = np.float64(variance)
self.lengthscale = np.float64(lengthscale)
self.parameter_list = ['variance', 'lengthscale']... | Matern52 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_10k_train_007455 | 9,047 | no_license | [
{
"docstring": "squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified",
"name": "__init__",
"signature": "def __init__(self, n_dims, variance=1.0, lengthscale=1.0, act... | 2 | stack_v2_sparse_classes_30k_train_001787 | Implement the Python class `Matern52` described below.
Class description:
Implement the Matern52 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | Implement the Python class `Matern52` described below.
Class description:
Implement the Matern52 class.
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel varianc... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specif... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Matern52:
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified"""
... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 | |
baf8338eddf4621f2f8e0ab2efc93c014e15355f | [
"self._name = name\nself._version = version\nself._release = release\nself._override = override",
"full_version = None\nif self.version:\n full_version = self.version\n if self.release:\n full_version = '{}-{}'.format(self.version, self.release)\nreturn full_version",
"if self.full_version:\n re... | <|body_start_0|>
self._name = name
self._version = version
self._release = release
self._override = override
<|end_body_0|>
<|body_start_1|>
full_version = None
if self.version:
full_version = self.version
if self.release:
full_ver... | A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families. | PackageVersion | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, ve... | stack_v2_sparse_classes_10k_train_007456 | 14,999 | permissive | [
{
"docstring": "Initializes a package version. Arguments: name: the name of the package version: the version of the package release: the release of the package",
"name": "__init__",
"signature": "def __init__(self, name: str, version: Optional[str]=None, release: Optional[str]=None, override: Optional[s... | 3 | stack_v2_sparse_classes_30k_train_002064 | Implement the Python class `PackageVersion` described below.
Class description:
A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families.
... | Implement the Python class `PackageVersion` described below.
Class description:
A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families.
... | 6854d582f58592675afb3759585ce614b3db08f3 | <|skeleton|>
class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, ve... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PackageVersion:
"""A package's authoritative version data. This class contains version information for a named package, and provides helper methods for formatting version/release data as well as version-enriched package name, for all supported OS families."""
def __init__(self, name: str, version: Option... | the_stack_v2_python_sparse | buildchain/buildchain/versions.py | scality/metalk8s | train | 321 |
5163a39a3ba3038af6cae509580ddedbda2cbc1a | [
"params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))\nparams['image_id'] = image_id\nparams['tag_group_id'] = tag_group_id\nform = SingleGetForm(params)\nif not form.is_valid():\n raise BadRequestException()\nreturn Response(form.submit(request))",
"params = dict(((key, val) for key, v... | <|body_start_0|>
params = dict(((key, val) for key, val in request.QUERY_PARAMS.iteritems()))
params['image_id'] = image_id
params['tag_group_id'] = tag_group_id
form = SingleGetForm(params)
if not form.is_valid():
raise BadRequestException()
return Response(f... | Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup. | TagGroupSingle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagGroupSingle:
"""Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup."""
def get(self, request, image_id, tag_group_id):
"""Method for getting multiple TagGroups either thorugh search or general listing."""
<|body_0|>
def pu... | stack_v2_sparse_classes_10k_train_007457 | 2,816 | no_license | [
{
"docstring": "Method for getting multiple TagGroups either thorugh search or general listing.",
"name": "get",
"signature": "def get(self, request, image_id, tag_group_id)"
},
{
"docstring": "Method for updating a TagGroup's information.",
"name": "put",
"signature": "def put(self, req... | 3 | stack_v2_sparse_classes_30k_train_003760 | Implement the Python class `TagGroupSingle` described below.
Class description:
Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup.
Method signatures and docstrings:
- def get(self, request, image_id, tag_group_id): Method for getting multiple TagGroups either thorugh sea... | Implement the Python class `TagGroupSingle` described below.
Class description:
Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup.
Method signatures and docstrings:
- def get(self, request, image_id, tag_group_id): Method for getting multiple TagGroups either thorugh sea... | 22c1ce3c5a8e4ed99c2f014672d60ad3c5a4003c | <|skeleton|>
class TagGroupSingle:
"""Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup."""
def get(self, request, image_id, tag_group_id):
"""Method for getting multiple TagGroups either thorugh search or general listing."""
<|body_0|>
def pu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TagGroupSingle:
"""Class for rendering the view for getting a TagGroup, deleting a TagGroup and updating a TagGroup."""
def get(self, request, image_id, tag_group_id):
"""Method for getting multiple TagGroups either thorugh search or general listing."""
params = dict(((key, val) for key, ... | the_stack_v2_python_sparse | biodig/rest/v2/TagGroups/views.py | asmariyaz23/BioDIG | train | 0 |
61c103c58d3c039e7fe0e84c2829b052ea80c438 | [
"super().__init__(**kwargs)\nself.factory = factory\nself.curriculum_guide = curriculum_guide",
"curriculum_guide_sections_structure = self.load_yaml_file(self.structure_file_path)\nsection_numbers = []\nfor section_slug, section_structure in curriculum_guide_sections_structure.items():\n if section_structure ... | <|body_start_0|>
super().__init__(**kwargs)
self.factory = factory
self.curriculum_guide = curriculum_guide
<|end_body_0|>
<|body_start_1|>
curriculum_guide_sections_structure = self.load_yaml_file(self.structure_file_path)
section_numbers = []
for section_slug, section_... | Custom loader for loading curriculum guide sections. | CurriculumGuideSectionsLoader | [
"CC-BY-NC-SA-4.0",
"BSD-3-Clause",
"CC0-1.0",
"ISC",
"Unlicense",
"LicenseRef-scancode-secret-labs-2011",
"WTFPL",
"Apache-2.0",
"LGPL-3.0-only",
"MIT",
"CC-BY-SA-4.0",
"LicenseRef-scancode-public-domain",
"CC-BY-NC-2.5",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurriculumGuideSectionsLoader:
"""Custom loader for loading curriculum guide sections."""
def __init__(self, factory, curriculum_guide, **kwargs):
"""Create the loader for loading curriculum guide sections. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). cur... | stack_v2_sparse_classes_10k_train_007458 | 4,393 | permissive | [
{
"docstring": "Create the loader for loading curriculum guide sections. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). curriculum_guide: Object of related curriculum guide model (CurriculumGuide).",
"name": "__init__",
"signature": "def __init__(self, factory, curriculum_guid... | 2 | stack_v2_sparse_classes_30k_train_002856 | Implement the Python class `CurriculumGuideSectionsLoader` described below.
Class description:
Custom loader for loading curriculum guide sections.
Method signatures and docstrings:
- def __init__(self, factory, curriculum_guide, **kwargs): Create the loader for loading curriculum guide sections. Args: factory: Loade... | Implement the Python class `CurriculumGuideSectionsLoader` described below.
Class description:
Custom loader for loading curriculum guide sections.
Method signatures and docstrings:
- def __init__(self, factory, curriculum_guide, **kwargs): Create the loader for loading curriculum guide sections. Args: factory: Loade... | ea3281ec6f4d17538f6d3cf6f88d74fa54581b34 | <|skeleton|>
class CurriculumGuideSectionsLoader:
"""Custom loader for loading curriculum guide sections."""
def __init__(self, factory, curriculum_guide, **kwargs):
"""Create the loader for loading curriculum guide sections. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). cur... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CurriculumGuideSectionsLoader:
"""Custom loader for loading curriculum guide sections."""
def __init__(self, factory, curriculum_guide, **kwargs):
"""Create the loader for loading curriculum guide sections. Args: factory: LoaderFactory object for creating loaders (LoaderFactory). curriculum_guide... | the_stack_v2_python_sparse | csfieldguide/curriculum_guides/management/commands/_CurriculumGuideSectionsLoader.py | uccser/cs-field-guide | train | 364 |
dd0b014422a05e3a443097c714a452d4d2dd0600 | [
"batch_size = 10\nnb_visible = 15\nnb_hidden = 10\nnb_z = 2\nvisible_units = numpy.random.normal(loc=0.0, scale=1.0, size=(batch_size, nb_visible))\nvariational_ae_0 = VariationalAutoencoder(nb_visible, nb_hidden, nb_z, True, 0.3)\nvariational_ae_0.backpropagation(visible_units, is_checking=True, path_to_checking_g... | <|body_start_0|>
batch_size = 10
nb_visible = 15
nb_hidden = 10
nb_z = 2
visible_units = numpy.random.normal(loc=0.0, scale=1.0, size=(batch_size, nb_visible))
variational_ae_0 = VariationalAutoencoder(nb_visible, nb_hidden, nb_z, True, 0.3)
variational_ae_0.backp... | Class for testing two methods of class `VariationalAutoencoder`. | TesterVariationalAutoencoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TesterVariationalAutoencoder:
"""Class for testing two methods of class `VariationalAutoencoder`."""
def test_backpropagation(self):
"""Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via ... | stack_v2_sparse_classes_10k_train_007459 | 4,566 | no_license | [
{
"docstring": "Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via gradient checking, see <http://ufldl.stanford.edu/wiki/index.php/Gradient_checking_and_advanced_optimization>. Six histograms are saved in the folde... | 2 | stack_v2_sparse_classes_30k_train_006976 | Implement the Python class `TesterVariationalAutoencoder` described below.
Class description:
Class for testing two methods of class `VariationalAutoencoder`.
Method signatures and docstrings:
- def test_backpropagation(self): Tests the method `backpropagation`. The method `backpropagation` computes the gradients of ... | Implement the Python class `TesterVariationalAutoencoder` described below.
Class description:
Class for testing two methods of class `VariationalAutoencoder`.
Method signatures and docstrings:
- def test_backpropagation(self): Tests the method `backpropagation`. The method `backpropagation` computes the gradients of ... | 17583bbbddeaf40b14bcfe816c061b8fed6bb5df | <|skeleton|>
class TesterVariationalAutoencoder:
"""Class for testing two methods of class `VariationalAutoencoder`."""
def test_backpropagation(self):
"""Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TesterVariationalAutoencoder:
"""Class for testing two methods of class `VariationalAutoencoder`."""
def test_backpropagation(self):
"""Tests the method `backpropagation`. The method `backpropagation` computes the gradients of the variational autoencoder parameters. It is tested via gradient chec... | the_stack_v2_python_sparse | svhn/test_vae.py | edmontdants/autoencoder_based_image_compression | train | 0 |
9230f03ce85eefc6084e7623f79f47360e3dedad | [
"threshold_diffs = np.diff(threshold_ranges)\nif any((diff < 1e-05 for diff in threshold_diffs)):\n raise ValueError('Plugin cannot distinguish between thresholds at {} {}'.format(threshold_ranges, threshold_units))\nself.threshold_ranges = threshold_ranges\nself.threshold_units = threshold_units",
"thresh_coo... | <|body_start_0|>
threshold_diffs = np.diff(threshold_ranges)
if any((diff < 1e-05 for diff in threshold_diffs)):
raise ValueError('Plugin cannot distinguish between thresholds at {} {}'.format(threshold_ranges, threshold_units))
self.threshold_ranges = threshold_ranges
self.t... | Calculate the probability of occurrence between thresholds | OccurrenceBetweenThresholds | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OccurrenceBetweenThresholds:
"""Calculate the probability of occurrence between thresholds"""
def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None:
"""Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differen... | stack_v2_sparse_classes_10k_train_007460 | 8,945 | permissive | [
{
"docstring": "Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differences at the 1e-5 (float32) precision level. Args: threshold_ranges: List of 2-item iterables specifying thresholds between which probabilities should be calculated threshold_units: Units in which t... | 6 | null | Implement the Python class `OccurrenceBetweenThresholds` described below.
Class description:
Calculate the probability of occurrence between thresholds
Method signatures and docstrings:
- def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: Initialise the class. Threshold ranges must... | Implement the Python class `OccurrenceBetweenThresholds` described below.
Class description:
Calculate the probability of occurrence between thresholds
Method signatures and docstrings:
- def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None: Initialise the class. Threshold ranges must... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class OccurrenceBetweenThresholds:
"""Calculate the probability of occurrence between thresholds"""
def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None:
"""Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OccurrenceBetweenThresholds:
"""Calculate the probability of occurrence between thresholds"""
def __init__(self, threshold_ranges: List[List[float]], threshold_units: str) -> None:
"""Initialise the class. Threshold ranges must be specified in a unit that is NOT sensitive to differences at the 1e... | the_stack_v2_python_sparse | improver/between_thresholds.py | metoppv/improver | train | 101 |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n student = get_object_or_404(Student, user__username=username)\n serializer = StudentSerializer(student)\n return JsonResponse({'students': [serializer.data]}, safe=False)\nsquad_id = request.GET.get('squad_id', None)\nif squad_id is ... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
student = get_object_or_404(Student, user__username=username)
serializer = StudentSerializer(student)
return JsonResponse({'students': [serializer.data]}, safe=False)
squad_... | 学生view | Students | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
<|body_0|>
def put(self, request):
"""修改学生"""
<|body_1|>
def post(self, request):
"""增加学生"""
<|body_2|>
def delete(self, request):
"""删除学生"""
<|body_3|>
<... | stack_v2_sparse_classes_10k_train_007461 | 16,053 | permissive | [
{
"docstring": "查询学生",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改学生",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加学生",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除学生",
... | 4 | stack_v2_sparse_classes_30k_train_007335 | Implement the Python class `Students` described below.
Class description:
学生view
Method signatures and docstrings:
- def get(self, request): 查询学生
- def put(self, request): 修改学生
- def post(self, request): 增加学生
- def delete(self, request): 删除学生 | Implement the Python class `Students` described below.
Class description:
学生view
Method signatures and docstrings:
- def get(self, request): 查询学生
- def put(self, request): 修改学生
- def post(self, request): 增加学生
- def delete(self, request): 删除学生
<|skeleton|>
class Students:
"""学生view"""
def get(self, request):... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
<|body_0|>
def put(self, request):
"""修改学生"""
<|body_1|>
def post(self, request):
"""增加学生"""
<|body_2|>
def delete(self, request):
"""删除学生"""
<|body_3|>
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Students:
"""学生view"""
def get(self, request):
"""查询学生"""
username = request.GET.get('username', None)
if username is not None:
student = get_object_or_404(Student, user__username=username)
serializer = StudentSerializer(student)
return JsonResp... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
51471a242c9778609113ef6ff9775962dcd5ab44 | [
"if not s or len(s.strip(' ')) == 0:\n return ''\nres = s.split(' ')\nstr = ''\nfor i in range(len(res) - 1, -1, -1):\n str = str.strip(' ') + ' ' + res[i]\nreturn str.strip(' ')",
"if not s or len(s.strip(' ')) == 0:\n return ''\nslist = s.split()\nslist = slist[::-1]\nreturn ' '.join(slist)"
] | <|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
<|end_body_0|>
<|body_start_1|>
if not s or len(s.strip(' ')... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not s or len(s.strip(' ')) == 0:
return ''
... | stack_v2_sparse_classes_10k_train_007462 | 1,018 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWords",
"signature": "def reverseWords(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseWordsSol",
"signature": "def reverseWordsSol(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003471 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseWords(self, s): :type s: str :rtype: str
- def reverseWordsSol(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseWords(self, s):
... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseWordsSol(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseWords(self, s):
""":type s: str :rtype: str"""
if not s or len(s.strip(' ')) == 0:
return ''
res = s.split(' ')
str = ''
for i in range(len(res) - 1, -1, -1):
str = str.strip(' ') + ' ' + res[i]
return str.strip(' ')
... | the_stack_v2_python_sparse | medium/reverse_words_in_string.py | gerrycfchang/leetcode-python | train | 2 | |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError('If degrees is a single number, it must be positive.')\n self.degrees = (-degrees, degrees)\nelse:\n if len(degrees) != 2:\n raise ValueError('If degrees is a sequence, it must be of len 2.')\n self.degrees = deg... | <|body_start_0|>
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError('If degrees is a single number, it must be positive.')
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError('If degrees... | Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the ce... | RandomRotation3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_10k_train_007463 | 34,927 | permissive | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, degrees, rotate_planes=[[0, 1], [0, 2], [1, 2]])"
},
{
"docstring": "Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation.",
"name": "get_param... | 3 | null | Implement the Python class `RandomRotation3D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | Implement the Python class `RandomRotation3D` described below.
Class description:
Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optiona... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandomRotation3D:
"""Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). center (2-tuple, optional): Optional center of rotation. Origin is the upper... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
427bb3364f64cd3837ccf15ba81b1a601b680bd9 | [
"try:\n service.ServerConfLoader().post(json.loads(str(request.body, 'utf-8')))\n return_data = {'status': '200', 'result': str('')}\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '400', 'result': str(e)}\n return Response(json.dumps(return_data))",
"t... | <|body_start_0|>
try:
service.ServerConfLoader().post(json.loads(str(request.body, 'utf-8')))
return_data = {'status': '200', 'result': str('')}
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '400', 'result': str(e... | 1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/{args}/... | CommonEnvInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonEnvInfo:
"""1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/datafr... | stack_v2_sparse_classes_10k_train_007464 | 2,612 | no_license | [
{
"docstring": "- Request json data example <texfied> <font size = 1> {'state': 'A', 'store_type': '1', 'fw_capa' : '1', 'livy_host' : '8ea172cae00f:8998' , 'livy_sess' : '1', 'spark_host' : '8ea172cae00f:7077', 'spark_core': '1', 'spark_memory': '1G', 'hdfs_host': '587ed1df9441:9000', 'hdfs_root': '/tensormsa'... | 2 | stack_v2_sparse_classes_30k_train_005265 | Implement the Python class `CommonEnvInfo` described below.
Class description:
1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/tabl... | Implement the Python class `CommonEnvInfo` described below.
Class description:
1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/tabl... | ef058737f391de817c74398ef9a5d3a28f973c98 | <|skeleton|>
class CommonEnvInfo:
"""1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/datafr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonEnvInfo:
"""1. Name : CommonEnvInfo (step 1) 2. Steps - WDNN essential steps - post /api/v1/type/common/env/ - post /api/v1/type/common/job/{nnid}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/ - post /api/v1/type/dataframe/base/{baseid}/table/{tb}/data/ - post /api/v1/type/dataframe/base/{bas... | the_stack_v2_python_sparse | tfmsarest/views/common_env.py | TensorMSA/tensormsa_old | train | 6 |
f79227895895befb9d6477caac884e53171e7c28 | [
"super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)\nself.parent = parent\nself.rfc = rfc\nself.tel = tel\nself.email = email\nself.name = name\nself.use = use\nself.initUi()",
"style = '\\n QLineEdit {\\n border-radius: 20%;\\n padding-... | <|body_start_0|>
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.parent = parent
self.rfc = rfc
self.tel = tel
self.email = email
self.name = name
self.use = use
self.initUi()
<|end_body_0|>
<|body_start_1|>
style =... | Dialog to capture the customer data for the invoice. | InvoiceData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def verify(self):
"""Verify all fields are fil... | stack_v2_sparse_classes_10k_train_007465 | 27,111 | no_license | [
{
"docstring": "Init.",
"name": "__init__",
"signature": "def __init__(self, rfc, tel, email, name, use, parent)"
},
{
"docstring": "Ui Setup.",
"name": "initUi",
"signature": "def initUi(self)"
},
{
"docstring": "Verify all fields are filled.",
"name": "verify",
"signatu... | 5 | stack_v2_sparse_classes_30k_train_005811 | Implement the Python class `InvoiceData` described below.
Class description:
Dialog to capture the customer data for the invoice.
Method signatures and docstrings:
- def __init__(self, rfc, tel, email, name, use, parent): Init.
- def initUi(self): Ui Setup.
- def verify(self): Verify all fields are filled.
- def acce... | Implement the Python class `InvoiceData` described below.
Class description:
Dialog to capture the customer data for the invoice.
Method signatures and docstrings:
- def __init__(self, rfc, tel, email, name, use, parent): Init.
- def initUi(self): Ui Setup.
- def verify(self): Verify all fields are filled.
- def acce... | a5d18593e689123cac34af552628ed2818ca5d59 | <|skeleton|>
class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
<|body_0|>
def initUi(self):
"""Ui Setup."""
<|body_1|>
def verify(self):
"""Verify all fields are fil... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InvoiceData:
"""Dialog to capture the customer data for the invoice."""
def __init__(self, rfc, tel, email, name, use, parent):
"""Init."""
super().__init__(parent, Qt.FramelessWindowHint | Qt.WindowSystemMenuHint)
self.parent = parent
self.rfc = rfc
self.tel = tel... | the_stack_v2_python_sparse | Dialogs.py | edgary777/lonchepos | train | 0 |
3c25d4cf11e3e2fb565273d4eb8de9bdce8aed84 | [
"max_area = left = 0\nright = len(heights) - 1\nwhile left < right:\n max_area = max(max_area, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]:\n left += 1\n else:\n right -= 1\nreturn max_area",
"max_area = 0\nfor left in range(len(heights)):\n f... | <|body_start_0|>
max_area = left = 0
right = len(heights) - 1
while left < right:
max_area = max(max_area, min(heights[left], heights[right]) * (right - left))
if heights[left] < heights[right]:
left += 1
else:
right -= 1
... | Container | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def get_max_area_(self, heights: List[int]) -> int:
"""Approach: Brute Force Time Complexity: O(N^2... | stack_v2_sparse_classes_10k_train_007466 | 1,463 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:",
"name": "get_max_area",
"signature": "def get_max_area(self, heights: List[int]) -> int"
},
{
"docstring": "Approach: Brute Force Time Complexity: O(N^2) Space Complexity: O(1) :param heigh... | 2 | stack_v2_sparse_classes_30k_train_005838 | Implement the Python class `Container` described below.
Class description:
Implement the Container class.
Method signatures and docstrings:
- def get_max_area(self, heights: List[int]) -> int: Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def get_max_area_(self, heights: L... | Implement the Python class `Container` described below.
Class description:
Implement the Container class.
Method signatures and docstrings:
- def get_max_area(self, heights: List[int]) -> int: Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:
- def get_max_area_(self, heights: L... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
<|body_0|>
def get_max_area_(self, heights: List[int]) -> int:
"""Approach: Brute Force Time Complexity: O(N^2... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Container:
def get_max_area(self, heights: List[int]) -> int:
"""Approach: One Pass Time Complexity: O(N) Space Complexity: O(1) :param heights: :return:"""
max_area = left = 0
right = len(heights) - 1
while left < right:
max_area = max(max_area, min(heights[left], ... | the_stack_v2_python_sparse | revisited/math_and_strings/math/container_with_most_amount_of_water.py | Shiv2157k/leet_code | train | 1 | |
980de806b394bb46849606d7e27fdf360354e87e | [
"url = reverse('api-supplier-part-list')\nresponse = self.get(url, {}, expected_code=200)\nself.assertEqual(len(response.data), SupplierPart.objects.count())\nfor supplier in Company.objects.filter(is_supplier=True):\n response = self.get(url, {'supplier': supplier.pk}, expected_code=200)\n self.assertEqual(l... | <|body_start_0|>
url = reverse('api-supplier-part-list')
response = self.get(url, {}, expected_code=200)
self.assertEqual(len(response.data), SupplierPart.objects.count())
for supplier in Company.objects.filter(is_supplier=True):
response = self.get(url, {'supplier': supplier... | Unit tests for the SupplierPart API endpoints | SupplierPartTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupplierPartTest:
"""Unit tests for the SupplierPart API endpoints"""
def test_supplier_part_list(self):
"""Test the SupplierPart API list functionality"""
<|body_0|>
def test_available(self):
"""Tests for updating the 'available' field"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_007467 | 19,439 | permissive | [
{
"docstring": "Test the SupplierPart API list functionality",
"name": "test_supplier_part_list",
"signature": "def test_supplier_part_list(self)"
},
{
"docstring": "Tests for updating the 'available' field",
"name": "test_available",
"signature": "def test_available(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002502 | Implement the Python class `SupplierPartTest` described below.
Class description:
Unit tests for the SupplierPart API endpoints
Method signatures and docstrings:
- def test_supplier_part_list(self): Test the SupplierPart API list functionality
- def test_available(self): Tests for updating the 'available' field | Implement the Python class `SupplierPartTest` described below.
Class description:
Unit tests for the SupplierPart API endpoints
Method signatures and docstrings:
- def test_supplier_part_list(self): Test the SupplierPart API list functionality
- def test_available(self): Tests for updating the 'available' field
<|sk... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class SupplierPartTest:
"""Unit tests for the SupplierPart API endpoints"""
def test_supplier_part_list(self):
"""Test the SupplierPart API list functionality"""
<|body_0|>
def test_available(self):
"""Tests for updating the 'available' field"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SupplierPartTest:
"""Unit tests for the SupplierPart API endpoints"""
def test_supplier_part_list(self):
"""Test the SupplierPart API list functionality"""
url = reverse('api-supplier-part-list')
response = self.get(url, {}, expected_code=200)
self.assertEqual(len(response... | the_stack_v2_python_sparse | InvenTree/company/test_api.py | inventree/InvenTree | train | 3,077 |
420be07774e250b1b3349a22a54715b27b101592 | [
"this_click_time = time.time()\ntime_to_last_click = None\nif cls.last_click_time:\n time_to_last_click = this_click_time - cls.last_click_time\ncls.last_click_time = this_click_time\nreturn time_to_last_click and time_to_last_click < 0.7",
"is_parent = cloud_plot.is_parent_artist(artist, ind)\ngen = cloud_plo... | <|body_start_0|>
this_click_time = time.time()
time_to_last_click = None
if cls.last_click_time:
time_to_last_click = this_click_time - cls.last_click_time
cls.last_click_time = this_click_time
return time_to_last_click and time_to_last_click < 0.7
<|end_body_0|>
<|b... | mouse pick event on cloud plot | PointClick | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointClick:
"""mouse pick event on cloud plot"""
def rate_limiting(cls):
"""limit the rate of clicking"""
<|body_0|>
def button_1(cls, cloud_plot, artist, ind):
"""click with button 1, i.e., left button"""
<|body_1|>
def button_3(cls, cloud_plot, art... | stack_v2_sparse_classes_10k_train_007468 | 4,481 | permissive | [
{
"docstring": "limit the rate of clicking",
"name": "rate_limiting",
"signature": "def rate_limiting(cls)"
},
{
"docstring": "click with button 1, i.e., left button",
"name": "button_1",
"signature": "def button_1(cls, cloud_plot, artist, ind)"
},
{
"docstring": "click with butt... | 4 | stack_v2_sparse_classes_30k_train_006595 | Implement the Python class `PointClick` described below.
Class description:
mouse pick event on cloud plot
Method signatures and docstrings:
- def rate_limiting(cls): limit the rate of clicking
- def button_1(cls, cloud_plot, artist, ind): click with button 1, i.e., left button
- def button_3(cls, cloud_plot, artist,... | Implement the Python class `PointClick` described below.
Class description:
mouse pick event on cloud plot
Method signatures and docstrings:
- def rate_limiting(cls): limit the rate of clicking
- def button_1(cls, cloud_plot, artist, ind): click with button 1, i.e., left button
- def button_3(cls, cloud_plot, artist,... | d0132c8a64516fbb45eb1e645c6312bbe56a7bc5 | <|skeleton|>
class PointClick:
"""mouse pick event on cloud plot"""
def rate_limiting(cls):
"""limit the rate of clicking"""
<|body_0|>
def button_1(cls, cloud_plot, artist, ind):
"""click with button 1, i.e., left button"""
<|body_1|>
def button_3(cls, cloud_plot, art... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PointClick:
"""mouse pick event on cloud plot"""
def rate_limiting(cls):
"""limit the rate of clicking"""
this_click_time = time.time()
time_to_last_click = None
if cls.last_click_time:
time_to_last_click = this_click_time - cls.last_click_time
cls.last... | the_stack_v2_python_sparse | visual_inspector/figure_base/mouse_event.py | justin-nguyen-1996/deep-neuroevolution | train | 1 |
8a35cc0467f05bc6c013748ef70aa4c80b707008 | [
"if head.next is None or head.next is None:\n return head\nnew_head = self.reverseList(head.next)\nhead.next.next = head\nhead.next = None\nreturn new_head",
"if head is None:\n return head\npre = None\ncur = head\nwhile cur is not None:\n next_node = cur.next\n cur.next = pre\n pre = cur\n cur ... | <|body_start_0|>
if head.next is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
<|end_body_0|>
<|body_start_1|>
if head is None:
return head
pre = None
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""递归"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""迭代"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if head.next is None or head.next is None:
return ... | stack_v2_sparse_classes_10k_train_007469 | 941 | no_license | [
{
"docstring": "递归",
"name": "reverseList",
"signature": "def reverseList(self, head: ListNode) -> ListNode"
},
{
"docstring": "迭代",
"name": "reverseList1",
"signature": "def reverseList1(self, head: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_004983 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 递归
- def reverseList1(self, head: ListNode) -> ListNode: 迭代 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head: ListNode) -> ListNode: 递归
- def reverseList1(self, head: ListNode) -> ListNode: 迭代
<|skeleton|>
class Solution:
def reverseList(self, head: List... | 3fa96c81f92595cf076ad675ba332e2b0eb0e071 | <|skeleton|>
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""递归"""
<|body_0|>
def reverseList1(self, head: ListNode) -> ListNode:
"""迭代"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head: ListNode) -> ListNode:
"""递归"""
if head.next is None or head.next is None:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
def reverseList1(self, hea... | the_stack_v2_python_sparse | 2020-03/3月每日一题复习/206反转链表.py | Annihilation7/Leetcode-Love | train | 0 | |
4e994443698c5c7521e81d1ed8659e97c3de7666 | [
"super(CommonRunCmd, self).do_treatcards(line, amcatnlo)\nkeepwidth = False\nif '--keepwidth' in line:\n keepwidth = True\n line = line.replace('--keepwidth', '')\nargs = self.split_arg(line)\nmode, opt = self.check_treatcards(args)\nif amcatnlo and mode in ['all', 'param'] and (not keepwidth):\n if os.pat... | <|body_start_0|>
super(CommonRunCmd, self).do_treatcards(line, amcatnlo)
keepwidth = False
if '--keepwidth' in line:
keepwidth = True
line = line.replace('--keepwidth', '')
args = self.split_arg(line)
mode, opt = self.check_treatcards(args)
if amca... | CommonRunCmd | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonRunCmd:
def do_treatcards(self, line, amcatnlo=False):
"""call the mother, then, if the param_card has to be updated, write it again"""
<|body_0|>
def replace_widths_in_paramcard_inc(self, decay_to_keep, param_inc):
"""replace the widths passed in decay_to_keep... | stack_v2_sparse_classes_10k_train_007470 | 4,818 | no_license | [
{
"docstring": "call the mother, then, if the param_card has to be updated, write it again",
"name": "do_treatcards",
"signature": "def do_treatcards(self, line, amcatnlo=False)"
},
{
"docstring": "replace the widths passed in decay_to_keep inside param_inc and force them to be zero",
"name"... | 3 | null | Implement the Python class `CommonRunCmd` described below.
Class description:
Implement the CommonRunCmd class.
Method signatures and docstrings:
- def do_treatcards(self, line, amcatnlo=False): call the mother, then, if the param_card has to be updated, write it again
- def replace_widths_in_paramcard_inc(self, deca... | Implement the Python class `CommonRunCmd` described below.
Class description:
Implement the CommonRunCmd class.
Method signatures and docstrings:
- def do_treatcards(self, line, amcatnlo=False): call the mother, then, if the param_card has to be updated, write it again
- def replace_widths_in_paramcard_inc(self, deca... | dd3d3a3826343d4f75ec36b4662b6e9ff1f270f4 | <|skeleton|>
class CommonRunCmd:
def do_treatcards(self, line, amcatnlo=False):
"""call the mother, then, if the param_card has to be updated, write it again"""
<|body_0|>
def replace_widths_in_paramcard_inc(self, decay_to_keep, param_inc):
"""replace the widths passed in decay_to_keep... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommonRunCmd:
def do_treatcards(self, line, amcatnlo=False):
"""call the mother, then, if the param_card has to be updated, write it again"""
super(CommonRunCmd, self).do_treatcards(line, amcatnlo)
keepwidth = False
if '--keepwidth' in line:
keepwidth = True
... | the_stack_v2_python_sparse | bin/MadGraph5_aMCatNLO/PLUGIN/MadSTR/common_run_interface.py | cms-sw/genproductions | train | 69 | |
4d999acdc0771ed4a7c0179cae436ba22f8dbeab | [
"self._video_path = video_path\nself._all_frames = []\nself._annotations = []",
"ann_frame = self._annotations[annotation_index]\nframe_num = ann_frame._frame_num\nbbox = ann_frame._bbox\nimage_files = self._all_frames\nassert len(image_files) > 0\nassert frame_num < len(image_files)\nimage = load(image_files[fra... | <|body_start_0|>
self._video_path = video_path
self._all_frames = []
self._annotations = []
<|end_body_0|>
<|body_start_1|>
ann_frame = self._annotations[annotation_index]
frame_num = ann_frame._frame_num
bbox = ann_frame._bbox
image_files = self._all_frames
... | Docstring for video. | video | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
<|body_0|>
def load_annotation(self, annotation_index):
"""load annotation"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._video_path = video_p... | stack_v2_sparse_classes_10k_train_007471 | 1,551 | permissive | [
{
"docstring": "@video_path: video path",
"name": "__init__",
"signature": "def __init__(self, video_path)"
},
{
"docstring": "load annotation",
"name": "load_annotation",
"signature": "def load_annotation(self, annotation_index)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001833 | Implement the Python class `video` described below.
Class description:
Docstring for video.
Method signatures and docstrings:
- def __init__(self, video_path): @video_path: video path
- def load_annotation(self, annotation_index): load annotation | Implement the Python class `video` described below.
Class description:
Docstring for video.
Method signatures and docstrings:
- def __init__(self, video_path): @video_path: video path
- def load_annotation(self, annotation_index): load annotation
<|skeleton|>
class video:
"""Docstring for video."""
def __in... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
<|body_0|>
def load_annotation(self, annotation_index):
"""load annotation"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class video:
"""Docstring for video."""
def __init__(self, video_path):
"""@video_path: video path"""
self._video_path = video_path
self._all_frames = []
self._annotations = []
def load_annotation(self, annotation_index):
"""load annotation"""
ann_frame = se... | the_stack_v2_python_sparse | PyTorch/built-in/cv/object_tracking/GOTURN_for_PyTorch/src/goturn/helper/video.py | Ascend/ModelZoo-PyTorch | train | 23 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nself.fft_size = fft_size\nself.shift_size = shift_size\nself.win_length = win_length\nself.window = window\nself.spectral_convergence_loss = SpectralConvergenceLoss()\nself.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()",
"x_mag = stft(x, self.fft_size, self.shift_size, self.win_length, sel... | <|body_start_0|>
super().__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = win_length
self.window = window
self.spectral_convergence_loss = SpectralConvergenceLoss()
self.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()
<|end_body_... | STFT loss module. | STFTLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T).... | stack_v2_sparse_classes_10k_train_007472 | 46,210 | permissive | [
{
"docstring": "Initialize STFT loss module.",
"name": "__init__",
"signature": "def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann')"
},
{
"docstring": "Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtruth signal (B, T). R... | 2 | stack_v2_sparse_classes_30k_train_000069 | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Pre... | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tensor): Pre... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T).... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann'):
"""Initialize STFT loss module."""
super().__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = win_length
self... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
bd6afedc1074725d2f7ced87041e895aeb78ce30 | [
"def helper_serialize(node, string):\n if node is None:\n string += 'None,'\n else:\n string += str(node.val) + ','\n string = helper_serialize(node.left, string)\n string = helper_serialize(node.right, string)\n return string\nreturn helper_serialize(root, '')",
"def helper_d... | <|body_start_0|>
def helper_serialize(node, string):
if node is None:
string += 'None,'
else:
string += str(node.val) + ','
string = helper_serialize(node.left, string)
string = helper_serialize(node.right, string)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_007473 | 3,469 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 0a34a19bb0979d58b511822782098f62cd86b25e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def helper_serialize(node, string):
if node is None:
string += 'None,'
else:
string += str(node.val) + ','
string ... | the_stack_v2_python_sparse | Tree/L297_Serialize_Deserialize_Binary_Tree_latest.py | SimonFans/LeetCode | train | 1 | |
79b88cfb0013cfe3ff89046b6315c677f120f59b | [
"def root_left_right(r):\n if not r:\n return []\n return [r.val] + root_left_right(r.left) + root_left_right(r.right)\nreturn str(root_left_right(root))",
"def _deserialize(_li):\n if not _li:\n return\n root = TreeNode(_li[0])\n left = 0\n right = len(_li)\n while left < right... | <|body_start_0|>
def root_left_right(r):
if not r:
return []
return [r.val] + root_left_right(r.left) + root_left_right(r.right)
return str(root_left_right(root))
<|end_body_0|>
<|body_start_1|>
def _deserialize(_li):
if not _li:
... | Codec2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def root_left... | stack_v2_sparse_classes_10k_train_007474 | 3,000 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_004924 | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec2` described below.
Class description:
Implement the Codec2 class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class ... | 6dc5b8968b6bef0186d3806e4aa35ee7b5d75ff2 | <|skeleton|>
class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec2:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def root_left_right(r):
if not r:
return []
return [r.val] + root_left_right(r.left) + root_left_right(r.right)
return str(root_left_right(root))
de... | the_stack_v2_python_sparse | letecode/361-480/441-460/449.py | hshrimp/letecode_for_me | train | 1 | |
30adfa153b5bfe7124ab0c9793504dc8e331680a | [
"if atom.IsInRing():\n return True\ncount = self.depth_first_search_for_ring(atom)\nreturn count > 1",
"count = 0\nfor nbor in atom.GetAtoms():\n visited = set()\n visited.add(atom)\n if nbor.IsInRing() or self.traverse_for_ring(visited, nbor):\n count += 1\nreturn count",
"visited.add(atom)\... | <|body_start_0|>
if atom.IsInRing():
return True
count = self.depth_first_search_for_ring(atom)
return count > 1
<|end_body_0|>
<|body_start_1|>
count = 0
for nbor in atom.GetAtoms():
visited = set()
visited.add(atom)
if nbor.IsInR... | Test if an atom is part of the Murcko scaffold of a molecule. | IsInScaffold | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsInScaffold:
"""Test if an atom is part of the Murcko scaffold of a molecule."""
def __call__(self, atom):
"""Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom."""
<|body_0|>
def depth_first_search_for_ring(self, atom):
""... | stack_v2_sparse_classes_10k_train_007475 | 3,664 | permissive | [
{
"docstring": "Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom.",
"name": "__call__",
"signature": "def __call__(self, atom)"
},
{
"docstring": "Perform a depth-first search to count the number of rings that are directly or indirectly connected to an at... | 3 | stack_v2_sparse_classes_30k_train_001418 | Implement the Python class `IsInScaffold` described below.
Class description:
Test if an atom is part of the Murcko scaffold of a molecule.
Method signatures and docstrings:
- def __call__(self, atom): Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom.
- def depth_first_search_... | Implement the Python class `IsInScaffold` described below.
Class description:
Test if an atom is part of the Murcko scaffold of a molecule.
Method signatures and docstrings:
- def __call__(self, atom): Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom.
- def depth_first_search_... | a6af3686c82a5d1d6b68341fe5e5b16e8e4ed356 | <|skeleton|>
class IsInScaffold:
"""Test if an atom is part of the Murcko scaffold of a molecule."""
def __call__(self, atom):
"""Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom."""
<|body_0|>
def depth_first_search_for_ring(self, atom):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IsInScaffold:
"""Test if an atom is part of the Murcko scaffold of a molecule."""
def __call__(self, atom):
"""Check whether an atom is in the Murcko scaffold. Parameters ---------- atom : OEAtom Atom."""
if atom.IsInRing():
return True
count = self.depth_first_search_... | the_stack_v2_python_sparse | oe_utils/chem/scaffold.py | skearnes/color-features | train | 5 |
8bd52e34a3e6fab768cdacbefb4e47142321352c | [
"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... | Interface exported by the server. | InferenceCoordinatorServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InferenceCoordinatorServicer:
"""Interface exported by the server."""
def DeploySpire(self, request, context):
"""Deploy a Spire"""
<|body_0|>
def DeleteSpire(self, request, context):
"""Delete a Spire"""
<|body_1|>
def GetSpireDeployStatus(self, req... | stack_v2_sparse_classes_10k_train_007476 | 8,159 | no_license | [
{
"docstring": "Deploy a Spire",
"name": "DeploySpire",
"signature": "def DeploySpire(self, request, context)"
},
{
"docstring": "Delete a Spire",
"name": "DeleteSpire",
"signature": "def DeleteSpire(self, request, context)"
},
{
"docstring": "Check whether a spire is running",
... | 4 | stack_v2_sparse_classes_30k_val_000119 | Implement the Python class `InferenceCoordinatorServicer` described below.
Class description:
Interface exported by the server.
Method signatures and docstrings:
- def DeploySpire(self, request, context): Deploy a Spire
- def DeleteSpire(self, request, context): Delete a Spire
- def GetSpireDeployStatus(self, request... | Implement the Python class `InferenceCoordinatorServicer` described below.
Class description:
Interface exported by the server.
Method signatures and docstrings:
- def DeploySpire(self, request, context): Deploy a Spire
- def DeleteSpire(self, request, context): Delete a Spire
- def GetSpireDeployStatus(self, request... | 49dc92036e71ca758cc35e8851a803b89d76ef52 | <|skeleton|>
class InferenceCoordinatorServicer:
"""Interface exported by the server."""
def DeploySpire(self, request, context):
"""Deploy a Spire"""
<|body_0|>
def DeleteSpire(self, request, context):
"""Delete a Spire"""
<|body_1|>
def GetSpireDeployStatus(self, req... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InferenceCoordinatorServicer:
"""Interface exported by the server."""
def DeploySpire(self, request, context):
"""Deploy a Spire"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemen... | the_stack_v2_python_sparse | proto/inference_coordinator/inference_coordinator_pb2_grpc.py | selwynClarifai/video-manager | train | 2 |
e683268bd87d377b3ad90bda0f2d8103faab0f81 | [
"rewards = [0 for _ in range(10001)]\nfor num in nums:\n rewards[num] += num\ncur, prev = (0, 0)\nfor reward in rewards:\n nxt = max(cur, prev + reward)\n prev = cur\n cur = nxt\nreturn cur",
"counter = defaultdict(int)\nfor n in nums:\n counter[n] += 1\nF = [0 for _ in range(10000 + 3)]\nfor i in ... | <|body_start_0|>
rewards = [0 for _ in range(10001)]
for num in nums:
rewards[num] += num
cur, prev = (0, 0)
for reward in rewards:
nxt = max(cur, prev + reward)
prev = cur
cur = nxt
return cur
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
<|body_0|>
def deleteAndEarn_dp(self, nums: List[int]) -> int:
"""reduce to house ... | stack_v2_sparse_classes_10k_train_007477 | 3,136 | no_license | [
{
"docstring": "reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n",
"name": "deleteAndEarn",
"signature": "def deleteAndEarn(self, nums: List[int]) -> int"
},
{
"docstring": "reduce to house rob problem whether to pick the num... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n
- def del... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteAndEarn(self, nums: List[int]) -> int: reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n
- def del... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
<|body_0|>
def deleteAndEarn_dp(self, nums: List[int]) -> int:
"""reduce to house ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""reduce to house rob problem whether to pick the number or not F[n] = max F[n-1] if not pick n F[n-2] + reward if pick n"""
rewards = [0 for _ in range(10001)]
for num in nums:
rewards[num] += num
cur, pre... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/740 Delete and Earn.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
b341a80d0b98d20bd612ab580d168513811c5f8f | [
"vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))\nslice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2:4])\nself.assertEqual(vowels[2:4], slice_vowels, 'Wrong slicing in CustomOrderedDict')\nself.assertEqual(vowels[2:-1], slice_vowels, 'Wrong slicing in CustomOrderedDict')\nself.assertEqual(vowe... | <|body_start_0|>
vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))
slice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2:4])
self.assertEqual(vowels[2:4], slice_vowels, 'Wrong slicing in CustomOrderedDict')
self.assertEqual(vowels[2:-1], slice_vowels, 'Wrong slicing in C... | Test exercise mod 06 CustomOrderedDict | TestCustomOrderedDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
<|body_0|>
def test_addition(self):
"""Check __add__ customization of CustomOrderedDict It returns a n... | stack_v2_sparse_classes_10k_train_007478 | 8,327 | no_license | [
{
"docstring": "Check __getitem__ customization (slicing) of CustomOrderedDict",
"name": "test_slicing",
"signature": "def test_slicing(self)"
},
{
"docstring": "Check __add__ customization of CustomOrderedDict It returns a new CustomOrderedDict with content of the first CustomOrderedDict update... | 3 | stack_v2_sparse_classes_30k_val_000093 | Implement the Python class `TestCustomOrderedDict` described below.
Class description:
Test exercise mod 06 CustomOrderedDict
Method signatures and docstrings:
- def test_slicing(self): Check __getitem__ customization (slicing) of CustomOrderedDict
- def test_addition(self): Check __add__ customization of CustomOrder... | Implement the Python class `TestCustomOrderedDict` described below.
Class description:
Test exercise mod 06 CustomOrderedDict
Method signatures and docstrings:
- def test_slicing(self): Check __getitem__ customization (slicing) of CustomOrderedDict
- def test_addition(self): Check __add__ customization of CustomOrder... | 8f082201e24f0f2b991d9388500fdbf95d6f073d | <|skeleton|>
class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
<|body_0|>
def test_addition(self):
"""Check __add__ customization of CustomOrderedDict It returns a n... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestCustomOrderedDict:
"""Test exercise mod 06 CustomOrderedDict"""
def test_slicing(self):
"""Check __getitem__ customization (slicing) of CustomOrderedDict"""
vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU'))
slice_vowels = source.CustomOrderedDict(zip('aeiou', 'AEIOU')[2... | the_stack_v2_python_sparse | intermediate/exercises/mod_04_data_model/tests_mod_04.py | garciacastano09/pycourse | train | 0 |
5fa9ac74608547f6c0963b65e1831279d1e3dee6 | [
"super(Decoder, self).__init__()\nself.example_size = example_size\nself.num_outputs = example_size[1] * example_size[0] * example_size[2]\nself.cuda_enabled = cuda_enabled\nfc1_output_size = 512\nfc2_output_size = 1024\nfc3_output_size = 4096\nfc4_output_size = 4096 * 3\nself.fc1 = nn.Linear(num_classes * output_u... | <|body_start_0|>
super(Decoder, self).__init__()
self.example_size = example_size
self.num_outputs = example_size[1] * example_size[0] * example_size[2]
self.cuda_enabled = cuda_enabled
fc1_output_size = 512
fc2_output_size = 1024
fc3_output_size = 4096
fc... | Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and send the [16,] vector to the decoder network to reconstruct a [784,] size ... | Decoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and send the [16,] vector to the decoder ne... | stack_v2_sparse_classes_10k_train_007479 | 3,631 | permissive | [
{
"docstring": "The decoder network consists of 3 fully connected layers, with 512, 1024, 784 neurons each.",
"name": "__init__",
"signature": "def __init__(self, num_classes, output_unit_size, cuda_enabled, example_size=(1, 28, 28))"
},
{
"docstring": "We send the outputs of the `DigitCaps` lay... | 2 | stack_v2_sparse_classes_30k_train_003883 | Implement the Python class `Decoder` described below.
Class description:
Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and ... | Implement the Python class `Decoder` described below.
Class description:
Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and ... | 0c6e7a6cccd7630751c8065befba14a0dbaeadd4 | <|skeleton|>
class Decoder:
"""Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and send the [16,] vector to the decoder ne... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Implement Decoder structure in section 4.1, Figure 2 to reconstruct a digit from the `DigitCaps` layer representation. The decoder network consists of 3 fully connected layers. For each [10, 16] output, we mask out the incorrect predictions, and send the [16,] vector to the decoder network to reco... | the_stack_v2_python_sparse | src/org/campagnelab/dl/pytorch/images/models/capsules/decoder.py | fac2003/ureg | train | 0 |
f724f1121326177b41aa01b76c078576ff5adfc5 | [
"self.after_cursor_entity_id = after_cursor_entity_id\nself.before_cursor_entity_id = before_cursor_entity_id\nself.node_id = node_id\nself.page_size = page_size",
"if dictionary is None:\n return None\nafter_cursor_entity_id = dictionary.get('afterCursorEntityId')\nbefore_cursor_entity_id = dictionary.get('be... | <|body_start_0|>
self.after_cursor_entity_id = after_cursor_entity_id
self.before_cursor_entity_id = before_cursor_entity_id
self.node_id = node_id
self.page_size = page_size
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
after_cursor_enti... | Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always refer to a specific source within th... | PaginationParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_10k_train_007480 | 2,821 | permissive | [
{
"docstring": "Constructor for the PaginationParameters class",
"name": "__init__",
"signature": "def __init__(self, after_cursor_entity_id=None, before_cursor_entity_id=None, node_id=None, page_size=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary ... | 2 | null | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | Implement the Python class `PaginationParameters` described below.
Class description:
Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the hel... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PaginationParameters:
"""Implementation of the 'PaginationParameters' model. Specifies the cursor based pagination parameters for Protection Source and its children. Pagination is supported at a given level within the Protection Source Hierarchy with the help of before or after cursors. A Cursor will always r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/pagination_parameters.py | cohesity/management-sdk-python | train | 24 |
9bca46cb6303803e01a256a0b04359a9cb2341b1 | [
"plt.imshow(image)\nplt.axis('off')\nplt.show()",
"_fig, axs = plt.subplots(2, 5, figsize=(10, 10))\nfor ax, image in zip(chain.from_iterable(axs), images):\n ax.imshow(image)\n ax.grid(False)\n ax.axis('off')\nplt.show()"
] | <|body_start_0|>
plt.imshow(image)
plt.axis('off')
plt.show()
<|end_body_0|>
<|body_start_1|>
_fig, axs = plt.subplots(2, 5, figsize=(10, 10))
for ax, image in zip(chain.from_iterable(axs), images):
ax.imshow(image)
ax.grid(False)
ax.axis('off... | Class for viewing images. | ImageViewer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageViewer:
"""Class for viewing images."""
def display(image):
"""Displays an image."""
<|body_0|>
def display_images(images):
"""Displays 10 images."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
plt.imshow(image)
plt.axis('off')
... | stack_v2_sparse_classes_10k_train_007481 | 990 | no_license | [
{
"docstring": "Displays an image.",
"name": "display",
"signature": "def display(image)"
},
{
"docstring": "Displays 10 images.",
"name": "display_images",
"signature": "def display_images(images)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005588 | Implement the Python class `ImageViewer` described below.
Class description:
Class for viewing images.
Method signatures and docstrings:
- def display(image): Displays an image.
- def display_images(images): Displays 10 images. | Implement the Python class `ImageViewer` described below.
Class description:
Class for viewing images.
Method signatures and docstrings:
- def display(image): Displays an image.
- def display_images(images): Displays 10 images.
<|skeleton|>
class ImageViewer:
"""Class for viewing images."""
def display(imag... | 7855d0ca4d74565955958a5d769fdd03b8aac940 | <|skeleton|>
class ImageViewer:
"""Class for viewing images."""
def display(image):
"""Displays an image."""
<|body_0|>
def display_images(images):
"""Displays 10 images."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageViewer:
"""Class for viewing images."""
def display(image):
"""Displays an image."""
plt.imshow(image)
plt.axis('off')
plt.show()
def display_images(images):
"""Displays 10 images."""
_fig, axs = plt.subplots(2, 5, figsize=(10, 10))
for ax... | the_stack_v2_python_sparse | Backpropagation/ImageViewer.py | askbk/IT3030-Deep-Learning | train | 0 |
d5080e6bb3d4e0ca3a7a5dc748a7ebc28116f7b6 | [
"super(MultiHeadedAttention, self).__init__()\nassert d_model % h == 0\nself.d_k = d_model // h\nself.h = h\nself.linears = clones(nn.Linear(d_model, d_model), 4)\nself.attn = None\nself.dropout = nn.Dropout(p=dropout)",
"if mask is not None:\n if len(mask.shape) == 3:\n mask = mask.unsqueeze(1)\n el... | <|body_start_0|>
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
<|end_body_0|>
<|body_start_1|>
... | MultiHeadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super... | stack_v2_sparse_classes_10k_train_007482 | 5,977 | no_license | [
{
"docstring": "Take in model size and number of heads.",
"name": "__init__",
"signature": "def __init__(self, h, d_model, dropout=0.1)"
},
{
"docstring": "Implements Figure 2",
"name": "forward",
"signature": "def forward(self, query, key, value, mask=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006287 | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | Implement the Python class `MultiHeadedAttention` described below.
Class description:
Implement the MultiHeadedAttention class.
Method signatures and docstrings:
- def __init__(self, h, d_model, dropout=0.1): Take in model size and number of heads.
- def forward(self, query, key, value, mask=None): Implements Figure ... | 05cc5124ac188013f8efda082d67d92a8ed6dbd4 | <|skeleton|>
class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
<|body_0|>
def forward(self, query, key, value, mask=None):
"""Implements Figure 2"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiHeadedAttention:
def __init__(self, h, d_model, dropout=0.1):
"""Take in model size and number of heads."""
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_mo... | the_stack_v2_python_sparse | 2020000888/src/scripts/model/transformer.py | info-ruc/web21projects | train | 1 | |
dbda750097e52195b1c42f6dffb73a604189bf48 | [
"ans = collections.defaultdict(list)\nfor s in strs:\n ans[tuple(sorted(s))].append(s)\nreturn list(ans.values())",
"ans = collections.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 list(ans.values())"
] | <|body_start_0|>
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return list(ans.values())
<|end_body_0|>
<|body_start_1|>
ans = collections.defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]:
"""时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:"""
<|body_0|>
def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:
"""时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:"""
<|b... | stack_v2_sparse_classes_10k_train_007483 | 1,552 | permissive | [
{
"docstring": "时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:",
"name": "groupAnagrams_1",
"signature": "def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:",
"name": "groupAnagrams_2",
"signature": "def gro... | 2 | stack_v2_sparse_classes_30k_train_006392 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: 时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:
- def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]: 时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:
- def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]:
"""时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:"""
<|body_0|>
def groupAnagrams_2(self, strs: List[str]) -> List[List[str]]:
"""时间复杂度:O(NK) 空间复杂度:O(NK) :param strs: :return:"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams_1(self, strs: List[str]) -> List[List[str]]:
"""时间复杂度:OO(NKlogK) 空间复杂度:O(NK) :param strs: :return:"""
ans = collections.defaultdict(list)
for s in strs:
ans[tuple(sorted(s))].append(s)
return list(ans.values())
def groupAnagrams_2(se... | the_stack_v2_python_sparse | LeetCode 热题 HOT 100/groupAnagrams.py | MaoningGuan/LeetCode | train | 3 | |
ff850c1ae77a6d3bacbdc5b57a4c494642a4ce4c | [
"if not root:\n return (0, 0)\nleft = self.robUtil(root.left)\nright = self.robUtil(root.right)\nexc = max(left[0], left[1]) + max(right[0], right[1])\ninc = root.val + left[0] + right[0]\nreturn (exc, inc)",
"if not root:\n return 0\nexc, inc = self.robUtil(root)\nreturn max(exc, inc)"
] | <|body_start_0|>
if not root:
return (0, 0)
left = self.robUtil(root.left)
right = self.robUtil(root.right)
exc = max(left[0], left[1]) + max(right[0], right[1])
inc = root.val + left[0] + right[0]
return (exc, inc)
<|end_body_0|>
<|body_start_1|>
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def robUtil(self, root):
""":type root: TreeNode :rtype: (included, excluded)"""
<|body_0|>
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return (0, 0)
... | stack_v2_sparse_classes_10k_train_007484 | 900 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: (included, excluded)",
"name": "robUtil",
"signature": "def robUtil(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rob",
"signature": "def rob(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007083 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def robUtil(self, root): :type root: TreeNode :rtype: (included, excluded)
- def rob(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def robUtil(self, root): :type root: TreeNode :rtype: (included, excluded)
- def rob(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def robUtil(... | 962803824b4173d553cb76940750dc249927b972 | <|skeleton|>
class Solution:
def robUtil(self, root):
""":type root: TreeNode :rtype: (included, excluded)"""
<|body_0|>
def rob(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def robUtil(self, root):
""":type root: TreeNode :rtype: (included, excluded)"""
if not root:
return (0, 0)
left = self.robUtil(root.left)
right = self.robUtil(root.right)
exc = max(left[0], left[1]) + max(right[0], right[1])
inc = root.val... | the_stack_v2_python_sparse | HouseRobber3.py | divyanshk/algorithms-and-data-structures | train | 0 | |
f148e743bb4383215204e8589fc5d3e0870ec399 | [
"company = ShopCompanyService.get_by_id(id)\ncontact_list = ShopCompanyContactService.get_by_company_id(id)\ncompany['contact_list'] = contact_list\nreturn api_response(data=company)",
"parsed_data = self.parsed_data\ntry:\n ShopCompanyService.update_shop_company_by_id(id, **parsed_data)\nexcept ClientError as... | <|body_start_0|>
company = ShopCompanyService.get_by_id(id)
contact_list = ShopCompanyContactService.get_by_company_id(id)
company['contact_list'] = contact_list
return api_response(data=company)
<|end_body_0|>
<|body_start_1|>
parsed_data = self.parsed_data
try:
... | ShopCompanyApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShopCompanyApi:
def get(self, id):
"""根据ID查询公司"""
<|body_0|>
def put(self, id):
"""根据ID修改公司信息"""
<|body_1|>
def delete(self, id):
"""根据ID删除公司"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
company = ShopCompanyService.get_by_id... | stack_v2_sparse_classes_10k_train_007485 | 8,580 | no_license | [
{
"docstring": "根据ID查询公司",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "根据ID修改公司信息",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "根据ID删除公司",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | stack_v2_sparse_classes_30k_test_000076 | Implement the Python class `ShopCompanyApi` described below.
Class description:
Implement the ShopCompanyApi class.
Method signatures and docstrings:
- def get(self, id): 根据ID查询公司
- def put(self, id): 根据ID修改公司信息
- def delete(self, id): 根据ID删除公司 | Implement the Python class `ShopCompanyApi` described below.
Class description:
Implement the ShopCompanyApi class.
Method signatures and docstrings:
- def get(self, id): 根据ID查询公司
- def put(self, id): 根据ID修改公司信息
- def delete(self, id): 根据ID删除公司
<|skeleton|>
class ShopCompanyApi:
def get(self, id):
"""根据... | e87f98f5fbe42c465473d83cb2a535209a8e8287 | <|skeleton|>
class ShopCompanyApi:
def get(self, id):
"""根据ID查询公司"""
<|body_0|>
def put(self, id):
"""根据ID修改公司信息"""
<|body_1|>
def delete(self, id):
"""根据ID删除公司"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShopCompanyApi:
def get(self, id):
"""根据ID查询公司"""
company = ShopCompanyService.get_by_id(id)
contact_list = ShopCompanyContactService.get_by_company_id(id)
company['contact_list'] = contact_list
return api_response(data=company)
def put(self, id):
"""根据ID修改... | the_stack_v2_python_sparse | creole/wsgi/api/v1/endpoint/shop.py | Creoles/creole | train | 0 | |
ec26c73f2ab189b55b53dbdfcf44d4b890a40935 | [
"self.radius = radius\nself.bits = bits\nself.chirality = chirality\nself.sanitize = sanitize",
"try:\n molecule = Chem.MolFromSmiles(smiles, sanitize=self.sanitize)\n if not self.sanitize:\n molecule.UpdatePropertyCache(strict=False)\n AllChem.FastFindRings(molecule)\n fingerprint = AllChe... | <|body_start_0|>
self.radius = radius
self.bits = bits
self.chirality = chirality
self.sanitize = sanitize
<|end_body_0|>
<|body_start_1|>
try:
molecule = Chem.MolFromSmiles(smiles, sanitize=self.sanitize)
if not self.sanitize:
molecule.Up... | Get fingerprints starting from SMILES. | SMILESToMorganFingerprints | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMILESToMorganFingerprints:
"""Get fingerprints starting from SMILES."""
def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None:
"""Initialize a SMILES to fingerprints object. Args: radius (int): radius of the fingerprints. bits (int): bits used to r... | stack_v2_sparse_classes_10k_train_007486 | 22,008 | permissive | [
{
"docstring": "Initialize a SMILES to fingerprints object. Args: radius (int): radius of the fingerprints. bits (int): bits used to represent the fingerprints.",
"name": "__init__",
"signature": "def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_004204 | Implement the Python class `SMILESToMorganFingerprints` described below.
Class description:
Get fingerprints starting from SMILES.
Method signatures and docstrings:
- def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None: Initialize a SMILES to fingerprints object. Args: radius (int... | Implement the Python class `SMILESToMorganFingerprints` described below.
Class description:
Get fingerprints starting from SMILES.
Method signatures and docstrings:
- def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None: Initialize a SMILES to fingerprints object. Args: radius (int... | 27ca3f8c5b5463cd081be5abdea04f5bfa076f39 | <|skeleton|>
class SMILESToMorganFingerprints:
"""Get fingerprints starting from SMILES."""
def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None:
"""Initialize a SMILES to fingerprints object. Args: radius (int): radius of the fingerprints. bits (int): bits used to r... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SMILESToMorganFingerprints:
"""Get fingerprints starting from SMILES."""
def __init__(self, radius: int=2, bits: int=512, chirality=True, sanitize=False) -> None:
"""Initialize a SMILES to fingerprints object. Args: radius (int): radius of the fingerprints. bits (int): bits used to represent the ... | the_stack_v2_python_sparse | pytoda/smiles/transforms.py | PaccMann/paccmann_datasets | train | 22 |
770bb01d6ee5335eaa2b75cfdb1c11c8a3b5a55f | [
"if not isinstance(p_object, FeedbackSet):\n raise ValueError('Appended object must be instance of FeedbackSet')\nsuper(FeedbackSetList, self).append(p_object)",
"best = None\nfor feedbackset in self:\n if not best:\n best = feedbackset\n elif best.grading_points < feedbackset.grading_points:\n ... | <|body_start_0|>
if not isinstance(p_object, FeedbackSet):
raise ValueError('Appended object must be instance of FeedbackSet')
super(FeedbackSetList, self).append(p_object)
<|end_body_0|>
<|body_start_1|>
best = None
for feedbackset in self:
if not best:
... | FeedbackSetList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
<|body_0|>
def get_feedbackset_with_most_points(self):
"""Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.Feedbac... | stack_v2_sparse_classes_10k_train_007487 | 21,904 | permissive | [
{
"docstring": "Args: p_object: Returns:",
"name": "append",
"signature": "def append(self, p_object)"
},
{
"docstring": "Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.FeedbackSet` or None.",
"name": "get_feedbac... | 2 | stack_v2_sparse_classes_30k_train_003354 | Implement the Python class `FeedbackSetList` described below.
Class description:
Implement the FeedbackSetList class.
Method signatures and docstrings:
- def append(self, p_object): Args: p_object: Returns:
- def get_feedbackset_with_most_points(self): Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with th... | Implement the Python class `FeedbackSetList` described below.
Class description:
Implement the FeedbackSetList class.
Method signatures and docstrings:
- def append(self, p_object): Args: p_object: Returns:
- def get_feedbackset_with_most_points(self): Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with th... | a3355fe78992466cfcae8b166128bf51ddbb26d0 | <|skeleton|>
class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
<|body_0|>
def get_feedbackset_with_most_points(self):
"""Get the :obj:`~.devilry.devilry_group.models.FeedbackSet` with the most points. Returns: :obj:`~.devilry.devilry_group.models.Feedbac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FeedbackSetList:
def append(self, p_object):
"""Args: p_object: Returns:"""
if not isinstance(p_object, FeedbackSet):
raise ValueError('Appended object must be instance of FeedbackSet')
super(FeedbackSetList, self).append(p_object)
def get_feedbackset_with_most_points(... | the_stack_v2_python_sparse | devilry/devilry_qualifiesforexam/utils/groups_groupedby_relatedstudent_and_assignments.py | devilry/devilry-django | train | 42 | |
417b9b528c2094cfe363a25775d3a80970f89dbf | [
"nums.sort()\nresults = []\nself.findNsum(nums, target, 4, [], results)\nreturn results",
"if len(nums) < N or N < 2:\n return\nif N == 2:\n l, r = (0, len(nums) - 1)\n while l < r:\n if nums[l] + nums[r] == target:\n results.append(result + [nums[l], nums[r]])\n l += 1\n ... | <|body_start_0|>
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
<|end_body_0|>
<|body_start_1|>
if len(nums) < N or N < 2:
return
if N == 2:
l, r = (0, len(nums) - 1)
while l < r:
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def findNsum(self, nums, target, N, result, results):
"""nums is a sorted arr"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_007488 | 2,791 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": "nums is a sorted arr",
"name": "findNsum",
"signature": "def findNsum(self, nums, target, N, result, results)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005337 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def findNsum(self, nums, target, N, result, results): nums is a sorted arr | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def findNsum(self, nums, target, N, result, results): nums is a sorted arr
<|s... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def findNsum(self, nums, target, N, result, results):
"""nums is a sorted arr"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
def findNsum(self, nums, target, N, result, results):
"""num... | the_stack_v2_python_sparse | Python/018__4Sum.py | FIRESTROM/Leetcode | train | 2 | |
b84b429655ea10b82dca273339ca87934dda9a5f | [
"if path_to_config.endswith('.json'):\n return self.parse_json_config(path_to_config)\nelse:\n return None",
"json_file = open(path_to_json_config)\njson_config = json.load(json_file)\njson_file.close()\nreturn json_config"
] | <|body_start_0|>
if path_to_config.endswith('.json'):
return self.parse_json_config(path_to_config)
else:
return None
<|end_body_0|>
<|body_start_1|>
json_file = open(path_to_json_config)
json_config = json.load(json_file)
json_file.close()
return... | The ConfigProvider provides the interface for getting the various config files i.e. via a path specification. | ConfigProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigProvider:
"""The ConfigProvider provides the interface for getting the various config files i.e. via a path specification."""
def get_config(self, path_to_config):
"""Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the co... | stack_v2_sparse_classes_10k_train_007489 | 1,014 | permissive | [
{
"docstring": "Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the config file. :return: config: (Dictionary) The parsed config.",
"name": "get_config",
"signature": "def get_config(self, path_to_config)"
},
{
"docstring": "Parses the con... | 2 | stack_v2_sparse_classes_30k_train_002204 | Implement the Python class `ConfigProvider` described below.
Class description:
The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.
Method signatures and docstrings:
- def get_config(self, path_to_config): Parses the config from a file with the path: path_to_c... | Implement the Python class `ConfigProvider` described below.
Class description:
The ConfigProvider provides the interface for getting the various config files i.e. via a path specification.
Method signatures and docstrings:
- def get_config(self, path_to_config): Parses the config from a file with the path: path_to_c... | 4bfea618727eb403e8b6f9863488e8b6e7d021cd | <|skeleton|>
class ConfigProvider:
"""The ConfigProvider provides the interface for getting the various config files i.e. via a path specification."""
def get_config(self, path_to_config):
"""Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConfigProvider:
"""The ConfigProvider provides the interface for getting the various config files i.e. via a path specification."""
def get_config(self, path_to_config):
"""Parses the config from a file with the path: path_to_config. :param path_to_config: (String) The path to the config file. :r... | the_stack_v2_python_sparse | ConfigInput_Component/ConfigProvider.py | BonifazStuhr/CSNN | train | 7 |
9c7759987f5b1a32aedf6cee1f23863d049d6cab | [
"with _Record.lock:\n with open(_Record.file, 'a+') as f:\n try:\n f.seek(0)\n r = json.load(f)\n except Exception as _:\n r = {}\n json.dump(r, f)\nreturn r",
"with _Record.lock:\n with open(_Record.file, 'r+') as f:\n r = json.load(f)\n ... | <|body_start_0|>
with _Record.lock:
with open(_Record.file, 'a+') as f:
try:
f.seek(0)
r = json.load(f)
except Exception as _:
r = {}
json.dump(r, f)
return r
<|end_body_0|>
<|bod... | Default tasks record handler Will read/write from/to ./tasks.json | _Record | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
<|body_0|>
def write(name, le):
"""Writes record to record_handler name (str): name of task le (str): str() cast of da... | stack_v2_sparse_classes_10k_train_007490 | 13,873 | permissive | [
{
"docstring": "Reads persistence record to dict Returns dict",
"name": "read",
"signature": "def read()"
},
{
"docstring": "Writes record to record_handler name (str): name of task le (str): str() cast of datetime.datetime object for last execution Does not return",
"name": "write",
"si... | 2 | stack_v2_sparse_classes_30k_train_001693 | Implement the Python class `_Record` described below.
Class description:
Default tasks record handler Will read/write from/to ./tasks.json
Method signatures and docstrings:
- def read(): Reads persistence record to dict Returns dict
- def write(name, le): Writes record to record_handler name (str): name of task le (s... | Implement the Python class `_Record` described below.
Class description:
Default tasks record handler Will read/write from/to ./tasks.json
Method signatures and docstrings:
- def read(): Reads persistence record to dict Returns dict
- def write(name, le): Writes record to record_handler name (str): name of task le (s... | 6c42679cc129656e9216fc847e5839d6496dc452 | <|skeleton|>
class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
<|body_0|>
def write(name, le):
"""Writes record to record_handler name (str): name of task le (str): str() cast of da... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _Record:
"""Default tasks record handler Will read/write from/to ./tasks.json"""
def read():
"""Reads persistence record to dict Returns dict"""
with _Record.lock:
with open(_Record.file, 'a+') as f:
try:
f.seek(0)
r = js... | the_stack_v2_python_sparse | lib/cherrypyscheduler.py | sinopsysHK/Watcher3 | train | 0 |
3cf1996c512d8f3da3a5622bcca33848d0a93395 | [
"def invert(node):\n node.left, node.right = (node.right, node.left)\n if node.left:\n invert(node.left)\n if node.right:\n invert(node.right)\ninvert(root)\nreturn root",
"def invert(node) -> TreeNode:\n node_copy = TreeNode(node.val)\n if node.left:\n node_copy.right = invert... | <|body_start_0|>
def invert(node):
node.left, node.right = (node.right, node.left)
if node.left:
invert(node.left)
if node.right:
invert(node.right)
invert(root)
return root
<|end_body_0|>
<|body_start_1|>
def invert(no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree_v1(self, root: TreeNode) -> TreeNode:
"""Invert in place ."""
<|body_0|>
def invertTree_v2(self, root: TreeNode) -> TreeNode:
"""Clone and invert."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def invert(node):
... | stack_v2_sparse_classes_10k_train_007491 | 2,223 | no_license | [
{
"docstring": "Invert in place .",
"name": "invertTree_v1",
"signature": "def invertTree_v1(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "Clone and invert.",
"name": "invertTree_v2",
"signature": "def invertTree_v2(self, root: TreeNode) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_005551 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree_v1(self, root: TreeNode) -> TreeNode: Invert in place .
- def invertTree_v2(self, root: TreeNode) -> TreeNode: Clone and invert. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree_v1(self, root: TreeNode) -> TreeNode: Invert in place .
- def invertTree_v2(self, root: TreeNode) -> TreeNode: Clone and invert.
<|skeleton|>
class Solution:
... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def invertTree_v1(self, root: TreeNode) -> TreeNode:
"""Invert in place ."""
<|body_0|>
def invertTree_v2(self, root: TreeNode) -> TreeNode:
"""Clone and invert."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree_v1(self, root: TreeNode) -> TreeNode:
"""Invert in place ."""
def invert(node):
node.left, node.right = (node.right, node.left)
if node.left:
invert(node.left)
if node.right:
invert(node.right)
... | the_stack_v2_python_sparse | python3/trees_and_graphs/invert_tree.py | victorchu/algorithms | train | 0 | |
79642d78bdfc4b8895089edb0cd6edcda84ff165 | [
"key = a2b_p('2b7e151628aed2a6abf7158809cf4f3c')\npt = 'This is a test case'\nalg1 = CBC(Rijndael(key, blockSize=32))\nalg2 = CBC(Rijndael(key, blockSize=32))\nct1 = alg1.encrypt(pt)\nct2 = alg2.encrypt(pt)\nself.assertNotEqual(ct1, ct2)",
"key = a2b_p('2b7e151628aed2a6abf7158809cf4f3c')\npt = 'This is yet anothe... | <|body_start_0|>
key = a2b_p('2b7e151628aed2a6abf7158809cf4f3c')
pt = 'This is a test case'
alg1 = CBC(Rijndael(key, blockSize=32))
alg2 = CBC(Rijndael(key, blockSize=32))
ct1 = alg1.encrypt(pt)
ct2 = alg2.encrypt(pt)
self.assertNotEqual(ct1, ct2)
<|end_body_0|>
... | CBC IV tests | CBC_Auto_IV_Test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CBC_Auto_IV_Test:
"""CBC IV tests"""
def testIVuniqueness(self):
"""Test that two different instances have different IVs"""
<|body_0|>
def testIVmultencryptUnique(self):
"""Test that two different encrypts have different IVs"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k_train_007492 | 5,430 | permissive | [
{
"docstring": "Test that two different instances have different IVs",
"name": "testIVuniqueness",
"signature": "def testIVuniqueness(self)"
},
{
"docstring": "Test that two different encrypts have different IVs",
"name": "testIVmultencryptUnique",
"signature": "def testIVmultencryptUniq... | 2 | stack_v2_sparse_classes_30k_train_001844 | Implement the Python class `CBC_Auto_IV_Test` described below.
Class description:
CBC IV tests
Method signatures and docstrings:
- def testIVuniqueness(self): Test that two different instances have different IVs
- def testIVmultencryptUnique(self): Test that two different encrypts have different IVs | Implement the Python class `CBC_Auto_IV_Test` described below.
Class description:
CBC IV tests
Method signatures and docstrings:
- def testIVuniqueness(self): Test that two different instances have different IVs
- def testIVmultencryptUnique(self): Test that two different encrypts have different IVs
<|skeleton|>
cla... | ed4d80d1e6f09634c12c0c3096e39667c6642b95 | <|skeleton|>
class CBC_Auto_IV_Test:
"""CBC IV tests"""
def testIVuniqueness(self):
"""Test that two different instances have different IVs"""
<|body_0|>
def testIVmultencryptUnique(self):
"""Test that two different encrypts have different IVs"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CBC_Auto_IV_Test:
"""CBC IV tests"""
def testIVuniqueness(self):
"""Test that two different instances have different IVs"""
key = a2b_p('2b7e151628aed2a6abf7158809cf4f3c')
pt = 'This is a test case'
alg1 = CBC(Rijndael(key, blockSize=32))
alg2 = CBC(Rijndael(key, b... | the_stack_v2_python_sparse | script.module.cryptolib/lib/cryptopy/cipher/cbc_test.py | gacj22/WizardGacj22 | train | 4 |
2895520e72ab70b2b5b438dc036517858b6d8e96 | [
"err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'\nerr_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'\nif not isinstance(style_image, np.ndarray):\n raise TypeError(err_m1)\nif len(style_image.shape) != 3 or style_image.shape[2] != 3:\n raise TypeError(err_m1)\nif not isi... | <|body_start_0|>
err_m1 = 'style_image must be a numpy.ndarray with shape (h, w, 3)'
err_m2 = 'content_image must be a numpy.ndarray with shape (h, w, 3)'
if not isinstance(style_image, np.ndarray):
raise TypeError(err_m1)
if len(style_image.shape) != 3 or style_image.shape[2... | Performs task for neural style transfer | NST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_10k_train_007493 | 2,925 | no_license | [
{
"docstring": "constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for style cost",
"name": "__init__",
"signature": "def __init__(self, style_image, content_image, alpha=10000.0, beta=1)"... | 2 | stack_v2_sparse_classes_30k_train_005303 | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | Implement the Python class `NST` described below.
Class description:
Performs task for neural style transfer
Method signatures and docstrings:
- def __init__(self, style_image, content_image, alpha=10000.0, beta=1): constructor @style_image: image used as style reference, np.ndarray @content_image: image used as cont... | e20b284d5f1841952104d7d9a0274cff80eb304d | <|skeleton|>
class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NST:
"""Performs task for neural style transfer"""
def __init__(self, style_image, content_image, alpha=10000.0, beta=1):
"""constructor @style_image: image used as style reference, np.ndarray @content_image: image used as content ref., np.ndarray @alpha: weight for style cost @beta: weight for s... | the_stack_v2_python_sparse | supervised_learning/0x0C-neural_style_transfer/0-neural_style.py | jgadelugo/holbertonschool-machine_learning | train | 1 |
6b748f62e90fb0d4adcfa1ef134567b23dc609be | [
"input_ts = random_data.create_random_ts(n_ts=5, n_req=3, n_hist=7, max_length=2000, min_length=200)\nwrite_data_to_iot_format.write_ts(input_ts, FILE_NAME)\ndata, metric_ids, host_ids, header_names = get_iot_data.get_data(FILE_NAME, [], True)\nos.remove(FILE_NAME)\nwith self.assertRaises(IndexError) as e:\n ts_... | <|body_start_0|>
input_ts = random_data.create_random_ts(n_ts=5, n_req=3, n_hist=7, max_length=2000, min_length=200)
write_data_to_iot_format.write_ts(input_ts, FILE_NAME)
data, metric_ids, host_ids, header_names = get_iot_data.get_data(FILE_NAME, [], True)
os.remove(FILE_NAME)
w... | TestIotData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestIotData:
def test_read_empty_lines(self):
"""Checks results of reading empty lines"""
<|body_0|>
def test_read_empty_dataset(self):
"""Checks results of reading empty dataset"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
input_ts = random_data... | stack_v2_sparse_classes_10k_train_007494 | 4,254 | no_license | [
{
"docstring": "Checks results of reading empty lines",
"name": "test_read_empty_lines",
"signature": "def test_read_empty_lines(self)"
},
{
"docstring": "Checks results of reading empty dataset",
"name": "test_read_empty_dataset",
"signature": "def test_read_empty_dataset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001813 | Implement the Python class `TestIotData` described below.
Class description:
Implement the TestIotData class.
Method signatures and docstrings:
- def test_read_empty_lines(self): Checks results of reading empty lines
- def test_read_empty_dataset(self): Checks results of reading empty dataset | Implement the Python class `TestIotData` described below.
Class description:
Implement the TestIotData class.
Method signatures and docstrings:
- def test_read_empty_lines(self): Checks results of reading empty lines
- def test_read_empty_dataset(self): Checks results of reading empty dataset
<|skeleton|>
class Test... | 7ed73b0db340b0f54cbc68a6ea02b95df45bc30e | <|skeleton|>
class TestIotData:
def test_read_empty_lines(self):
"""Checks results of reading empty lines"""
<|body_0|>
def test_read_empty_dataset(self):
"""Checks results of reading empty dataset"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestIotData:
def test_read_empty_lines(self):
"""Checks results of reading empty lines"""
input_ts = random_data.create_random_ts(n_ts=5, n_req=3, n_hist=7, max_length=2000, min_length=200)
write_data_to_iot_format.write_ts(input_ts, FILE_NAME)
data, metric_ids, host_ids, heade... | the_stack_v2_python_sparse | python-code/UnitTests/test_iot_data.py | Strijov/Multiscale | train | 3 | |
2341d025b8c354ff101edee1828e1c4e6c1972e4 | [
"super().__init__()\nself.strategy: Strategy = Strategy()\nif data.get('strategy'):\n self.strategy = Strategy(data.get('strategy', {}))\nself.accuracy_criterion: AccCriterion = AccCriterion(data.get('accuracy_criterion', {}))\nself.objective: Optional[str] = data.get('objective', None)\nself.exit_policy: Option... | <|body_start_0|>
super().__init__()
self.strategy: Strategy = Strategy()
if data.get('strategy'):
self.strategy = Strategy(data.get('strategy', {}))
self.accuracy_criterion: AccCriterion = AccCriterion(data.get('accuracy_criterion', {}))
self.objective: Optional[str] ... | Configuration Tuning class. | Tuning | [
"MIT",
"Intel",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tuning:
"""Configuration Tuning class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Tuning class."""
<|body_0|>
def set_timeout(self, timeout: int) -> None:
"""Update tuning timeout in config."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k_train_007495 | 5,856 | permissive | [
{
"docstring": "Initialize Configuration Tuning class.",
"name": "__init__",
"signature": "def __init__(self, data: Dict[str, Any]={}) -> None"
},
{
"docstring": "Update tuning timeout in config.",
"name": "set_timeout",
"signature": "def set_timeout(self, timeout: int) -> None"
},
{... | 5 | stack_v2_sparse_classes_30k_train_007021 | Implement the Python class `Tuning` described below.
Class description:
Configuration Tuning class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Tuning class.
- def set_timeout(self, timeout: int) -> None: Update tuning timeout in config.
- def set_... | Implement the Python class `Tuning` described below.
Class description:
Configuration Tuning class.
Method signatures and docstrings:
- def __init__(self, data: Dict[str, Any]={}) -> None: Initialize Configuration Tuning class.
- def set_timeout(self, timeout: int) -> None: Update tuning timeout in config.
- def set_... | 3976edc4215398e69ce0213f87ec295f5dc96e0e | <|skeleton|>
class Tuning:
"""Configuration Tuning class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Tuning class."""
<|body_0|>
def set_timeout(self, timeout: int) -> None:
"""Update tuning timeout in config."""
<|body_1|>
def ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tuning:
"""Configuration Tuning class."""
def __init__(self, data: Dict[str, Any]={}) -> None:
"""Initialize Configuration Tuning class."""
super().__init__()
self.strategy: Strategy = Strategy()
if data.get('strategy'):
self.strategy = Strategy(data.get('strat... | the_stack_v2_python_sparse | neural_compressor/ux/utils/workload/tuning.py | Skp80/neural-compressor | train | 0 |
dc7c082da76ead298ccbcb1cac104e2f0ae5a092 | [
"if not a:\n return 0\np = deque()\nq = deque()\nt = float('-inf')\nm = float('-inf')\nn = len(a)\nfor i in range(0, n, 1):\n if not q or a[i] > q[-1]:\n p.append(i)\n q.append(a[i])\n elif a[i] < q[-1]:\n while q and a[i] < q[-1]:\n x = p.pop()\n y = q.pop()\n ... | <|body_start_0|>
if not a:
return 0
p = deque()
q = deque()
t = float('-inf')
m = float('-inf')
n = len(a)
for i in range(0, n, 1):
if not q or a[i] > q[-1]:
p.append(i)
q.append(a[i])
elif a[i] <... | Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized collect all array elements and indicies in stacks | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized collect all array elements and indicies... | stack_v2_sparse_classes_10k_train_007496 | 4,337 | permissive | [
{
"docstring": "Determines area of maximum rectangle in histogram. :param list[int] a: list of height values in histogram :return: area of maximum rectangle :rtype: int",
"name": "largest_rectangle_area",
"signature": "def largest_rectangle_area(self, a)"
},
{
"docstring": "Calculates maximum ar... | 2 | stack_v2_sparse_classes_30k_train_001755 | Implement the Python class `Solution` described below.
Class description:
Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized ... | Implement the Python class `Solution` described below.
Class description:
Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized ... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized collect all array elements and indicies... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Iteration over all array elements. Interpolates greedy algorithm. Reference: https://www.youtube.com/watch?v=VNbkzsnllsU Time complexity: O(n) - Iterate over all array indicies and collected index-height pairs Space complexity: O(n) - Amortized collect all array elements and indicies in stacks"""... | the_stack_v2_python_sparse | 0084_largest_rectangle_histogram/python_source.py | arthurdysart/LeetCode | train | 0 |
2fb06516b2ace1f47ffc127afe636bb07667c911 | [
"try:\n minTimestamp = int(self.request.query_params.get('minTimestamp', ''))\n maxTimestamp = int(self.request.query_params.get('maxTimestamp', ''))\n if minTimestamp and maxTimestamp:\n return UrlData.objects.filter(timestamp__range=[minTimestamp, maxTimestamp], category__isnull=False).order_by('t... | <|body_start_0|>
try:
minTimestamp = int(self.request.query_params.get('minTimestamp', ''))
maxTimestamp = int(self.request.query_params.get('maxTimestamp', ''))
if minTimestamp and maxTimestamp:
return UrlData.objects.filter(timestamp__range=[minTimestamp, ma... | 根据timestamp区间范围获取分类情况 | TitleCategoryList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TitleCategoryList:
"""根据timestamp区间范围获取分类情况"""
def get_queryset(self):
"""根据时间戳返回记录 :return:"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""返回横轴+数据 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_10k_train_007497 | 7,395 | permissive | [
{
"docstring": "根据时间戳返回记录 :return:",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docstring": "返回横轴+数据 :param request: :param args: :param kwargs: :return:",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006388 | Implement the Python class `TitleCategoryList` described below.
Class description:
根据timestamp区间范围获取分类情况
Method signatures and docstrings:
- def get_queryset(self): 根据时间戳返回记录 :return:
- def list(self, request, *args, **kwargs): 返回横轴+数据 :param request: :param args: :param kwargs: :return: | Implement the Python class `TitleCategoryList` described below.
Class description:
根据timestamp区间范围获取分类情况
Method signatures and docstrings:
- def get_queryset(self): 根据时间戳返回记录 :return:
- def list(self, request, *args, **kwargs): 返回横轴+数据 :param request: :param args: :param kwargs: :return:
<|skeleton|>
class TitleCate... | 67d04f83d6cf69b7efc351f473b125b029551cb1 | <|skeleton|>
class TitleCategoryList:
"""根据timestamp区间范围获取分类情况"""
def get_queryset(self):
"""根据时间戳返回记录 :return:"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""返回横轴+数据 :param request: :param args: :param kwargs: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TitleCategoryList:
"""根据timestamp区间范围获取分类情况"""
def get_queryset(self):
"""根据时间戳返回记录 :return:"""
try:
minTimestamp = int(self.request.query_params.get('minTimestamp', ''))
maxTimestamp = int(self.request.query_params.get('maxTimestamp', ''))
if minTimest... | the_stack_v2_python_sparse | WorkStatusForNetTrafficWithDjango/WorkStatusForNetTrafficWithDjango/dashboard/restViews.py | Ayi-/WorkStatusForNetTrafficMonitorAndClassify | train | 0 |
fac5cb7fec6bd3148cabcc36b2632d410ff9a1a2 | [
"indy_config = IndyWalletConfig(config)\nopened = await indy_config.create_wallet()\nreturn IndySdkProfile(opened, context)",
"warnings.warn('Indy wallet type is deprecated, use Askar instead; see: https://aca-py.org/main/deploying/IndySDKtoAskarMigration/', DeprecationWarning)\nLOGGER.warning('Indy wallet type i... | <|body_start_0|>
indy_config = IndyWalletConfig(config)
opened = await indy_config.create_wallet()
return IndySdkProfile(opened, context)
<|end_body_0|>
<|body_start_1|>
warnings.warn('Indy wallet type is deprecated, use Askar instead; see: https://aca-py.org/main/deploying/IndySDKtoAsk... | Manager for Indy-SDK wallets. | IndySdkProfileManager | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
<|body_0|>
async def open(self, context: InjectionContext, config: Map... | stack_v2_sparse_classes_10k_train_007498 | 8,718 | permissive | [
{
"docstring": "Provision a new instance of a profile.",
"name": "provision",
"signature": "async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile"
},
{
"docstring": "Open an instance of an existing profile.",
"name": "open",
"signature": "async d... | 2 | null | Implement the Python class `IndySdkProfileManager` described below.
Class description:
Manager for Indy-SDK wallets.
Method signatures and docstrings:
- async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile: Provision a new instance of a profile.
- async def open(self, contex... | Implement the Python class `IndySdkProfileManager` described below.
Class description:
Manager for Indy-SDK wallets.
Method signatures and docstrings:
- async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile: Provision a new instance of a profile.
- async def open(self, contex... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
<|body_0|>
async def open(self, context: InjectionContext, config: Map... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
indy_config = IndyWalletConfig(config)
opened = await indy_config.create_wallet(... | the_stack_v2_python_sparse | aries_cloudagent/indy/sdk/profile.py | hyperledger/aries-cloudagent-python | train | 370 |
85595bfaf85f7fa65e8737348abe471bc5559a59 | [
"self._vgg = tf.keras.applications.VGG19(include_top=False, weights=weights)\nself._vgg.trainable = False\nself._layers = layers\nself._weights = layer_weights\noutput_names = layers\noutputs = [self._vgg.get_layer(name).output for name in output_names]\nself._model = tf.keras.Model([self._vgg.input], outputs)",
... | <|body_start_0|>
self._vgg = tf.keras.applications.VGG19(include_top=False, weights=weights)
self._vgg.trainable = False
self._layers = layers
self._weights = layer_weights
output_names = layers
outputs = [self._vgg.get_layer(name).output for name in output_names]
... | A VGG losss class. | VGGLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
<|body_0|>
def... | stack_v2_sparse_classes_10k_train_007499 | 1,984 | permissive | [
{
"docstring": "Initializes the VGG network.",
"name": "__init__",
"signature": "def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0))"
},
{
"docstring": "Computes... | 2 | stack_v2_sparse_classes_30k_train_006994 | Implement the Python class `VGGLoss` described below.
Class description:
A VGG losss class.
Method signatures and docstrings:
- def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)): In... | Implement the Python class `VGGLoss` described below.
Class description:
A VGG losss class.
Method signatures and docstrings:
- def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)): In... | a9a6643968a7b6b29cab3b53b73ab80d14fb32b7 | <|skeleton|>
class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
<|body_0|>
def... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VGGLoss:
"""A VGG losss class."""
def __init__(self, weights='imagenet', layers=('block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1', 'block5_conv1'), layer_weights=(1.0 / 32, 1.0 / 16, 1.0 / 8, 1.0 / 4, 1.0)):
"""Initializes the VGG network."""
self._vgg = tf.keras.application... | the_stack_v2_python_sparse | losses/vgg_loss.py | czero69/lsr | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.