blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32a21addfbb1d488d95643e6e418a4ce4cac8cfe | [
"self.sensor = Sensor('127.0.0.1', 8000)\nself.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(10, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=11.3)\nself.pump.get_state = MagicMock(return_value='PUMP_IN')\nself.pump.set_state = ... | <|body_start_0|>
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=11.3)
... | Module tests for the water-regulation module | ModuleTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sensor = ... | stack_v2_sparse_classes_36k_train_029400 | 956 | no_license | [
{
"docstring": "Set up controller for test",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test controller tick method",
"name": "test_controller",
"signature": "def test_controller(self)"
}
] | 2 | null | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method | Implement the Python class `ModuleTests` described below.
Class description:
Module tests for the water-regulation module
Method signatures and docstrings:
- def setUp(self): Set up controller for test
- def test_controller(self): test controller tick method
<|skeleton|>
class ModuleTests:
"""Module tests for th... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
<|body_0|>
def test_controller(self):
"""test controller tick method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleTests:
"""Module tests for the water-regulation module"""
def setUp(self):
"""Set up controller for test"""
self.sensor = Sensor('127.0.0.1', 8000)
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(10, 0.05)
self.controller = Controller(self.sensor, ... | the_stack_v2_python_sparse | students/smitco/lesson06/waterregulation/integrationtest.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
2ab61fae1a943af8224ac40fbedbbf8868cf272b | [
"i = 0\nwhile i ** 2 <= x:\n i += 1\nreturn i if i ** 2 == x else i - 1",
"left, right = (0, x)\nwhile left <= right:\n mid = left + (right - left) // 2\n if mid ** 2 < x:\n left = mid + 1\n elif mid ** 2 > x:\n right = mid - 1\n else:\n return mid\nreturn right",
"y = x\nwhi... | <|body_start_0|>
i = 0
while i ** 2 <= x:
i += 1
return i if i ** 2 == x else i - 1
<|end_body_0|>
<|body_start_1|>
left, right = (0, x)
while left <= right:
mid = left + (right - left) // 2
if mid ** 2 < x:
left = mid + 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x: int) -> int:
"""执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3... | stack_v2_sparse_classes_36k_train_029401 | 2,069 | no_license | [
{
"docstring": "执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
},
{
"docstring": "执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3 提交中击败了5.20%的用户 思路:二分法 :... | 3 | stack_v2_sparse_classes_30k_train_005628 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:
- def mySqrt2(self, x: int) -> int: 执行用时 :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:
- def mySqrt2(self, x: int) -> int: 执行用时 :... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
<|body_0|>
def mySqrt2(self, x: int) -> int:
"""执行用时 :44 ms, 在所有 Python3 提交中击败了66.27%的用户 内存消耗 :13.7 MB, 在所有 Python3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mySqrt(self, x: int) -> int:
"""执行用时 :8272 ms, 在所有 Python3 提交中击败了5.01%的用户 内存消耗 :13.6 MB, 在所有 Python3 提交中击败了5.09%的用户 :param x: :return:"""
i = 0
while i ** 2 <= x:
i += 1
return i if i ** 2 == x else i - 1
def mySqrt2(self, x: int) -> int:
... | the_stack_v2_python_sparse | LeetCode/数学/69. Sqrt(x).py | yiming1012/MyLeetCode | train | 2 | |
f2fc41d312acec66667a9d52162ca4663649520b | [
"def rserialize(root, string):\n if root == None:\n string += '# '\n else:\n string += str(root.val) + ' '\n string = rserialize(root.left, string)\n string = rserialize(root.right, string)\n return string\nstring = rserialize(root, '')\nreturn string",
"def rdeserialize(l):\n... | <|body_start_0|>
def rserialize(root, string):
if root == None:
string += '# '
else:
string += str(root.val) + ' '
string = rserialize(root.left, string)
string = rserialize(root.right, string)
return string
... | Codec | [
"Apache-2.0"
] | 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_36k_train_029402 | 1,755 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_009235 | 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:... | fb3fa6df7c77feb2d252feea7f3507569e057c70 | <|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_36k | 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 rserialize(root, string):
if root == None:
string += '# '
else:
string += str(root.val) + ' '
string = rserial... | the_stack_v2_python_sparse | 297/serializeanddeserializebinarytree.py | cccccccccccccc/Myleetcode | train | 0 | |
2dc40208b16f0879fbecedc907edb8f2773610f2 | [
"self.capacity = capacity\nself.lru_dict = defaultdict()\nself.length = 0\nself.index_cache = defaultdict(list)\nself.index_cache[-1] = [-1, -1]\nself.last_key = -1",
"value = self.lru_dict.get(key, -1)\nif value >= 0 and self.last_key != key:\n prev_key = self.index_cache[key][0]\n next_key = self.index_ca... | <|body_start_0|>
self.capacity = capacity
self.lru_dict = defaultdict()
self.length = 0
self.index_cache = defaultdict(list)
self.index_cache[-1] = [-1, -1]
self.last_key = -1
<|end_body_0|>
<|body_start_1|>
value = self.lru_dict.get(key, -1)
if value >= ... | Class for LRU cache | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
"""Class for LRU cache"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"... | stack_v2_sparse_classes_36k_train_029403 | 2,405 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_006276 | Implement the Python class `LRUCache` described below.
Class description:
Class for LRU cache
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Class for LRU cache
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|skeleton|>
c... | 009484a2bb80fed61970558a72670d66d9b71b6b | <|skeleton|>
class LRUCache:
"""Class for LRU cache"""
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
"""Class for LRU cache"""
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.lru_dict = defaultdict()
self.length = 0
self.index_cache = defaultdict(list)
self.index_cache[-1] = [-1, -1]
self.last_key = -... | the_stack_v2_python_sparse | lru_cache_alt.py | at3103/Leetcode | train | 0 |
3b690eaab13796b84d1a7a3f1ef2af45c3ce1eb1 | [
"self.full_file_checks = [self.check_for_double_syntax]\nself.line_checks = [self.check_for_noreturn]\nself.replace = replace",
"if os.path.join('praw', 'const.py') in filename:\n return True\nnew_content = re.sub('(^|\\\\s)/(u|r)/', '\\\\1\\\\2/', content)\nif content == new_content:\n return True\nif self... | <|body_start_0|>
self.full_file_checks = [self.check_for_double_syntax]
self.line_checks = [self.check_for_noreturn]
self.replace = replace
<|end_body_0|>
<|body_start_1|>
if os.path.join('praw', 'const.py') in filename:
return True
new_content = re.sub('(^|\\s)/(u|r... | Run simple checks on the entire document or specific lines. | StaticChecker | [
"GPL-3.0-only",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticChecker:
"""Run simple checks on the entire document or specific lines."""
def __init__(self, replace: bool) -> None:
"""Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements."""
<|body_0|>
def check_for_double_syntax(se... | stack_v2_sparse_classes_36k_train_029404 | 5,054 | permissive | [
{
"docstring": "Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements.",
"name": "__init__",
"signature": "def __init__(self, replace: bool) -> None"
},
{
"docstring": "Checks a file for double-slash statements (``/r/`` and ``/u/``). :param filename: ... | 4 | stack_v2_sparse_classes_30k_test_000561 | Implement the Python class `StaticChecker` described below.
Class description:
Run simple checks on the entire document or specific lines.
Method signatures and docstrings:
- def __init__(self, replace: bool) -> None: Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements.
... | Implement the Python class `StaticChecker` described below.
Class description:
Run simple checks on the entire document or specific lines.
Method signatures and docstrings:
- def __init__(self, replace: bool) -> None: Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements.
... | f1d5506b7a3df240f748e1b7749fd5636aa67b32 | <|skeleton|>
class StaticChecker:
"""Run simple checks on the entire document or specific lines."""
def __init__(self, replace: bool) -> None:
"""Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements."""
<|body_0|>
def check_for_double_syntax(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticChecker:
"""Run simple checks on the entire document or specific lines."""
def __init__(self, replace: bool) -> None:
"""Initialize a :class:`.StaticChecker` instance. :param replace: Whether or not to make replacements."""
self.full_file_checks = [self.check_for_double_syntax]
... | the_stack_v2_python_sparse | tools/static_word_checks.py | praw-dev/praw | train | 2,825 |
7ce2c670676ecf81843da0a2677a1db85b021ceb | [
"super().__init__()\nself.hidden_size = hidden_size\nself.k = k\nself.bridge_size = bridge_size\nself.attn_scale = np.sqrt(np.sqrt(self.bridge_size))\nself.W1 = torch.nn.Linear(hidden_size, bridge_size, bias=False)\nself.W2 = torch.nn.Linear(bridge_size, k, bias=False)\nself.act = torch.nn.ReLU()",
"attention_sco... | <|body_start_0|>
super().__init__()
self.hidden_size = hidden_size
self.k = k
self.bridge_size = bridge_size
self.attn_scale = np.sqrt(np.sqrt(self.bridge_size))
self.W1 = torch.nn.Linear(hidden_size, bridge_size, bias=False)
self.W2 = torch.nn.Linear(bridge_size,... | A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf | AttentionBridge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidde... | stack_v2_sparse_classes_36k_train_029405 | 12,242 | permissive | [
{
"docstring": "hidden_size - size of input hidden state k - number of attention heads bridge_size - size of internal feed forward weights (i.e., attention head size)",
"name": "__init__",
"signature": "def __init__(self, hidden_size, k, bridge_size)"
},
{
"docstring": "Project hidden [B x N x H... | 2 | stack_v2_sparse_classes_30k_train_007110 | Implement the Python class `AttentionBridge` described below.
Class description:
A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf
Method signatures and docstrings:
- def __init__(self, hidden... | Implement the Python class `AttentionBridge` described below.
Class description:
A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf
Method signatures and docstrings:
- def __init__(self, hidden... | c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7 | <|skeleton|>
class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidde... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AttentionBridge:
"""A multi-head attention bridge to project a variable-size hidden states to k hidden states (per attention head). Code is based on the paper https://arxiv.org/pdf/1703.03130.pdf"""
def __init__(self, hidden_size, k, bridge_size):
"""hidden_size - size of input hidden state k - n... | the_stack_v2_python_sparse | nemo/collections/nlp/modules/common/transformer/transformer_modules.py | NVIDIA/NeMo | train | 7,957 |
cb28f6331ad7bdb320ebea55fd4badfc276c63cc | [
"data = json.load(f) or []\nnow = time.time()\nfor cookie in map(go_to_py_cookie, data):\n if not ignore_expires and cookie.is_expired(now):\n continue\n self.set_cookie(cookie)",
"if filename is None:\n if self.filename is not None:\n filename = self.filename\n else:\n raise Valu... | <|body_start_0|>
data = json.load(f) or []
now = time.time()
for cookie in map(go_to_py_cookie, data):
if not ignore_expires and cookie.is_expired(now):
continue
self.set_cookie(cookie)
<|end_body_0|>
<|body_start_1|>
if filename is None:
... | A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar. | GoCookieJar | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called b... | stack_v2_sparse_classes_36k_train_029406 | 3,755 | permissive | [
{
"docstring": "Implement the _really_load method called by FileCookieJar to implement the actual cookie loading",
"name": "_really_load",
"signature": "def _really_load(self, f, filename, ignore_discard, ignore_expires)"
},
{
"docstring": "Implement the FileCookieJar abstract method.",
"nam... | 2 | stack_v2_sparse_classes_30k_train_017328 | Implement the Python class `GoCookieJar` described below.
Class description:
A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar.
Method signatures and docstrings:
- def _really_load(self, f, filename, ignore_discard, ig... | Implement the Python class `GoCookieJar` described below.
Class description:
A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar.
Method signatures and docstrings:
- def _really_load(self, f, filename, ignore_discard, ig... | f21bc426952579efb980439f6a07d59bcb4cce0b | <|skeleton|>
class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoCookieJar:
"""A CookieJar implementation that reads and writes cookies to the cookiejar format as understood by the Go package github.com/juju/persistent-cookiejar."""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
"""Implement the _really_load method called by FileCookieJ... | the_stack_v2_python_sparse | juju/client/gocookies.py | juju/python-libjuju | train | 63 |
ee6cf268644065e2e2e4a39c410bdb0ea77118c3 | [
"while True:\n num = (rand7() - 1) * 7 + rand7()\n if num <= 40:\n return num % 10 + 1",
"while True:\n num = (rand7() - 1) * 7 + rand7()\n if num <= 40:\n return num % 10 + 1\n rand9 = num - 40\n num = (rand9 - 1) * 7 + rand7()\n if num <= 60:\n return num % 10 + 1\n ... | <|body_start_0|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
<|end_body_0|>
<|body_start_1|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
ra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 1... | stack_v2_sparse_classes_36k_train_029407 | 1,066 | no_license | [
{
"docstring": "拒绝采样",
"name": "rand10",
"signature": "def rand10(self)"
},
{
"docstring": "拒绝采样-减少舍弃数字",
"name": "rand10_new",
"signature": "def rand10_new(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000458 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10(self): 拒绝采样
- def rand10_new(self): 拒绝采样-减少舍弃数字
<|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
... | 52756b30e9d51794591aca030bc918e707f473f1 | <|skeleton|>
class Solution:
def rand10(self):
"""拒绝采样"""
<|body_0|>
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rand10(self):
"""拒绝采样"""
while True:
num = (rand7() - 1) * 7 + rand7()
if num <= 40:
return num % 10 + 1
def rand10_new(self):
"""拒绝采样-减少舍弃数字"""
while True:
num = (rand7() - 1) * 7 + rand7()
if n... | the_stack_v2_python_sparse | 470.用 Rand7() 实现 Rand10()/solution.py | QtTao/daily_leetcode | train | 0 | |
e71350c8184044e92417aea63d480cf382ff0cce | [
"self.name = name\nself.train = train\nself.valid = valid\nself.test = test\nself.questions = questions\nself.answers = answers\nself.additional_answers = additional_answers or []\nself.generated_questions = generated_questions or dict()",
"name = '{}+{}'.format(self.name, other_archive.name)\ntrain = self.train.... | <|body_start_0|>
self.name = name
self.train = train
self.valid = valid
self.test = test
self.questions = questions
self.answers = answers
self.additional_answers = additional_answers or []
self.generated_questions = generated_questions or dict()
<|end_bod... | Archive | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Archive:
def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None):
""":type name: str :type train: Data :type valid: Data :type test: list[Data] :type questions: list[TexItem] :type answers: list[TexItem]"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_029408 | 3,465 | permissive | [
{
"docstring": ":type name: str :type train: Data :type valid: Data :type test: list[Data] :type questions: list[TexItem] :type answers: list[TexItem]",
"name": "__init__",
"signature": "def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None)"
... | 3 | null | Implement the Python class `Archive` described below.
Class description:
Implement the Archive class.
Method signatures and docstrings:
- def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None): :type name: str :type train: Data :type valid: Data :type test:... | Implement the Python class `Archive` described below.
Class description:
Implement the Archive class.
Method signatures and docstrings:
- def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None): :type name: str :type train: Data :type valid: Data :type test:... | 17a9d97c2414666fcc08015a58619fe9722daf2b | <|skeleton|>
class Archive:
def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None):
""":type name: str :type train: Data :type valid: Data :type test: list[Data] :type questions: list[TexItem] :type answers: list[TexItem]"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Archive:
def __init__(self, name, train, valid, test, questions, answers, additional_answers=None, generated_questions=None):
""":type name: str :type train: Data :type valid: Data :type test: list[Data] :type questions: list[TexItem] :type answers: list[TexItem]"""
self.name = name
se... | the_stack_v2_python_sparse | bert-training/experiment/qa/data/models.py | UKPLab/emnlp2019-duplicate_question_detection | train | 7 | |
286caddc8ba113a8be35db66b21ab619292fcbf9 | [
"img_shape = image.shape[:2]\nempty_shape = (img_shape[0], img_shape[1], 3)\ntext_image = np.full(empty_shape, 255, dtype=np.uint8)\nif texts:\n text_image = self.get_labels_image(text_image, labels=texts, bboxes=bboxes, font_families=self.font_families, font_properties=self.font_properties)\nif polygons:\n p... | <|body_start_0|>
img_shape = image.shape[:2]
empty_shape = (img_shape[0], img_shape[1], 3)
text_image = np.full(empty_shape, 255, dtype=np.uint8)
if texts:
text_image = self.get_labels_image(text_image, labels=texts, bboxes=bboxes, font_families=self.font_families, font_prope... | TextSpottingLocalVisualizer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB... | stack_v2_sparse_classes_36k_train_029409 | 6,362 | permissive | [
{
"docstring": "Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB. bboxes (np.ndarray, torch.Tensor): The bboxes to draw. The shape of bboxes should be (N, 4), where N is the number of texts. polygons (Sequence[np.ndarray]): The polygons to draw. The length of... | 2 | null | Implement the Python class `TextSpottingLocalVisualizer` described below.
Class description:
Implement the TextSpottingLocalVisualizer class.
Method signatures and docstrings:
- def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) ... | Implement the Python class `TextSpottingLocalVisualizer` described below.
Class description:
Implement the TextSpottingLocalVisualizer class.
Method signatures and docstrings:
- def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) ... | 9551af6e5a2482e72a2af1e3b8597fd54b999d69 | <|skeleton|>
class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextSpottingLocalVisualizer:
def _draw_instances(self, image: np.ndarray, bboxes: Union[np.ndarray, torch.Tensor], polygons: Sequence[np.ndarray], texts: Sequence[str]) -> np.ndarray:
"""Draw instances on image. Args: image (np.ndarray): The origin image to draw. The format should be RGB. bboxes (np.n... | the_stack_v2_python_sparse | mmocr/visualization/textspotting_visualizer.py | open-mmlab/mmocr | train | 3,734 | |
7b06a9ee3dfc9239cc84ef23e7e2e0073f0ee8be | [
"super(UndirectedGraph, self).add_edge(edge)\nreverse = Edge(edge.dest, edge.src, edge.weight)\nsuper(UndirectedGraph, self).add_edge(reverse)",
"connections = defaultdict(list)\nfor node in self.edges:\n for e in self.edges[node]:\n connections[e.src].append((e.weight, e.src, e.dest, e))\n conne... | <|body_start_0|>
super(UndirectedGraph, self).add_edge(edge)
reverse = Edge(edge.dest, edge.src, edge.weight)
super(UndirectedGraph, self).add_edge(reverse)
<|end_body_0|>
<|body_start_1|>
connections = defaultdict(list)
for node in self.edges:
for e in self.edges[no... | UndirectedGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UndirectedGraph:
def add_edge(self, edge):
"""Override"""
<|body_0|>
def prims_algorithm(self):
"""Returns a set of edges that form the minimum spanning tree of the graph. Note that this graph must be connected. Taken from http://programmingpraxis.com/2010/04/09/mini... | stack_v2_sparse_classes_36k_train_029410 | 2,186 | no_license | [
{
"docstring": "Override",
"name": "add_edge",
"signature": "def add_edge(self, edge)"
},
{
"docstring": "Returns a set of edges that form the minimum spanning tree of the graph. Note that this graph must be connected. Taken from http://programmingpraxis.com/2010/04/09/minimum-spanning-tree-prim... | 2 | null | Implement the Python class `UndirectedGraph` described below.
Class description:
Implement the UndirectedGraph class.
Method signatures and docstrings:
- def add_edge(self, edge): Override
- def prims_algorithm(self): Returns a set of edges that form the minimum spanning tree of the graph. Note that this graph must b... | Implement the Python class `UndirectedGraph` described below.
Class description:
Implement the UndirectedGraph class.
Method signatures and docstrings:
- def add_edge(self, edge): Override
- def prims_algorithm(self): Returns a set of edges that form the minimum spanning tree of the graph. Note that this graph must b... | 3b47e87570b6a43bd22790566ff6bc9a3351e4a9 | <|skeleton|>
class UndirectedGraph:
def add_edge(self, edge):
"""Override"""
<|body_0|>
def prims_algorithm(self):
"""Returns a set of edges that form the minimum spanning tree of the graph. Note that this graph must be connected. Taken from http://programmingpraxis.com/2010/04/09/mini... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UndirectedGraph:
def add_edge(self, edge):
"""Override"""
super(UndirectedGraph, self).add_edge(edge)
reverse = Edge(edge.dest, edge.src, edge.weight)
super(UndirectedGraph, self).add_edge(reverse)
def prims_algorithm(self):
"""Returns a set of edges that form the ... | the_stack_v2_python_sparse | utils/python/graph.py | devang191/algorithms_competitions | train | 0 | |
7a61236040e9fb2e28058559ec0d44547cf08313 | [
"i = j = 0\ncount = collections.defaultdict(int)\nfor j in range(1, len(s) + 1):\n count[s[j - 1]] += 1\n most_com = count[max(count.keys(), key=lambda k: count[k])]\n if j - i - most_com > k:\n count[s[i]] -= 1\n i += 1\nreturn j - i",
"max_len = k + 1\nl, r = (0, 0)\ncounts = collections.... | <|body_start_0|>
i = j = 0
count = collections.defaultdict(int)
for j in range(1, len(s) + 1):
count[s[j - 1]] += 1
most_com = count[max(count.keys(), key=lambda k: count[k])]
if j - i - most_com > k:
count[s[i]] -= 1
i += 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def characterReplacement_refer(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = j = 0
... | stack_v2_sparse_classes_36k_train_029411 | 2,097 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "characterReplacement",
"signature": "def characterReplacement(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: int",
"name": "characterReplacement_refer",
"signature": "def characterReplacement_refer(self, ... | 2 | stack_v2_sparse_classes_30k_train_003247 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def characterReplacement(self, s, k): :type s: str :type k: int :rtype: int
- def characterReplacement_refer(self, s, k): :type s: str :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def characterReplacement(self, s, k): :type s: str :type k: int :rtype: int
- def characterReplacement_refer(self, s, k): :type s: str :type k: int :rtype: int
<|skeleton|>
clas... | f3fc71f344cd758cfce77f16ab72992c99ab288e | <|skeleton|>
class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_0|>
def characterReplacement_refer(self, s, k):
""":type s: str :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def characterReplacement(self, s, k):
""":type s: str :type k: int :rtype: int"""
i = j = 0
count = collections.defaultdict(int)
for j in range(1, len(s) + 1):
count[s[j - 1]] += 1
most_com = count[max(count.keys(), key=lambda k: count[k])]
... | the_stack_v2_python_sparse | 424_characterReplacement.py | jennyChing/leetCode | train | 2 | |
e4872b61312de0115e7f6ed0ff00135a457dd4cc | [
"self.dynamic_network_pool_config = dynamic_network_pool_config\nself.groupnet = groupnet\nself.smb_credentials = smb_credentials\nself.static_network_pool_config = static_network_pool_config",
"if dictionary is None:\n return None\ndynamic_network_pool_config = cohesity_management_sdk.models.isilon_env_params... | <|body_start_0|>
self.dynamic_network_pool_config = dynamic_network_pool_config
self.groupnet = groupnet
self.smb_credentials = smb_credentials
self.static_network_pool_config = static_network_pool_config
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return ... | Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zone. Dynamic pool is used for stateless protocols, e.g. NFSv3. groupnet (string): Name of the ... | IsilonEnvParams_ZoneConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsilonEnvParams_ZoneConfig:
"""Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zone. Dynamic pool is used for stateless ... | stack_v2_sparse_classes_36k_train_029412 | 3,492 | permissive | [
{
"docstring": "Constructor for the IsilonEnvParams_ZoneConfig class",
"name": "__init__",
"signature": "def __init__(self, dynamic_network_pool_config=None, groupnet=None, smb_credentials=None, static_network_pool_config=None)"
},
{
"docstring": "Creates an instance of this model from a diction... | 2 | stack_v2_sparse_classes_30k_train_002239 | Implement the Python class `IsilonEnvParams_ZoneConfig` described below.
Class description:
Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zo... | Implement the Python class `IsilonEnvParams_ZoneConfig` described below.
Class description:
Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zo... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IsilonEnvParams_ZoneConfig:
"""Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zone. Dynamic pool is used for stateless ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IsilonEnvParams_ZoneConfig:
"""Implementation of the 'IsilonEnvParams_ZoneConfig' model. TODO: type description here. Attributes: dynamic_network_pool_config (IsilonEnvParams_ZoneConfig_NetworkPoolConfig): Dynamic network pool configuration for the access zone. Dynamic pool is used for stateless protocols, e.... | the_stack_v2_python_sparse | cohesity_management_sdk/models/isilon_env_params_zone_config.py | cohesity/management-sdk-python | train | 24 |
f2fa722e9343dfd5667190fba69e5be2fecbb2f6 | [
"x_keys = list((key for key in board_dict if 'X' == board_dict[key]))\ny_keys = list((key for key in board_dict if 'O' == board_dict[key]))\nreturn (x_keys, y_keys)",
"for i in range(0, 3):\n row_comb = list((True for _x, _y in x_keys if _x == i))\n col_comb = list((True for _x, _y in x_keys if _y == i))\n ... | <|body_start_0|>
x_keys = list((key for key in board_dict if 'X' == board_dict[key]))
y_keys = list((key for key in board_dict if 'O' == board_dict[key]))
return (x_keys, y_keys)
<|end_body_0|>
<|body_start_1|>
for i in range(0, 3):
row_comb = list((True for _x, _y in x_keys... | GamePatternBased | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GamePatternBased:
def get_all_keys_for_x_and_o(board_dict):
"""get all keys for both players :param board_dict: :return:"""
<|body_0|>
def win_condition_check(x_keys):
""":param x_keys: :return:"""
<|body_1|>
def based_win_condition(self):
""":pa... | stack_v2_sparse_classes_36k_train_029413 | 3,788 | no_license | [
{
"docstring": "get all keys for both players :param board_dict: :return:",
"name": "get_all_keys_for_x_and_o",
"signature": "def get_all_keys_for_x_and_o(board_dict)"
},
{
"docstring": ":param x_keys: :return:",
"name": "win_condition_check",
"signature": "def win_condition_check(x_keys... | 5 | stack_v2_sparse_classes_30k_train_018685 | Implement the Python class `GamePatternBased` described below.
Class description:
Implement the GamePatternBased class.
Method signatures and docstrings:
- def get_all_keys_for_x_and_o(board_dict): get all keys for both players :param board_dict: :return:
- def win_condition_check(x_keys): :param x_keys: :return:
- d... | Implement the Python class `GamePatternBased` described below.
Class description:
Implement the GamePatternBased class.
Method signatures and docstrings:
- def get_all_keys_for_x_and_o(board_dict): get all keys for both players :param board_dict: :return:
- def win_condition_check(x_keys): :param x_keys: :return:
- d... | 5e243ce7b3f221a11293f5f414e3f326e3043b51 | <|skeleton|>
class GamePatternBased:
def get_all_keys_for_x_and_o(board_dict):
"""get all keys for both players :param board_dict: :return:"""
<|body_0|>
def win_condition_check(x_keys):
""":param x_keys: :return:"""
<|body_1|>
def based_win_condition(self):
""":pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GamePatternBased:
def get_all_keys_for_x_and_o(board_dict):
"""get all keys for both players :param board_dict: :return:"""
x_keys = list((key for key in board_dict if 'X' == board_dict[key]))
y_keys = list((key for key in board_dict if 'O' == board_dict[key]))
return (x_keys, ... | the_stack_v2_python_sparse | src/game_pattern_based.py | pantlavanya/tic_tac_toe_game | train | 0 | |
6bd25a442fcef5067eef82114f0434a89532ca67 | [
"self._mutation = actual_mutation\nself._accept_less_percent = accept_less\nself._accept_less_rand = random.Random()",
"new_org = self._mutation.mutate(org)\nnew_org.recalculate_fitness()\nif org.fitness > new_org.fitness:\n accept_less_chance = self._accept_less_rand.random()\n if accept_less_chance <= sel... | <|body_start_0|>
self._mutation = actual_mutation
self._accept_less_percent = accept_less
self._accept_less_rand = random.Random()
<|end_body_0|>
<|body_start_1|>
new_org = self._mutation.mutate(org)
new_org.recalculate_fitness()
if org.fitness > new_org.fitness:
... | Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses. | SafeFitnessMutation | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do... | stack_v2_sparse_classes_36k_train_029414 | 1,414 | permissive | [
{
"docstring": "Initialize to do safe mutations Arguments: o actual_mutation - A Mutation class which actually implements mutation. functionality. o accept_less - A probability to accept mutations which generate lower fitness. This allows you to accept some crossovers which reduce fitness, but not all of them."... | 2 | stack_v2_sparse_classes_30k_train_016544 | Implement the Python class `SafeFitnessMutation` described below.
Class description:
Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses.
Method signatures and docstrings:
- def __init__(... | Implement the Python class `SafeFitnessMutation` described below.
Class description:
Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses.
Method signatures and docstrings:
- def __init__(... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SafeFitnessMutation:
"""Perform mutations, but do not allow decreases in organism fitness. This doesn't actually do any mutation work, but just checks that newly create organisms do not have lower fitnesses."""
def __init__(self, actual_mutation, accept_less=0.0):
"""Initialize to do safe mutatio... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/GA/Mutation/General.py | LyonsLab/coge | train | 41 |
01ab0524405545fffde9124f0b3bf31b6856d507 | [
"super(Vehicle, self).__init__(voxel_data_dict, vehicle_csys=vehicle_csys, voxel_size=voxel_size)\nself.floor = None\nself.ceiling = None",
"labels = self.get_labels(mask_from_voxel=cabin_voxel)\nself.ceiling = np.zeros((labels.shape[0], labels.shape[1]), dtype=np.int16)\nself.floor = np.zeros((labels.shape[0], l... | <|body_start_0|>
super(Vehicle, self).__init__(voxel_data_dict, vehicle_csys=vehicle_csys, voxel_size=voxel_size)
self.floor = None
self.ceiling = None
<|end_body_0|>
<|body_start_1|>
labels = self.get_labels(mask_from_voxel=cabin_voxel)
self.ceiling = np.zeros((labels.shape[0],... | Add specific methods for finding floor and ceiling | Vehicle | [
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vehicle:
"""Add specific methods for finding floor and ceiling"""
def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None):
"""Call constructor of superclass and then add on two more empty parameters"""
<|body_0|>
def _make_floor_ceil(self, cabin_voxel):
... | stack_v2_sparse_classes_36k_train_029415 | 8,134 | permissive | [
{
"docstring": "Call constructor of superclass and then add on two more empty parameters",
"name": "__init__",
"signature": "def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None)"
},
{
"docstring": "Alternate method of ceiling detection: get the label in a region containing tro... | 4 | stack_v2_sparse_classes_30k_train_007924 | Implement the Python class `Vehicle` described below.
Class description:
Add specific methods for finding floor and ceiling
Method signatures and docstrings:
- def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None): Call constructor of superclass and then add on two more empty parameters
- def _make_... | Implement the Python class `Vehicle` described below.
Class description:
Add specific methods for finding floor and ceiling
Method signatures and docstrings:
- def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None): Call constructor of superclass and then add on two more empty parameters
- def _make_... | bc7a05e04c7901f477fe553c59e478a837116d92 | <|skeleton|>
class Vehicle:
"""Add specific methods for finding floor and ceiling"""
def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None):
"""Call constructor of superclass and then add on two more empty parameters"""
<|body_0|>
def _make_floor_ceil(self, cabin_voxel):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Vehicle:
"""Add specific methods for finding floor and ceiling"""
def __init__(self, voxel_data_dict, vehicle_csys=None, voxel_size=None):
"""Call constructor of superclass and then add on two more empty parameters"""
super(Vehicle, self).__init__(voxel_data_dict, vehicle_csys=vehicle_csy... | the_stack_v2_python_sparse | analysis_tools/PYTHON_RICARDO/output_ingress_egress/scripts/voxel_methods.py | metamorph-inc/meta-core | train | 25 |
85fe12ca643e635b08203cf5bbdad122d2373a8e | [
"if not has_perm(self.request.user, 'core.can_see_history'):\n self.permission_denied(self.request)\ntype = self.request.query_params.get('type')\nvalue = self.request.query_params.get('value')\nif type not in 'element':\n raise ValidationError({'detail': \"Invalid input. Type should be 'element' or 'text'.\"... | <|body_start_0|>
if not has_perm(self.request.user, 'core.can_see_history'):
self.permission_denied(self.request)
type = self.request.query_params.get('type')
value = self.request.query_params.get('value')
if type not in 'element':
raise ValidationError({'detail':... | View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for motion 42 Use DELETE to clear the history. | HistoryInformationView | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HistoryInformationView:
"""View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for motion 42 Use DELETE to clear the history... | stack_v2_sparse_classes_36k_train_029416 | 24,920 | permissive | [
{
"docstring": "Checks permission and parses query parameters.",
"name": "get_context_data",
"signature": "def get_context_data(self, **context)"
},
{
"docstring": "Retrieves history information for element search.",
"name": "get_data_element_search",
"signature": "def get_data_element_s... | 3 | stack_v2_sparse_classes_30k_train_020085 | Implement the Python class `HistoryInformationView` described below.
Class description:
View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for mo... | Implement the Python class `HistoryInformationView` described below.
Class description:
View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for mo... | 7dc35dce404339b41c7729eb3de29010ca63f9a0 | <|skeleton|>
class HistoryInformationView:
"""View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for motion 42 Use DELETE to clear the history... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HistoryInformationView:
"""View to retrieve information about OpenSlides history. Use GET to search history information. The query parameter 'type' determines the type of your search: Examples: /?type=element&value=motions%2Fmotion%3A42 if your search for motion 42 Use DELETE to clear the history."""
def... | the_stack_v2_python_sparse | server/openslides/core/views.py | FinnStutzenstein/OpenSlides | train | 0 |
9a73605607d379437b0d529a50c7923e1a3f50cb | [
"select_sql = u\"select * from T_CARD_INFO where card_code='%s'\"\nself.open_card_information()\ncard_code = self.get_table_cell_text(1, 2)\ncard_type = self.get_table_cell_text(1, 4)\nsearch_list = [card_code, u'', u'', u'', card_type, u'']\nself.search_card_information(search_list)\nresult_text = self.get_search_... | <|body_start_0|>
select_sql = u"select * from T_CARD_INFO where card_code='%s'"
self.open_card_information()
card_code = self.get_table_cell_text(1, 2)
card_type = self.get_table_cell_text(1, 4)
search_list = [card_code, u'', u'', u'', card_type, u'']
self.search_card_inf... | 投注卡信息测试 | CardInformationTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CardInformationTest:
"""投注卡信息测试"""
def test_card_information_search(self):
"""投注卡信息-卡片查询"""
<|body_0|>
def test_card_information_check_detail(self):
"""投注卡信息-卡片查看"""
<|body_1|>
def test_card_information_cancel(self):
"""投注卡信息-卡片注销"""
... | stack_v2_sparse_classes_36k_train_029417 | 2,686 | no_license | [
{
"docstring": "投注卡信息-卡片查询",
"name": "test_card_information_search",
"signature": "def test_card_information_search(self)"
},
{
"docstring": "投注卡信息-卡片查看",
"name": "test_card_information_check_detail",
"signature": "def test_card_information_check_detail(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_test_000979 | Implement the Python class `CardInformationTest` described below.
Class description:
投注卡信息测试
Method signatures and docstrings:
- def test_card_information_search(self): 投注卡信息-卡片查询
- def test_card_information_check_detail(self): 投注卡信息-卡片查看
- def test_card_information_cancel(self): 投注卡信息-卡片注销 | Implement the Python class `CardInformationTest` described below.
Class description:
投注卡信息测试
Method signatures and docstrings:
- def test_card_information_search(self): 投注卡信息-卡片查询
- def test_card_information_check_detail(self): 投注卡信息-卡片查看
- def test_card_information_cancel(self): 投注卡信息-卡片注销
<|skeleton|>
class CardIn... | dcae68955b2857bbfe411145432865c57561c9ef | <|skeleton|>
class CardInformationTest:
"""投注卡信息测试"""
def test_card_information_search(self):
"""投注卡信息-卡片查询"""
<|body_0|>
def test_card_information_check_detail(self):
"""投注卡信息-卡片查看"""
<|body_1|>
def test_card_information_cancel(self):
"""投注卡信息-卡片注销"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CardInformationTest:
"""投注卡信息测试"""
def test_card_information_search(self):
"""投注卡信息-卡片查询"""
select_sql = u"select * from T_CARD_INFO where card_code='%s'"
self.open_card_information()
card_code = self.get_table_cell_text(1, 2)
card_type = self.get_table_cell_text(1... | the_stack_v2_python_sparse | genlot_vlt2/cases/BusinessManagement/card_balance/card_information_test.py | bbwdi/auto | train | 1 |
1062f6e210a39596b6011cd84b6e02bc63345ffb | [
"p = len(curr)\nif p >= len(digits):\n comb = ''.join(curr)\n if comb:\n sol.append(comb)\n return\nidx = ord(digits[p]) - ord('0')\nfor c in self.letters[idx]:\n curr.append(c)\n self.dfs(digits, curr, sol)\n curr.pop()",
"digits = digits.replace('1', '')\nsol = []\nself.dfs(digits, [], ... | <|body_start_0|>
p = len(curr)
if p >= len(digits):
comb = ''.join(curr)
if comb:
sol.append(comb)
return
idx = ord(digits[p]) - ord('0')
for c in self.letters[idx]:
curr.append(c)
self.dfs(digits, curr, sol)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dfs(self, digits, curr, sol):
""":param curr: list[char] :param sol: :return:"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
p = len(curr)
... | stack_v2_sparse_classes_36k_train_029418 | 1,180 | no_license | [
{
"docstring": ":param curr: list[char] :param sol: :return:",
"name": "dfs",
"signature": "def dfs(self, digits, curr, sol)"
},
{
"docstring": ":type digits: str :rtype: List[str]",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, digits, curr, sol): :param curr: list[char] :param sol: :return:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dfs(self, digits, curr, sol): :param curr: list[char] :param sol: :return:
- def letterCombinations(self, digits): :type digits: str :rtype: List[str]
<|skeleton|>
class Sol... | 20580185c6f72f3c09a725168af48893156161f5 | <|skeleton|>
class Solution:
def dfs(self, digits, curr, sol):
""":param curr: list[char] :param sol: :return:"""
<|body_0|>
def letterCombinations(self, digits):
""":type digits: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dfs(self, digits, curr, sol):
""":param curr: list[char] :param sol: :return:"""
p = len(curr)
if p >= len(digits):
comb = ''.join(curr)
if comb:
sol.append(comb)
return
idx = ord(digits[p]) - ord('0')
fo... | the_stack_v2_python_sparse | coding/00017-letter-comb-of-phone-number/solution.py | misaka-10032/leetcode | train | 3 | |
c47418b0559807e90f5df83f59e0413944bf4a20 | [
"headers = {name: response.raw.headers.getlist(name) for name in response.raw.headers.keys()}\nhttp_version = '1.0' if response.raw.version == 10 else '1.1'\nreturn cls(status_code=response.status_code, message=response.reason, body=serialize_payload(response.content), encoding=response.encoding or 'utf8', headers=... | <|body_start_0|>
headers = {name: response.raw.headers.getlist(name) for name in response.raw.headers.keys()}
http_version = '1.0' if response.raw.version == 10 else '1.1'
return cls(status_code=response.status_code, message=response.reason, body=serialize_payload(response.content), encoding=res... | Unified response data. | Response | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Response:
"""Unified response data."""
def from_requests(cls, response: requests.Response) -> 'Response':
"""Create a response from requests.Response."""
<|body_0|>
def from_wsgi(cls, response: WSGIResponse, elapsed: float) -> 'Response':
"""Create a response fro... | stack_v2_sparse_classes_36k_train_029419 | 32,203 | permissive | [
{
"docstring": "Create a response from requests.Response.",
"name": "from_requests",
"signature": "def from_requests(cls, response: requests.Response) -> 'Response'"
},
{
"docstring": "Create a response from WSGI response.",
"name": "from_wsgi",
"signature": "def from_wsgi(cls, response:... | 2 | stack_v2_sparse_classes_30k_train_016404 | Implement the Python class `Response` described below.
Class description:
Unified response data.
Method signatures and docstrings:
- def from_requests(cls, response: requests.Response) -> 'Response': Create a response from requests.Response.
- def from_wsgi(cls, response: WSGIResponse, elapsed: float) -> 'Response': ... | Implement the Python class `Response` described below.
Class description:
Unified response data.
Method signatures and docstrings:
- def from_requests(cls, response: requests.Response) -> 'Response': Create a response from requests.Response.
- def from_wsgi(cls, response: WSGIResponse, elapsed: float) -> 'Response': ... | 9ba2244bf0e52db6f149243de403c8c7c157216f | <|skeleton|>
class Response:
"""Unified response data."""
def from_requests(cls, response: requests.Response) -> 'Response':
"""Create a response from requests.Response."""
<|body_0|>
def from_wsgi(cls, response: WSGIResponse, elapsed: float) -> 'Response':
"""Create a response fro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Response:
"""Unified response data."""
def from_requests(cls, response: requests.Response) -> 'Response':
"""Create a response from requests.Response."""
headers = {name: response.raw.headers.getlist(name) for name in response.raw.headers.keys()}
http_version = '1.0' if response.r... | the_stack_v2_python_sparse | schemathesis/models.py | ngalongc/openapi_security_scanner | train | 167 |
6e494acea65e0761b72b7258315f9f7f2ed0bc54 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing certificates. | CertificateServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CertificateServiceServicer:
"""A set of methods for managing certificates."""
def Get(self, request, context):
"""Returns the specified certificate. To get the list of available certificates, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_36k_train_029420 | 13,260 | permissive | [
{
"docstring": "Returns the specified certificate. To get the list of available certificates, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of certificates in the specified federation.",
"name": "List",
"signa... | 6 | null | Implement the Python class `CertificateServiceServicer` described below.
Class description:
A set of methods for managing certificates.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified certificate. To get the list of available certificates, make a [List] request.
- def List(s... | Implement the Python class `CertificateServiceServicer` described below.
Class description:
A set of methods for managing certificates.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified certificate. To get the list of available certificates, make a [List] request.
- def List(s... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class CertificateServiceServicer:
"""A set of methods for managing certificates."""
def Get(self, request, context):
"""Returns the specified certificate. To get the list of available certificates, make a [List] request."""
<|body_0|>
def List(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CertificateServiceServicer:
"""A set of methods for managing certificates."""
def Get(self, request, context):
"""Returns the specified certificate. To get the list of available certificates, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_det... | the_stack_v2_python_sparse | yandex/cloud/organizationmanager/v1/saml/certificate_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
f167bc0b98d2f132359136156770754348c98299 | [
"validate = Validate()\nname = self.cleaned_data['name']\nif not validate.check_name(name):\n raise ValidationError(u\"Некоректно введено ім'я.\")\nreturn name",
"validate = Validate()\nlogin = self.cleaned_data['login']\nif not validate.check_login(login):\n raise ValidationError(u'Некоректно введно логін.... | <|body_start_0|>
validate = Validate()
name = self.cleaned_data['name']
if not validate.check_name(name):
raise ValidationError(u"Некоректно введено ім'я.")
return name
<|end_body_0|>
<|body_start_1|>
validate = Validate()
login = self.cleaned_data['login']
... | This class is the form class for teachers. | TeacherForm | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeacherForm:
"""This class is the form class for teachers."""
def clean_name(self):
"""Validate name field."""
<|body_0|>
def clean_login(self):
"""Validate login field."""
<|body_1|>
def clean_email(self):
"""Validate email field."""
... | stack_v2_sparse_classes_36k_train_029421 | 1,418 | permissive | [
{
"docstring": "Validate name field.",
"name": "clean_name",
"signature": "def clean_name(self)"
},
{
"docstring": "Validate login field.",
"name": "clean_login",
"signature": "def clean_login(self)"
},
{
"docstring": "Validate email field.",
"name": "clean_email",
"signa... | 3 | stack_v2_sparse_classes_30k_train_005261 | Implement the Python class `TeacherForm` described below.
Class description:
This class is the form class for teachers.
Method signatures and docstrings:
- def clean_name(self): Validate name field.
- def clean_login(self): Validate login field.
- def clean_email(self): Validate email field. | Implement the Python class `TeacherForm` described below.
Class description:
This class is the form class for teachers.
Method signatures and docstrings:
- def clean_name(self): Validate name field.
- def clean_login(self): Validate login field.
- def clean_email(self): Validate email field.
<|skeleton|>
class Teach... | 3bdfa3dac95590036be8f33f8cd1f8831e872ef0 | <|skeleton|>
class TeacherForm:
"""This class is the form class for teachers."""
def clean_name(self):
"""Validate name field."""
<|body_0|>
def clean_login(self):
"""Validate login field."""
<|body_1|>
def clean_email(self):
"""Validate email field."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeacherForm:
"""This class is the form class for teachers."""
def clean_name(self):
"""Validate name field."""
validate = Validate()
name = self.cleaned_data['name']
if not validate.check_name(name):
raise ValidationError(u"Некоректно введено ім'я.")
re... | the_stack_v2_python_sparse | SMS/apps/mainteacher/forms.py | Social-projects-Rivne/SMS_autotesting | train | 0 |
519127431cccfbb2ff502a3520b9ee554721da20 | [
"super(HiveFilteredPartitionSensor, self).__init__(host, port, **kwargs)\nself._table_name = table_name\nself._partition_filter = partition_filter",
"with self._hive_metastore_client as client:\n partitions = client.get_partitions_by_filter(db_name=self._schema, tbl_name=self._table_name, filter=self._partitio... | <|body_start_0|>
super(HiveFilteredPartitionSensor, self).__init__(host, port, **kwargs)
self._table_name = table_name
self._partition_filter = partition_filter
<|end_body_0|>
<|body_start_1|>
with self._hive_metastore_client as client:
partitions = client.get_partitions_by_... | HiveFilteredPartitionSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it ... | stack_v2_sparse_classes_36k_train_029422 | 4,900 | permissive | [
{
"docstring": "This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it is a more efficient API. :param Text table_name: The name of the table :param Text partition_filter: A filter ex... | 2 | null | Implement the Python class `HiveFilteredPartitionSensor` described below.
Class description:
Implement the HiveFilteredPartitionSensor class.
Method signatures and docstrings:
- def __init__(self, table_name, partition_filter, host, port, **kwargs): This class allows sensing for any Hive partition that matches a filt... | Implement the Python class `HiveFilteredPartitionSensor` described below.
Class description:
Implement the HiveFilteredPartitionSensor class.
Method signatures and docstrings:
- def __init__(self, table_name, partition_filter, host, port, **kwargs): This class allows sensing for any Hive partition that matches a filt... | 2eb9ce7aacaab6e49c1fc901c14c7b0d6b479523 | <|skeleton|>
class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HiveFilteredPartitionSensor:
def __init__(self, table_name, partition_filter, host, port, **kwargs):
"""This class allows sensing for any Hive partition that matches a filter expression. It is recommended that the user should use HiveNamedPartitionSensor instead when possible because it is a more effi... | the_stack_v2_python_sparse | flytekit/contrib/sensors/impl.py | jbrambleDC/flytekit | train | 1 | |
f88335f1626945df598ec5e619c88df3c14f83ef | [
"app = self.request.app\napp.logger.debug(f'Chat command {cmd}')\nif cmd == '/clear':\n await app.objects.execute(Message.delete().where(Message.room == self.room))\n app.logger.debug(f'Removed {count} messages')\n for peer in app.wslist[self.room.id].values():\n peer.send_json({'cmd': 'empty'})\nel... | <|body_start_0|>
app = self.request.app
app.logger.debug(f'Chat command {cmd}')
if cmd == '/clear':
await app.objects.execute(Message.delete().where(Message.room == self.room))
app.logger.debug(f'Removed {count} messages')
for peer in app.wslist[self.room.id].... | Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер | WebSocketMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
<|body_0|>
async def broadcast(self, message: Message) ... | stack_v2_sparse_classes_36k_train_029423 | 4,826 | no_license | [
{
"docstring": "Некоторые управляющие команды",
"name": "command_line",
"signature": "async def command_line(self, cmd: str) -> Dict[str, str]"
},
{
"docstring": "Рассылка сообщениий по всей комнате",
"name": "broadcast",
"signature": "async def broadcast(self, message: Message) -> None"... | 2 | stack_v2_sparse_classes_30k_train_011397 | Implement the Python class `WebSocketMixin` described below.
Class description:
Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер
Method signatures and docstrings:
- async def command_line(self, cmd: str) -> Dict[str, str]: Некоторые управляющие команды
- async def br... | Implement the Python class `WebSocketMixin` described below.
Class description:
Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер
Method signatures and docstrings:
- async def command_line(self, cmd: str) -> Dict[str, str]: Некоторые управляющие команды
- async def br... | b7760f05e1d00f28a06b07bcd120c4af0237ce94 | <|skeleton|>
class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
<|body_0|>
async def broadcast(self, message: Message) ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebSocketMixin:
"""Вспомогательный класс для всяких нужных методов для работы с вебсокетами, что бы не засорять хелпер"""
async def command_line(self, cmd: str) -> Dict[str, str]:
"""Некоторые управляющие команды"""
app = self.request.app
app.logger.debug(f'Chat command {cmd}')
... | the_stack_v2_python_sparse | src/chat_take_aiohttp/web/chat_handlers.py | Tsvetov/chat_take_aiohttp | train | 0 |
8b7fe54bad51aeb1997abb809802c39a17d75b87 | [
"self.spin_id1 = spin_id1\nself.spin_id2 = spin_id2\nself.dipole_pair = False\nself.select = select",
"text = 'Class containing all the interatomic specific data between spins %s and %s.\\n\\n' % (self.spin_id1, self.spin_id2)\ntext = text + '\\n'\ntext = text + 'Objects:\\n'\nfor name in dir(self):\n if name ... | <|body_start_0|>
self.spin_id1 = spin_id1
self.spin_id2 = spin_id2
self.dipole_pair = False
self.select = select
<|end_body_0|>
<|body_start_1|>
text = 'Class containing all the interatomic specific data between spins %s and %s.\n\n' % (self.spin_id1, self.spin_id2)
text... | Class containing the interatomic data. | InteratomContainer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InteratomContainer:
"""Class containing the interatomic data."""
def __init__(self, spin_id1=None, spin_id2=None, select=True):
"""Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of the first atom. @type spin_id1: str @keyword spin_id2: The... | stack_v2_sparse_classes_36k_train_029424 | 9,873 | no_license | [
{
"docstring": "Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of the first atom. @type spin_id1: str @keyword spin_id2: The spin ID string of the second atom. @type spin_id2: str @keyword select: The selection flag. @type select: bool",
"name": "__init__",
"... | 3 | null | Implement the Python class `InteratomContainer` described below.
Class description:
Class containing the interatomic data.
Method signatures and docstrings:
- def __init__(self, spin_id1=None, spin_id2=None, select=True): Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of t... | Implement the Python class `InteratomContainer` described below.
Class description:
Class containing the interatomic data.
Method signatures and docstrings:
- def __init__(self, spin_id1=None, spin_id2=None, select=True): Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of t... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class InteratomContainer:
"""Class containing the interatomic data."""
def __init__(self, spin_id1=None, spin_id2=None, select=True):
"""Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of the first atom. @type spin_id1: str @keyword spin_id2: The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InteratomContainer:
"""Class containing the interatomic data."""
def __init__(self, spin_id1=None, spin_id2=None, select=True):
"""Set up the objects of the interatomic data container. @keyword spin_id1: The spin ID string of the first atom. @type spin_id1: str @keyword spin_id2: The spin ID stri... | the_stack_v2_python_sparse | data_store/interatomic.py | jlec/relax | train | 4 |
29abbd1ea85905caa5b284ecae65636de4d33fd3 | [
"if not secret_key:\n return None\nsigner_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)\nreturn URLSafeTimedSerializer(secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=signer_kwargs)",
"sscsi = SimpleSecureCookieSessionInterface()\nsigningSerializer = ... | <|body_start_0|>
if not secret_key:
return None
signer_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)
return URLSafeTimedSerializer(secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=signer_kwargs)
<|end_body_0|>
<|body_start_1... | SimpleSecureCookieSessionInterface | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
<|body_0|>
def decodeFlaskCookie(self, secret_key, cookieValue):
"""Decode a base 64 encoded string"""
<|body_1|>
def encodeFlaskCookie(self,... | stack_v2_sparse_classes_36k_train_029425 | 2,701 | no_license | [
{
"docstring": "Used to check secret key",
"name": "get_signing_serializer",
"signature": "def get_signing_serializer(self, secret_key)"
},
{
"docstring": "Decode a base 64 encoded string",
"name": "decodeFlaskCookie",
"signature": "def decodeFlaskCookie(self, secret_key, cookieValue)"
... | 3 | stack_v2_sparse_classes_30k_train_009089 | Implement the Python class `SimpleSecureCookieSessionInterface` described below.
Class description:
Implement the SimpleSecureCookieSessionInterface class.
Method signatures and docstrings:
- def get_signing_serializer(self, secret_key): Used to check secret key
- def decodeFlaskCookie(self, secret_key, cookieValue):... | Implement the Python class `SimpleSecureCookieSessionInterface` described below.
Class description:
Implement the SimpleSecureCookieSessionInterface class.
Method signatures and docstrings:
- def get_signing_serializer(self, secret_key): Used to check secret key
- def decodeFlaskCookie(self, secret_key, cookieValue):... | 24e1e25d2e512105c9bf70b5e33b1afed4790f71 | <|skeleton|>
class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
<|body_0|>
def decodeFlaskCookie(self, secret_key, cookieValue):
"""Decode a base 64 encoded string"""
<|body_1|>
def encodeFlaskCookie(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleSecureCookieSessionInterface:
def get_signing_serializer(self, secret_key):
"""Used to check secret key"""
if not secret_key:
return None
signer_kwargs = dict(key_derivation=self.key_derivation, digest_method=self.digest_method)
return URLSafeTimedSerializer(s... | the_stack_v2_python_sparse | flask/app/config.py | InTheNou/InTheNou-Backend | train | 0 | |
386e07ffd35e8e0abafc0b950ed38ed17d9dc2e3 | [
"def recursive(root, string):\n if not root:\n string += 'null,'\n else:\n string += str(root.val) + ','\n string = recursive(root.left, string)\n string = recursive(root.right, string)\n return string\nreturn recursive(root, '')",
"def recursive(data):\n if data[0] == 'nul... | <|body_start_0|>
def recursive(root, string):
if not root:
string += 'null,'
else:
string += str(root.val) + ','
string = recursive(root.left, string)
string = recursive(root.right, string)
return string
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_029426 | 5,096 | 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:... | cc7740026c3774be21ab924b99ae7596ef20d0e4 | <|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_36k | 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 recursive(root, string):
if not root:
string += 'null,'
else:
string += str(root.val) + ','
string = recursive... | the_stack_v2_python_sparse | HOT_100/094.py | yangtao0304/hands-on-programming-exercise | train | 0 | |
6eb1d97bae897bfb663e8601b8ae427d7054af1b | [
"result = 0\nfor i in range(1, len(prices)):\n profit = prices[i] - prices[i - 1]\n if profit > 0:\n result += profit\nreturn result",
"if len(prices) < 2:\n return 0\nbuy, sell = ([0] * len(prices), [0] * len(prices))\nbuy[0], sell[0] = (-prices[0], 0)\nfor i in range(1, len(prices)):\n buy[i]... | <|body_start_0|>
result = 0
for i in range(1, len(prices)):
profit = prices[i] - prices[i - 1]
if profit > 0:
result += profit
return result
<|end_body_0|>
<|body_start_1|>
if len(prices) < 2:
return 0
buy, sell = ([0] * len(pr... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。"""
<|body_0|>
def maxProfit_dp(self, prices: List[int]) -> int:
"""每天只能操作一次的情况下是一个动态规划问题"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_029427 | 1,034 | permissive | [
{
"docstring": "在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "每天只能操作一次的情况下是一个动态规划问题",
"name": "maxProfit_dp",
"signature": "def maxProfit_dp(self, prices: List[int]) -> int"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。
- def maxProfit_dp(self, prices: List[int]) -> int: 每天只能操作一次的情况下是一个动态规划问题 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。
- def maxProfit_dp(self, prices: List[int]) -> int: 每天只能操作一次的情况下是一个动态规划问题
... | d203aecd1afe1af13a0384a9c657c8424aab322d | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。"""
<|body_0|>
def maxProfit_dp(self, prices: List[int]) -> int:
"""每天只能操作一次的情况下是一个动态规划问题"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""在一天之内能卖了再买的情况下,利润就是前面大的减小的。 即使卖出后出现更大的,也可以立即买回,所以直接加就完事。"""
result = 0
for i in range(1, len(prices)):
profit = prices[i] - prices[i - 1]
if profit > 0:
result += profit
return r... | the_stack_v2_python_sparse | easy/Q122_BestTimeToBuyAndSellStock2.py | Kaciras/leetcode | train | 0 | |
24e78ac3c00315fa287f132e96163ae23010bb7e | [
"count, items = cls.search_for_items(session, item, False)\nif count > 0:\n return items[0]\nreturn None",
"if 'name' not in item:\n return (0, [])\nresult = cls.search(session, name=item['name'])\ncount = result.count()\nif multiple and count > 0:\n return (count, result)\nif count == 1 and (not multipl... | <|body_start_0|>
count, items = cls.search_for_items(session, item, False)
if count > 0:
return items[0]
return None
<|end_body_0|>
<|body_start_1|>
if 'name' not in item:
return (0, [])
result = cls.search(session, name=item['name'])
count = resu... | Common methods used for both Album and Artist objects | ArtistAlbumMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtistAlbumMixin:
"""Common methods used for both Album and Artist objects"""
def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']:
"""Try to match "item" to an object already in the database."""
<|body_0|>
def search_for_i... | stack_v2_sparse_classes_36k_train_029428 | 9,401 | no_license | [
{
"docstring": "Try to match \"item\" to an object already in the database.",
"name": "search_for_item",
"signature": "def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']"
},
{
"docstring": "Try to match this item to one or more items already in t... | 2 | null | Implement the Python class `ArtistAlbumMixin` described below.
Class description:
Common methods used for both Album and Artist objects
Method signatures and docstrings:
- def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']: Try to match "item" to an object already in ... | Implement the Python class `ArtistAlbumMixin` described below.
Class description:
Common methods used for both Album and Artist objects
Method signatures and docstrings:
- def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']: Try to match "item" to an object already in ... | f49d26900a10593a6f993b82d8d782b2e7367f84 | <|skeleton|>
class ArtistAlbumMixin:
"""Common methods used for both Album and Artist objects"""
def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']:
"""Try to match "item" to an object already in the database."""
<|body_0|>
def search_for_i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArtistAlbumMixin:
"""Common methods used for both Album and Artist objects"""
def search_for_item(cls, session: DatabaseSession, item: JsonObject) -> Optional['ArtistAlbumMixin']:
"""Try to match "item" to an object already in the database."""
count, items = cls.search_for_items(session, ... | the_stack_v2_python_sparse | musicbingo/models/modelmixin.py | asrashley/music-bingo | train | 1 |
d97809225c8c9d0cb10db0e29504c05b8c835a9b | [
"def recur(root, string):\n if root is None:\n string += 'None,'\n else:\n string += str(root.val) + ','\n string = recur(root.left, string)\n string = recur(root.right, string)\n return string\nreturn recur(root, '')",
"def recur(data_list):\n if data_list[0] == 'None':\n ... | <|body_start_0|>
def recur(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = recur(root.left, string)
string = recur(root.right, string)
return string
return r... | Codec | [
"MIT"
] | 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_36k_train_029429 | 1,769 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_002974 | 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:... | 8ec18e08e9313bc3326846ca6ef6e569380a133f | <|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_36k | 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 recur(root, string):
if root is None:
string += 'None,'
else:
string += str(root.val) + ','
string = recur(roo... | the_stack_v2_python_sparse | Max/Max_0297_20200115.py | Morek999/OMSCS_Taiwan_Leetcode | train | 1 | |
514df190515b8f56183b7b031362c656e48f3a5f | [
"self.n += len(fs)\n_f = self.setdefault\nreturn tuple((_f(f, f) for f in map(float, fs)))",
"Cx = _Coeffs(coeffs)\nCx.set_(ALorder=ALorder, n=self.n, u=len(self.keys()))\nreturn Cx"
] | <|body_start_0|>
self.n += len(fs)
_f = self.setdefault
return tuple((_f(f, f) for f in map(float, fs)))
<|end_body_0|>
<|body_start_1|>
Cx = _Coeffs(coeffs)
Cx.set_(ALorder=ALorder, n=self.n, u=len(self.keys()))
return Cx
<|end_body_1|>
| (INTERNAL) "Uniquify" floats. | _Ufloats | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Ufloats:
"""(INTERNAL) "Uniquify" floats."""
def __call__(self, *fs):
"""Return a tuple of "uniquified" floats."""
<|body_0|>
def _Coeffs(self, ALorder, coeffs):
"""Return C{coeffs} (C{_Coeffs}, I{embellished})."""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_029430 | 7,992 | permissive | [
{
"docstring": "Return a tuple of \"uniquified\" floats.",
"name": "__call__",
"signature": "def __call__(self, *fs)"
},
{
"docstring": "Return C{coeffs} (C{_Coeffs}, I{embellished}).",
"name": "_Coeffs",
"signature": "def _Coeffs(self, ALorder, coeffs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000958 | Implement the Python class `_Ufloats` described below.
Class description:
(INTERNAL) "Uniquify" floats.
Method signatures and docstrings:
- def __call__(self, *fs): Return a tuple of "uniquified" floats.
- def _Coeffs(self, ALorder, coeffs): Return C{coeffs} (C{_Coeffs}, I{embellished}). | Implement the Python class `_Ufloats` described below.
Class description:
(INTERNAL) "Uniquify" floats.
Method signatures and docstrings:
- def __call__(self, *fs): Return a tuple of "uniquified" floats.
- def _Coeffs(self, ALorder, coeffs): Return C{coeffs} (C{_Coeffs}, I{embellished}).
<|skeleton|>
class _Ufloats:... | eba35704b248a7a0388b30f3cea19793921e99b7 | <|skeleton|>
class _Ufloats:
"""(INTERNAL) "Uniquify" floats."""
def __call__(self, *fs):
"""Return a tuple of "uniquified" floats."""
<|body_0|>
def _Coeffs(self, ALorder, coeffs):
"""Return C{coeffs} (C{_Coeffs}, I{embellished})."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Ufloats:
"""(INTERNAL) "Uniquify" floats."""
def __call__(self, *fs):
"""Return a tuple of "uniquified" floats."""
self.n += len(fs)
_f = self.setdefault
return tuple((_f(f, f) for f in map(float, fs)))
def _Coeffs(self, ALorder, coeffs):
"""Return C{coeffs} ... | the_stack_v2_python_sparse | pygeodesy/auxilats/auxily.py | mrJean1/PyGeodesy | train | 283 |
a8fa2cc612ce097403898bc641de3f44dcab82b7 | [
"queryset = RoleUser.objects.all()\nserializer = RoleUserDetailSerializer(queryset, many=True, context={'request': request})\nreturn Response(serializer.data)",
"serializer = RoleUserSerializer(data=request.data)\nif serializer.is_valid():\n role_user = serializer.save()\n return Response(RoleUserDetailSeri... | <|body_start_0|>
queryset = RoleUser.objects.all()
serializer = RoleUserDetailSerializer(queryset, many=True, context={'request': request})
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = RoleUserSerializer(data=request.data)
if serializer.is_valid(... | Configuration role by user. | RoleUserViewSet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleUserViewSet:
"""Configuration role by user."""
def list(self, request):
"""Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages: - code: 400 message: BAD REQUEST - code: 200 message: O... | stack_v2_sparse_classes_36k_train_029431 | 6,899 | permissive | [
{
"docstring": "Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages: - code: 400 message: BAD REQUEST - code: 200 message: OK - code: 201 message: CREATED - code: 500 message: INTERNAL SERVER ERROR consumes: - appli... | 6 | null | Implement the Python class `RoleUserViewSet` described below.
Class description:
Configuration role by user.
Method signatures and docstrings:
- def list(self, request): Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages... | Implement the Python class `RoleUserViewSet` described below.
Class description:
Configuration role by user.
Method signatures and docstrings:
- def list(self, request): Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages... | 7349ce18f56658d67daedf5e1abb352b5c15a029 | <|skeleton|>
class RoleUserViewSet:
"""Configuration role by user."""
def list(self, request):
"""Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages: - code: 400 message: BAD REQUEST - code: 200 message: O... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleUserViewSet:
"""Configuration role by user."""
def list(self, request):
"""Configuration role by user. --- serializer: RoleUserSerializer response_serializer: RoleUserDetailSerializer omit_serializer: false responseMessages: - code: 400 message: BAD REQUEST - code: 200 message: OK - code: 201... | the_stack_v2_python_sparse | src/tandlr/security_configuration/viewsets.py | shrmoud/schoolapp | train | 0 |
ed370112a5656e31165a3f31631ed44153b7b785 | [
"if not self._is_server_configured():\n return ({'msg': 'This server does not support VPN'}, HTTPStatus.NOT_IMPLEMENTED)\ntry:\n vpn_connector = EduVPNConnector(self.config['vpn_server'])\n ovpn_config = vpn_connector.get_ovpn_config()\nexcept VPNPortalAuthException as e:\n log.error('Could not obtain V... | <|body_start_0|>
if not self._is_server_configured():
return ({'msg': 'This server does not support VPN'}, HTTPStatus.NOT_IMPLEMENTED)
try:
vpn_connector = EduVPNConnector(self.config['vpn_server'])
ovpn_config = vpn_connector.get_ovpn_config()
except VPNPorta... | VPNConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VPNConfig:
def get(self):
"""Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN server. This endpoint is not accessible for users, but only for authenticated nodes. responses: 200: d... | stack_v2_sparse_classes_36k_train_029432 | 19,105 | permissive | [
{
"docstring": "Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN server. This endpoint is not accessible for users, but only for authenticated nodes. responses: 200: description: Ok 500: description: Erro... | 3 | stack_v2_sparse_classes_30k_val_000285 | Implement the Python class `VPNConfig` described below.
Class description:
Implement the VPNConfig class.
Method signatures and docstrings:
- def get(self): Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN serv... | Implement the Python class `VPNConfig` described below.
Class description:
Implement the VPNConfig class.
Method signatures and docstrings:
- def get(self): Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN serv... | b3ff6e91ac4caeaf31c12c20f73dfc61cfd9baca | <|skeleton|>
class VPNConfig:
def get(self):
"""Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN server. This endpoint is not accessible for users, but only for authenticated nodes. responses: 200: d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VPNConfig:
def get(self):
"""Get OVPN configuration file --- description: >- Returns the contents of an OVPN configuration file. This configuration allows the node to connect to the VPN server. This endpoint is not accessible for users, but only for authenticated nodes. responses: 200: description: Ok... | the_stack_v2_python_sparse | vantage6-server/vantage6/server/resource/vpn.py | vantage6/vantage6 | train | 15 | |
a68b9565a97edec62497eafc94f3d89a1e5616cc | [
"Part = self.old_state.apps.get_model('part', 'part')\nCompany = self.old_state.apps.get_model('company', 'company')\nSupplierPart = self.old_state.apps.get_model('company', 'supplierpart')\nself.part = Part.objects.create(name='PART', description='A purchaseable part', purchaseable=True, level=0, tree_id=0, lft=0,... | <|body_start_0|>
Part = self.old_state.apps.get_model('part', 'part')
Company = self.old_state.apps.get_model('company', 'company')
SupplierPart = self.old_state.apps.get_model('company', 'supplierpart')
self.part = Part.objects.create(name='PART', description='A purchaseable part', purc... | Test that the supplier part quantity is correctly migrated. | TestSupplierPartQuantity | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSupplierPartQuantity:
"""Test that the supplier part quantity is correctly migrated."""
def prepare(self):
"""Prepare a number of SupplierPart objects"""
<|body_0|>
def test_supplier_part_quantity(self):
"""Test that the supplier part quantity is correctly mi... | stack_v2_sparse_classes_36k_train_029433 | 12,626 | permissive | [
{
"docstring": "Prepare a number of SupplierPart objects",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the supplier part quantity is correctly migrated.",
"name": "test_supplier_part_quantity",
"signature": "def test_supplier_part_quantity(self)"
}
... | 2 | null | Implement the Python class `TestSupplierPartQuantity` described below.
Class description:
Test that the supplier part quantity is correctly migrated.
Method signatures and docstrings:
- def prepare(self): Prepare a number of SupplierPart objects
- def test_supplier_part_quantity(self): Test that the supplier part qua... | Implement the Python class `TestSupplierPartQuantity` described below.
Class description:
Test that the supplier part quantity is correctly migrated.
Method signatures and docstrings:
- def prepare(self): Prepare a number of SupplierPart objects
- def test_supplier_part_quantity(self): Test that the supplier part qua... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestSupplierPartQuantity:
"""Test that the supplier part quantity is correctly migrated."""
def prepare(self):
"""Prepare a number of SupplierPart objects"""
<|body_0|>
def test_supplier_part_quantity(self):
"""Test that the supplier part quantity is correctly mi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSupplierPartQuantity:
"""Test that the supplier part quantity is correctly migrated."""
def prepare(self):
"""Prepare a number of SupplierPart objects"""
Part = self.old_state.apps.get_model('part', 'part')
Company = self.old_state.apps.get_model('company', 'company')
... | the_stack_v2_python_sparse | InvenTree/company/test_migrations.py | inventree/InvenTree | train | 3,077 |
2b896966bd93afb60e6662b5400c54aa3edef7ff | [
"full_layer_specs = []\nfor i, layer_spec in enumerate(layer_specs):\n full_layer_spec = [3, layer_spec[0], layer_spec[1], 1]\n full_layer_specs.append(full_layer_spec)\nsuper().__init__(name=name, layer_specs=full_layer_specs, activation_fn=activation_fn, last_activation_fn=None, regularizer=regularizer, pad... | <|body_start_0|>
full_layer_specs = []
for i, layer_spec in enumerate(layer_specs):
full_layer_spec = [3, layer_spec[0], layer_spec[1], 1]
full_layer_specs.append(full_layer_spec)
super().__init__(name=name, layer_specs=full_layer_specs, activation_fn=activation_fn, last_... | UpSamplingConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_... | stack_v2_sparse_classes_36k_train_029434 | 6,555 | no_license | [
{
"docstring": ":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_output_features, dilation]. :param activation_fn: Tensorflow activation function. This will not be applied on the la... | 2 | stack_v2_sparse_classes_30k_train_006554 | Implement the Python class `UpSamplingConnection` described below.
Class description:
Implement the UpSamplingConnection class.
Method signatures and docstrings:
- def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None): :param name: Str. For variable scoping. :param layer_specs: Array of sh... | Implement the Python class `UpSamplingConnection` described below.
Class description:
Implement the UpSamplingConnection class.
Method signatures and docstrings:
- def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None): :param name: Str. For variable scoping. :param layer_specs: Array of sh... | 494d503c729ba018614fc742f1aee1e48d37127e | <|skeleton|>
class UpSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpSamplingConnection:
def __init__(self, name, layer_specs, activation_fn=leaky_relu, regularizer=None):
""":param name: Str. For variable scoping. :param layer_specs: Array of shape [num_layers, 2]. Constrained version of parent class' layer_specs. The second dimension consists of [num_output_feature... | the_stack_v2_python_sparse | context_interp/gridnet/connections/connections.py | NeedsMorePie/interpolator | train | 2 | |
d62536d7bfe2d381f9f64418358bc96eba9965f4 | [
"if not root:\n return 0\nleft = self.maxDepth(root.left)\nright = self.maxDepth(root.right)\nreturn max(left, right) + 1",
"if not root:\n return 0\nstack = [root]\ncur = root\nres = 0\nwhile stack:\n n = len(stack)\n for i in range(n):\n cur = stack.pop(0)\n if cur.left:\n s... | <|body_start_0|>
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
stack = [root]
cur = root
res = 0
wh... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return 0
left = self... | stack_v2_sparse_classes_36k_train_029435 | 1,436 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019254 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(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 maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, root... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
if not root:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left, right) + 1
def maxDepth(self, root):
""":type root: TreeNode :rty... | the_stack_v2_python_sparse | 剑指 Offer 55 - I. 二叉树的深度.py | yangyuxiang1996/leetcode | train | 0 | |
1cb40013026a4eed5d3e083e020c8372f267ebb9 | [
"assert tx_mat.ndim == 4 or tx_mat.ndim == 3, 'Transition matrix wrong dims ({} != 3 or 4)'.format(tx_mat.ndim)\nassert r_mat.ndim == 4 or r_mat.ndim == 3, 'Reward matrix wrong dims ({} != 3 or 4)'.format(tx_mat.ndim)\nassert r_mat.shape == tx_mat.shape, 'Transition / Reward matricies not the same shape!'\nassert t... | <|body_start_0|>
assert tx_mat.ndim == 4 or tx_mat.ndim == 3, 'Transition matrix wrong dims ({} != 3 or 4)'.format(tx_mat.ndim)
assert r_mat.ndim == 4 or r_mat.ndim == 3, 'Reward matrix wrong dims ({} != 3 or 4)'.format(tx_mat.ndim)
assert r_mat.shape == tx_mat.shape, 'Transition / Reward matric... | MatrixMDP | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatrixMDP:
def __init__(self, tx_mat, r_mat, p_initial_state=None, p_mixture=None):
"""__init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or (n_actions x n_states x n_states) :param r_mat: Reward matrix of shape (n_components x n_actions x... | stack_v2_sparse_classes_36k_train_029436 | 21,162 | permissive | [
{
"docstring": "__init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or (n_actions x n_states x n_states) :param r_mat: Reward matrix of shape (n_components x n_actions x n_states x n_states) or (n_actions x n_states x n_states) :param p_initial_state: Probability ... | 4 | stack_v2_sparse_classes_30k_train_006730 | Implement the Python class `MatrixMDP` described below.
Class description:
Implement the MatrixMDP class.
Method signatures and docstrings:
- def __init__(self, tx_mat, r_mat, p_initial_state=None, p_mixture=None): __init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or ... | Implement the Python class `MatrixMDP` described below.
Class description:
Implement the MatrixMDP class.
Method signatures and docstrings:
- def __init__(self, tx_mat, r_mat, p_initial_state=None, p_mixture=None): __init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or ... | d6878a0fe06fda09f8ed9d5069731af0e148cf34 | <|skeleton|>
class MatrixMDP:
def __init__(self, tx_mat, r_mat, p_initial_state=None, p_mixture=None):
"""__init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or (n_actions x n_states x n_states) :param r_mat: Reward matrix of shape (n_components x n_actions x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatrixMDP:
def __init__(self, tx_mat, r_mat, p_initial_state=None, p_mixture=None):
"""__init__ :param tx_mat: Transition matrix of shape (n_components x n_actions x n_states x n_states) or (n_actions x n_states x n_states) :param r_mat: Reward matrix of shape (n_components x n_actions x n_states x n_... | the_stack_v2_python_sparse | src/sepsis_simulator/cf/counterfactual.py | dtak/POPCORN-POMDP | train | 9 | |
d3a202fddc192e28366477f14c345a12dc114bd5 | [
"cu = Change_Param(username, password, prod)\ngu = cu.get_params()\nself.suffix = self.c.get_value('Deal', 'trade_promotion')\nself.url = self.url_joint(prod) + gu[1]\nlogs.info('test url:%s' % self.url)\nreturn self.post_requests(self.url, gu[0], data)",
"cu = Change_Param(username, password, prod)\ngu = cu.get_... | <|body_start_0|>
cu = Change_Param(username, password, prod)
gu = cu.get_params()
self.suffix = self.c.get_value('Deal', 'trade_promotion')
self.url = self.url_joint(prod) + gu[1]
logs.info('test url:%s' % self.url)
return self.post_requests(self.url, gu[0], data)
<|end_b... | Trade_promotion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trade_promotion:
def post_tarde_promotion(self, username=None, password=None, data=None, prod=None):
"""相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型"""
<|body_0|>
def del_tarde_create(self, username=None, password=None, data=None, prod=None):
... | stack_v2_sparse_classes_36k_train_029437 | 4,204 | no_license | [
{
"docstring": "相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型",
"name": "post_tarde_promotion",
"signature": "def post_tarde_promotion(self, username=None, password=None, data=None, prod=None)"
},
{
"docstring": "相关参数有: seller_id 卖家id sku_id 产品id sellerId sellerId skuId ... | 4 | stack_v2_sparse_classes_30k_train_019719 | Implement the Python class `Trade_promotion` described below.
Class description:
Implement the Trade_promotion class.
Method signatures and docstrings:
- def post_tarde_promotion(self, username=None, password=None, data=None, prod=None): 相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型
- def del... | Implement the Python class `Trade_promotion` described below.
Class description:
Implement the Trade_promotion class.
Method signatures and docstrings:
- def post_tarde_promotion(self, username=None, password=None, data=None, prod=None): 相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型
- def del... | 235200a67c1fb125f75f9771808f6655a7b14202 | <|skeleton|>
class Trade_promotion:
def post_tarde_promotion(self, username=None, password=None, data=None, prod=None):
"""相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型"""
<|body_0|>
def del_tarde_create(self, username=None, password=None, data=None, prod=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trade_promotion:
def post_tarde_promotion(self, username=None, password=None, data=None, prod=None):
"""相关参数有: seller_id 卖家id sku_id 产品id activity_id 活动id promotion_type 活动类型"""
cu = Change_Param(username, password, prod)
gu = cu.get_params()
self.suffix = self.c.get_value('Dea... | the_stack_v2_python_sparse | business/deal/trade_promotion.py | vothin/requsets_test | train | 0 | |
32400b804cd97bfff8b87d952c34e7e5088be414 | [
"self.logger = logger\nself.is_trained = False\nself.supported_formats = ['pkl', 'onnx', 'pmml']\nself.name = 'SVM'\nself.centroids = None\nself.sigma = None\nself.weights = None",
"sqrtDists = cdist(setDim1, setDim2, 'euclidean')\ngamma = 1 / self.sigma ** 2\nreturn np.exp(-gamma * np.power(sqrtDists, 2))",
"K... | <|body_start_0|>
self.logger = logger
self.is_trained = False
self.supported_formats = ['pkl', 'onnx', 'pmml']
self.name = 'SVM'
self.centroids = None
self.sigma = None
self.weights = None
<|end_body_0|>
<|body_start_1|>
sqrtDists = cdist(setDim1, setDim2... | This class contains the Semiparametric SVM model. | SVM_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SVM_model:
"""This class contains the Semiparametric SVM model."""
def __init__(self, logger):
"""Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
<|body_0|>
def kernelMatrix(self, setDim1, setDim2)... | stack_v2_sparse_classes_36k_train_029438 | 18,427 | permissive | [
{
"docstring": "Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.",
"name": "__init__",
"signature": "def __init__(self, logger)"
},
{
"docstring": "Computes a kernel matrix given two datasets. Parameters ---------- setDim1: nd... | 3 | stack_v2_sparse_classes_30k_train_004056 | Implement the Python class `SVM_model` described below.
Class description:
This class contains the Semiparametric SVM model.
Method signatures and docstrings:
- def __init__(self, logger): Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.
- def kern... | Implement the Python class `SVM_model` described below.
Class description:
This class contains the Semiparametric SVM model.
Method signatures and docstrings:
- def __init__(self, logger): Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance.
- def kern... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class SVM_model:
"""This class contains the Semiparametric SVM model."""
def __init__(self, logger):
"""Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
<|body_0|>
def kernelMatrix(self, setDim1, setDim2)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SVM_model:
"""This class contains the Semiparametric SVM model."""
def __init__(self, logger):
"""Create a :class:`SVM_model` instance. Parameters ---------- logger: :class:`mylogging.Logger` Logging object instance."""
self.logger = logger
self.is_trained = False
self.sup... | the_stack_v2_python_sparse | MMLL/models/POM3/SVM/SVM.py | Musketeer-H2020/MMLL-Robust | train | 0 |
cc4ef721a8f08a4a42d31990909e67f6b354adf4 | [
"if zipfile.is_zipfile(filename) is False:\n return False\nz = zipfile.ZipFile(filename, 'r')\nreturn any((x.endswith('annotation.xml') for x in z.namelist()))",
"if name is None:\n name = self.__class__.__name__\nsuper(sppasANT, self).__init__(name)\nself.default_extension = 'ant'\nself._accept_multi_tiers... | <|body_start_0|>
if zipfile.is_zipfile(filename) is False:
return False
z = zipfile.ZipFile(filename, 'r')
return any((x.endswith('annotation.xml') for x in z.namelist()))
<|end_body_0|>
<|body_start_1|>
if name is None:
name = self.__class__.__name__
sup... | AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZIPPED directory. | sppasANT | [
"GPL-3.0-only",
"MIT",
"GFDL-1.1-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sppasANT:
"""AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZIPPED directory."""
def detect(file... | stack_v2_sparse_classes_36k_train_029439 | 25,982 | permissive | [
{
"docstring": "Check whether a file is of ANT format or not. :param filename: (str) Name of the file to check. :returns: (bool)",
"name": "detect",
"signature": "def detect(filename)"
},
{
"docstring": "Initialize a new sppasANT instance. :param name: (str) This transcription name.",
"name"... | 4 | null | Implement the Python class `sppasANT` described below.
Class description:
AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZI... | Implement the Python class `sppasANT` described below.
Class description:
AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZI... | 3167b65f576abcc27a8767d24c274a04712bd948 | <|skeleton|>
class sppasANT:
"""AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZIPPED directory."""
def detect(file... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sppasANT:
"""AnnotationPro ANT reader and writer. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi An ANT file is a ZIPPED directory."""
def detect(filename):
... | the_stack_v2_python_sparse | sppas/sppas/src/anndata/aio/annotationpro.py | mirfan899/MTTS | train | 0 |
7d35545b6372aec057a4a78c9d8a50f8c8eacd90 | [
"try:\n BinarySearchTree()\nexcept:\n self.fail('Error while constructing a BinarySearchTree')",
"itemcount = 26\nitems = []\nfor i in range(itemcount):\n items.append((i, chr(ord('a') + i)))\nrandom.shuffle(items)\nbintree = BinarySearchTree()\nfor key, value in items:\n bintree[key] = value\nself.as... | <|body_start_0|>
try:
BinarySearchTree()
except:
self.fail('Error while constructing a BinarySearchTree')
<|end_body_0|>
<|body_start_1|>
itemcount = 26
items = []
for i in range(itemcount):
items.append((i, chr(ord('a') + i)))
random.... | TestProblem5 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Is BinarySearchTree constructable?"""
<|body_0|>
def test_storeAndLoad(self):
"""P5: Can items be stored and retrieved from the BinarySearchTree?"""
<|body_1|>
def test_updates(self):
"""P5: C... | stack_v2_sparse_classes_36k_train_029440 | 11,207 | no_license | [
{
"docstring": "P5: Sanity Test: Is BinarySearchTree constructable?",
"name": "test_API",
"signature": "def test_API(self)"
},
{
"docstring": "P5: Can items be stored and retrieved from the BinarySearchTree?",
"name": "test_storeAndLoad",
"signature": "def test_storeAndLoad(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_003162 | Implement the Python class `TestProblem5` described below.
Class description:
Implement the TestProblem5 class.
Method signatures and docstrings:
- def test_API(self): P5: Sanity Test: Is BinarySearchTree constructable?
- def test_storeAndLoad(self): P5: Can items be stored and retrieved from the BinarySearchTree?
- ... | Implement the Python class `TestProblem5` described below.
Class description:
Implement the TestProblem5 class.
Method signatures and docstrings:
- def test_API(self): P5: Sanity Test: Is BinarySearchTree constructable?
- def test_storeAndLoad(self): P5: Can items be stored and retrieved from the BinarySearchTree?
- ... | d4f32507a5f581ad8ee0ce84e6cd92daac0941d7 | <|skeleton|>
class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Is BinarySearchTree constructable?"""
<|body_0|>
def test_storeAndLoad(self):
"""P5: Can items be stored and retrieved from the BinarySearchTree?"""
<|body_1|>
def test_updates(self):
"""P5: C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestProblem5:
def test_API(self):
"""P5: Sanity Test: Is BinarySearchTree constructable?"""
try:
BinarySearchTree()
except:
self.fail('Error while constructing a BinarySearchTree')
def test_storeAndLoad(self):
"""P5: Can items be stored and retrieve... | the_stack_v2_python_sparse | Homework5/hw5_test.py | pillowfication/ECS-32B | train | 1 | |
925baeaed88d3d17922e332c79942d541b8f87db | [
"database.drop_data()\nself.assertEqual(database.show_available_products(), {})\nwith self.assertRaises(FileNotFoundError):\n result = database.import_data('data2', 'p.csv', 'c.csv', 'r.csv')\nresult = database.import_data('data', 'products.csv', 'customers.csv', 'rentals.csv')\nself.assertEqual(result[0][0], 5)... | <|body_start_0|>
database.drop_data()
self.assertEqual(database.show_available_products(), {})
with self.assertRaises(FileNotFoundError):
result = database.import_data('data2', 'p.csv', 'c.csv', 'r.csv')
result = database.import_data('data', 'products.csv', 'customers.csv', '... | Tests for population and data integrity of database. | RentalDbTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
<|body_0|>
def test_2_show_available(self):
"""Test the integrity of the returned dictionary of available prod... | stack_v2_sparse_classes_36k_train_029441 | 4,281 | no_license | [
{
"docstring": "Test that the records are successfully imported.",
"name": "test_1_import",
"signature": "def test_1_import(self)"
},
{
"docstring": "Test the integrity of the returned dictionary of available products. We particularly want to validate that quantity_available is deducted to accou... | 3 | null | Implement the Python class `RentalDbTest` described below.
Class description:
Tests for population and data integrity of database.
Method signatures and docstrings:
- def test_1_import(self): Test that the records are successfully imported.
- def test_2_show_available(self): Test the integrity of the returned diction... | Implement the Python class `RentalDbTest` described below.
Class description:
Tests for population and data integrity of database.
Method signatures and docstrings:
- def test_1_import(self): Test that the records are successfully imported.
- def test_2_show_available(self): Test the integrity of the returned diction... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
<|body_0|>
def test_2_show_available(self):
"""Test the integrity of the returned dictionary of available prod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RentalDbTest:
"""Tests for population and data integrity of database."""
def test_1_import(self):
"""Test that the records are successfully imported."""
database.drop_data()
self.assertEqual(database.show_available_products(), {})
with self.assertRaises(FileNotFoundError):... | the_stack_v2_python_sparse | students/shodges/lesson10/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
3c4b114a9c3eed4783d30677fe874c8ddcefa2dc | [
"super().__init__()\nself.action_bias = action_bias\nself.action_scale = action_scale\nself.shared_net = nn.Sequential(nn.Linear(input_shape[0], hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU())\nself.mean_layer = nn.Linear(hidden_size, n_actions)\nself.logstd_layer = nn.Linear(hidden_size, n... | <|body_start_0|>
super().__init__()
self.action_bias = action_bias
self.action_scale = action_scale
self.shared_net = nn.Sequential(nn.Linear(input_shape[0], hidden_size), nn.ReLU(), nn.Linear(hidden_size, hidden_size), nn.ReLU())
self.mean_layer = nn.Linear(hidden_size, n_action... | MLP network that outputs continuous value via Gaussian distribution. | ContinuousMLP | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_a... | stack_v2_sparse_classes_36k_train_029442 | 15,112 | permissive | [
{
"docstring": "Args: input_shape: observation shape of the environment n_actions: dimension of actions in the environment hidden_size: size of hidden layers action_bias: the center of the action space action_scale: the scale of the action space",
"name": "__init__",
"signature": "def __init__(self, inp... | 3 | stack_v2_sparse_classes_30k_train_000336 | Implement the Python class `ContinuousMLP` described below.
Class description:
MLP network that outputs continuous value via Gaussian distribution.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None: Ar... | Implement the Python class `ContinuousMLP` described below.
Class description:
MLP network that outputs continuous value via Gaussian distribution.
Method signatures and docstrings:
- def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None: Ar... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContinuousMLP:
"""MLP network that outputs continuous value via Gaussian distribution."""
def __init__(self, input_shape: Tuple[int], n_actions: int, hidden_size: int=128, action_bias: int=0, action_scale: int=1) -> None:
"""Args: input_shape: observation shape of the environment n_actions: dimen... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/networks.py | Lightning-Universe/lightning-bolts | train | 76 |
e14c53ddde42953ccf163f31c76c8594edf7f20e | [
"hypers = self._list_hypervisors()\nself.assertNotEmpty(hypers, 'No hypervisors found.')\nhostname = hypers[0]['hypervisor_hostname']\nhypervisors = self.client.list_servers_on_hypervisor(hostname)['hypervisors']\nself.assertNotEmpty(hypervisors)",
"hypers = self._list_hypervisors()\nself.assertNotEmpty(hypers, '... | <|body_start_0|>
hypers = self._list_hypervisors()
self.assertNotEmpty(hypers, 'No hypervisors found.')
hostname = hypers[0]['hypervisor_hostname']
hypervisors = self.client.list_servers_on_hypervisor(hostname)['hypervisors']
self.assertNotEmpty(hypervisors)
<|end_body_0|>
<|bod... | Tests Hypervisors API below 2.53 that require admin privileges | HypervisorAdminUnderV252Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HypervisorAdminUnderV252Test:
"""Tests Hypervisors API below 2.53 that require admin privileges"""
def test_get_hypervisor_show_servers(self):
"""Test showing instances about the specific hypervisors"""
<|body_0|>
def test_search_hypervisor(self):
"""Test searchi... | stack_v2_sparse_classes_36k_train_029443 | 6,975 | permissive | [
{
"docstring": "Test showing instances about the specific hypervisors",
"name": "test_get_hypervisor_show_servers",
"signature": "def test_get_hypervisor_show_servers(self)"
},
{
"docstring": "Test searching for hypervisors by its name",
"name": "test_search_hypervisor",
"signature": "de... | 2 | null | Implement the Python class `HypervisorAdminUnderV252Test` described below.
Class description:
Tests Hypervisors API below 2.53 that require admin privileges
Method signatures and docstrings:
- def test_get_hypervisor_show_servers(self): Test showing instances about the specific hypervisors
- def test_search_hyperviso... | Implement the Python class `HypervisorAdminUnderV252Test` described below.
Class description:
Tests Hypervisors API below 2.53 that require admin privileges
Method signatures and docstrings:
- def test_get_hypervisor_show_servers(self): Test showing instances about the specific hypervisors
- def test_search_hyperviso... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class HypervisorAdminUnderV252Test:
"""Tests Hypervisors API below 2.53 that require admin privileges"""
def test_get_hypervisor_show_servers(self):
"""Test showing instances about the specific hypervisors"""
<|body_0|>
def test_search_hypervisor(self):
"""Test searchi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HypervisorAdminUnderV252Test:
"""Tests Hypervisors API below 2.53 that require admin privileges"""
def test_get_hypervisor_show_servers(self):
"""Test showing instances about the specific hypervisors"""
hypers = self._list_hypervisors()
self.assertNotEmpty(hypers, 'No hypervisors ... | the_stack_v2_python_sparse | tempest/api/compute/admin/test_hypervisor.py | openstack/tempest | train | 270 |
80fff1582798aed0a2cc0b60af1a0347eaed5e9d | [
"l, r = (0, len(numbers) - 1)\nwhile l < r:\n s = numbers[l] + numbers[r]\n if s < target:\n l += 1\n elif s > target:\n r -= 1\n else:\n return [l + 1, r + 1]",
"for i in range(len(numbers)):\n l, r = (i + 1, len(numbers) - 1)\n while l <= r:\n mid = (l + r) // 2\n ... | <|body_start_0|>
l, r = (0, len(numbers) - 1)
while l < r:
s = numbers[l] + numbers[r]
if s < target:
l += 1
elif s > target:
r -= 1
else:
return [l + 1, r + 1]
<|end_body_0|>
<|body_start_1|>
for i ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def TwoPointers(self, numbers, target):
""":type numbers: List[int], target: int :rtype: List[int]"""
<|body_0|>
def BinarySearch(self, numbers, target):
""":type numbers: List[int], target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_029444 | 980 | no_license | [
{
"docstring": ":type numbers: List[int], target: int :rtype: List[int]",
"name": "TwoPointers",
"signature": "def TwoPointers(self, numbers, target)"
},
{
"docstring": ":type numbers: List[int], target: int :rtype: List[int]",
"name": "BinarySearch",
"signature": "def BinarySearch(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def TwoPointers(self, numbers, target): :type numbers: List[int], target: int :rtype: List[int]
- def BinarySearch(self, numbers, target): :type numbers: List[int], target: int :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def TwoPointers(self, numbers, target): :type numbers: List[int], target: int :rtype: List[int]
- def BinarySearch(self, numbers, target): :type numbers: List[int], target: int :... | 885a9af8a7bee3c228c7ae4e295dca810bd91d01 | <|skeleton|>
class Solution:
def TwoPointers(self, numbers, target):
""":type numbers: List[int], target: int :rtype: List[int]"""
<|body_0|>
def BinarySearch(self, numbers, target):
""":type numbers: List[int], target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def TwoPointers(self, numbers, target):
""":type numbers: List[int], target: int :rtype: List[int]"""
l, r = (0, len(numbers) - 1)
while l < r:
s = numbers[l] + numbers[r]
if s < target:
l += 1
elif s > target:
... | the_stack_v2_python_sparse | Python/167.py | kevin851066/Leetcode | train | 0 | |
c11d4f8f3efcc03f3382be77608d2526ae21ebf9 | [
"super(RebCurrentLimits, self).__init__()\nself.rebps = rebps\nself.ts8 = ts8\nself.logger = rebps.logger\nself['DigI'] = ChannelLimits('digital.IbefLDO', 450.0, 560.0, 100.0)\nself['AnaI'] = ChannelLimits('analog.IbefLDO', 500.0, 660.0, 50.0)\nself['ClkHI'] = ChannelLimits('clockhi.IbefLDO', 80.0, 180.0, 25.0)\nse... | <|body_start_0|>
super(RebCurrentLimits, self).__init__()
self.rebps = rebps
self.ts8 = ts8
self.logger = rebps.logger
self['DigI'] = ChannelLimits('digital.IbefLDO', 450.0, 560.0, 100.0)
self['AnaI'] = ChannelLimits('analog.IbefLDO', 500.0, 660.0, 50.0)
self['Clk... | Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps. | RebCurrentLimits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, re... | stack_v2_sparse_classes_36k_train_029445 | 4,646 | no_license | [
{
"docstring": "Parameters ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator.",
"name": "__init__",
"signature": "def __init__(self, rebps, ts8)"
},
{
"docstring": "C... | 3 | stack_v2_sparse_classes_30k_train_002170 | Implement the Python class `RebCurrentLimits` described below.
Class description:
Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from se... | Implement the Python class `RebCurrentLimits` described below.
Class description:
Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from se... | e6768df4b72c3b99cb9f7c3985a951b359b39c05 | <|skeleton|>
class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RebCurrentLimits:
"""Attributes ---------- rebps : CCS subsystem object REB power supply subsystem, decorated by SubsystemDecorator. ts8 : CCS subsystem object TS8 raft subsystem, decorated by SubsystemDecorator. logger : Logging.Logger Logger object from self.rebps."""
def __init__(self, rebps, ts8):
... | the_stack_v2_python_sparse | python/rebCurrentLimits.py | lsst-camera-dh/CR-jobs | train | 0 |
54a21407f58a16fe6d5f82c873890f7506f24ffe | [
"if not len(s):\n return 0\nresult = 1\nfor i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n flag = s[i:j]\n if len(set(flag)) == len(flag):\n result = result if result > len(flag) else len(flag)\nreturn result",
"result, i, j = (0, 0, 0)\nflag = set()\nwhile i < len(s) an... | <|body_start_0|>
if not len(s):
return 0
result = 1
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
flag = s[i:j]
if len(set(flag)) == len(flag):
result = result if result > len(flag) else len(flag)
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
"""暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
"""检查字符串是否重复,设置一个初试字符串flag。 遍历s字符串,当右边添加一个判断是否重复,当重复的话就删除左边的字符串。 时间复杂度:O(2n) 空间复... | stack_v2_sparse_classes_36k_train_029446 | 2,172 | no_license | [
{
"docstring": "暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": "检查字符串是否重复,设置一个初试字符串flag。 遍历s字符串,当右边添加一个判断是否重复,当重复的话就删除左边的字符串。 时间复杂度:O(2n) 空间复杂度:O(min(m,n... | 3 | stack_v2_sparse_classes_30k_train_001418 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): 暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int
- def lengthOfLongestSubstring1(self, s): 检查字符串是否重复,设置一个初试... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): 暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int
- def lengthOfLongestSubstring1(self, s): 检查字符串是否重复,设置一个初试... | f5de348cbc00fc24ca0282235fac6d819817d005 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
"""暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring1(self, s):
"""检查字符串是否重复,设置一个初试字符串flag。 遍历s字符串,当右边添加一个判断是否重复,当重复的话就删除左边的字符串。 时间复杂度:O(2n) 空间复... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
"""暴力方法,直接全部遍历,但是会超时。 会检验返回在[i, j)的字符是否都是唯一的。 时间复杂度:O(n^3) :type s: str :rtype: int"""
if not len(s):
return 0
result = 1
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
flag = s... | the_stack_v2_python_sparse | 1-10/3.py | hubogle/PythonCode | train | 0 | |
976a9822f0280abefb4ca2aa8d1ff24f0598e8e2 | [
"super(focal_loss, self).__init__()\nself.alpha = alpha\nself.gamma = gamma\nself.logits = with_logits",
"if self.logits:\n CE_loss = F.binary_cross_entropy_with_logits(prediction, labels)\nelse:\n CE_loss = F.binary_cross_entropy(prediction, labels)\npt = torch.exp(-CE_loss)\nF_loss = self.alpha * (1 - pt)... | <|body_start_0|>
super(focal_loss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.logits = with_logits
<|end_body_0|>
<|body_start_1|>
if self.logits:
CE_loss = F.binary_cross_entropy_with_logits(prediction, labels)
else:
CE_loss = F.... | Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "balance" coefficient, gamma (float): "foc... | focal_loss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "bal... | stack_v2_sparse_classes_36k_train_029447 | 6,385 | permissive | [
{
"docstring": "Parameter initialization",
"name": "__init__",
"signature": "def __init__(self, alpha: int=0.5, gamma: int=2, with_logits: bool=True) -> None"
},
{
"docstring": "Calculates loss",
"name": "forward",
"signature": "def forward(self, prediction: torch.Tensor, labels: torch.T... | 2 | stack_v2_sparse_classes_30k_train_008290 | Implement the Python class `focal_loss` described below.
Class description:
Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/ab... | Implement the Python class `focal_loss` described below.
Class description:
Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/ab... | 6d187296074143d017ca8fc60302364cd946b180 | <|skeleton|>
class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "bal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class focal_loss:
"""Loss function for classification tasks with large data imbalance. Focal loss (FL) is define as: FL(p_t) = -alpha*((1-p_t)^gamma))*log(p_t), where p_t is a cross-entropy loss for binary classification. For more details, see https://arxiv.org/abs/1708.02002. Args: alpha (float): "balance" coeffic... | the_stack_v2_python_sparse | atomai/losses_metrics/losses.py | pycroscopy/atomai | train | 157 |
76c4c118604dbe89e244db1163048a31835fd479 | [
"import clipboard\nsett = clipboard.paste()\nmeta = analyse(sett)\nlines = []\nlines.append(gen_constructor(meta))\nlines.append(gen_overrides(meta))\nlines.append(gen_as_map(meta))\ncnt = '\\n\\n'.join(lines)\nprint('---------------------- ✁')\nprint(cnt)\nclipboard.copy(cnt)\nprint('done.')",
"import clipboard\... | <|body_start_0|>
import clipboard
sett = clipboard.paste()
meta = analyse(sett)
lines = []
lines.append(gen_constructor(meta))
lines.append(gen_overrides(meta))
lines.append(gen_as_map(meta))
cnt = '\n\n'.join(lines)
print('---------------------- ✁... | GenTool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenTool:
def gen_model_cls(self):
"""Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime toDate = DateTime.now(); TimeOfDay toTime = const TimeOfDay(hour: 7, minute: 28); // final List<... | stack_v2_sparse_classes_36k_train_029448 | 8,411 | permissive | [
{
"docstring": "Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime toDate = DateTime.now(); TimeOfDay toTime = const TimeOfDay(hour: 7, minute: 28); // final List<String> allActivities = <String>['hiking', 's... | 2 | stack_v2_sparse_classes_30k_train_003896 | Implement the Python class `GenTool` described below.
Class description:
Implement the GenTool class.
Method signatures and docstrings:
- def gen_model_cls(self): Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime ... | Implement the Python class `GenTool` described below.
Class description:
Implement the GenTool class.
Method signatures and docstrings:
- def gen_model_cls(self): Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime ... | 9958d18ee5e75cf9794f546c904097dc1ff4f3a0 | <|skeleton|>
class GenTool:
def gen_model_cls(self):
"""Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime toDate = DateTime.now(); TimeOfDay toTime = const TimeOfDay(hour: 7, minute: 28); // final List<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenTool:
def gen_model_cls(self):
"""Code format: ``` class Schedule extends Equatable { DateTime fromDate= DateTime.now(); TimeOfDay fromTime = const TimeOfDay(hour: 7, minute: 28); DateTime toDate = DateTime.now(); TimeOfDay toTime = const TimeOfDay(hour: 7, minute: 28); // final List<String> allAct... | the_stack_v2_python_sparse | sagas/ofbiz/gen_tool.py | samlet/stack | train | 3 | |
310363a6d254d985219a50da54877da875ae6075 | [
"super().__init__(5, initial_x, initial_y, 1, game_width, game_height, None, None, debug)\nself.scale(100, 50)\nself.set_points(points)",
"self.move_right()\nif self.get_x() > self.game_width:\n self.kill()\n return\nreturn super().update(1)"
] | <|body_start_0|>
super().__init__(5, initial_x, initial_y, 1, game_width, game_height, None, None, debug)
self.scale(100, 50)
self.set_points(points)
<|end_body_0|>
<|body_start_1|>
self.move_right()
if self.get_x() > self.game_width:
self.kill()
return
... | MotherShip | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MotherShip:
def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False):
"""Main constructor for the mothership"""
<|body_0|>
def update(self) -> None:
"""Update movement of the mothership"""
<|body_1|... | stack_v2_sparse_classes_36k_train_029449 | 960 | permissive | [
{
"docstring": "Main constructor for the mothership",
"name": "__init__",
"signature": "def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False)"
},
{
"docstring": "Update movement of the mothership",
"name": "update",
"signatu... | 2 | null | Implement the Python class `MotherShip` described below.
Class description:
Implement the MotherShip class.
Method signatures and docstrings:
- def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False): Main constructor for the mothership
- def update(self) ... | Implement the Python class `MotherShip` described below.
Class description:
Implement the MotherShip class.
Method signatures and docstrings:
- def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False): Main constructor for the mothership
- def update(self) ... | 6f8f2da4fd26ef1d77c0c6183230c3a5e6bf0bb9 | <|skeleton|>
class MotherShip:
def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False):
"""Main constructor for the mothership"""
<|body_0|>
def update(self) -> None:
"""Update movement of the mothership"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MotherShip:
def __init__(self, initial_x: int, initial_y: int, game_width: int, game_height: int, points: int, debug: bool=False):
"""Main constructor for the mothership"""
super().__init__(5, initial_x, initial_y, 1, game_width, game_height, None, None, debug)
self.scale(100, 50)
... | the_stack_v2_python_sparse | gym_invaders/gym_game/envs/classes/Game/Sprites/Mothership.py | Jh123x/Orbital | train | 4 | |
275740dfb7a544d777b30ce37861a05a5218ae9c | [
"from pyraf import iraf\nfrom iraf import stsdas, analysis, dither\niraf.unlearn('drizzle')",
"from pyraf import iraf\nfrom iraf import stsdas, analysis, dither\nif len(data) > 80:\n err_msg = 'File name \"%s\" is too long (>80 chars) for drizzle task' % data\n raise aXeError(err_msg)\nif len(outdata) > 80:... | <|body_start_0|>
from pyraf import iraf
from iraf import stsdas, analysis, dither
iraf.unlearn('drizzle')
<|end_body_0|>
<|body_start_1|>
from pyraf import iraf
from iraf import stsdas, analysis, dither
if len(data) > 80:
err_msg = 'File name "%s" is too long... | Class to wrap drizzle command | Drizzle | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Drizzle:
"""Class to wrap drizzle command"""
def __init__(self):
"""Initializes the class"""
<|body_0|>
def run(self, data, in_mask, outdata, outweig, coeffs, wt_scl, drizzle_params, img_nx, img_ny):
"""Do the drizzling Currently, the basic command is the iraf-ve... | stack_v2_sparse_classes_36k_train_029450 | 23,324 | permissive | [
{
"docstring": "Initializes the class",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Do the drizzling Currently, the basic command is the iraf-version of drizzle, but the pydrizzle version may at some point be used instead.",
"name": "run",
"signature": "def r... | 2 | stack_v2_sparse_classes_30k_train_001942 | Implement the Python class `Drizzle` described below.
Class description:
Class to wrap drizzle command
Method signatures and docstrings:
- def __init__(self): Initializes the class
- def run(self, data, in_mask, outdata, outweig, coeffs, wt_scl, drizzle_params, img_nx, img_ny): Do the drizzling Currently, the basic c... | Implement the Python class `Drizzle` described below.
Class description:
Class to wrap drizzle command
Method signatures and docstrings:
- def __init__(self): Initializes the class
- def run(self, data, in_mask, outdata, outweig, coeffs, wt_scl, drizzle_params, img_nx, img_ny): Do the drizzling Currently, the basic c... | 043c173fd5497c18c2b1bfe8bcff65180bca3996 | <|skeleton|>
class Drizzle:
"""Class to wrap drizzle command"""
def __init__(self):
"""Initializes the class"""
<|body_0|>
def run(self, data, in_mask, outdata, outweig, coeffs, wt_scl, drizzle_params, img_nx, img_ny):
"""Do the drizzling Currently, the basic command is the iraf-ve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Drizzle:
"""Class to wrap drizzle command"""
def __init__(self):
"""Initializes the class"""
from pyraf import iraf
from iraf import stsdas, analysis, dither
iraf.unlearn('drizzle')
def run(self, data, in_mask, outdata, outweig, coeffs, wt_scl, drizzle_params, img_nx,... | the_stack_v2_python_sparse | stsdas/pkg/analysis/slitless/axe/axesrc/dither.py | spacetelescope/stsdas_stripped | train | 1 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('name')\nself.parser.add_argument('token')\nsuper(CtaStrategyInit, self).__init__()",
"args = self.parser.parse_args()\ntoken = args['token']\nname = 'strategyHedge_syt'\nengine = me.getApp('CtaStrategy')\nif not name:\n engine.initAll()\nelse:\... | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyInit, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
token = args['token']
name = 'strate... | 初始化策略 | CtaStrategyInit | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_a... | stack_v2_sparse_classes_36k_train_029451 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019437 | Implement the Python class `CtaStrategyInit` described below.
Class description:
初始化策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅 | Implement the Python class `CtaStrategyInit` described below.
Class description:
初始化策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅
<|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaStrategyInit:
"""初始化策略"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('name')
self.parser.add_argument('token')
super(CtaStrategyInit, self).__init__()
def post(self):
"""订阅"""
args = self.pa... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
a04e2813ec9aba7bdc30dcac7f7e0b4a050008c4 | [
"if not self.id or viewer.has_perm('bookwyrm.create_invites'):\n return\nraise PermissionDenied()",
"if not self.id and User.objects.filter(email=self.email).exists():\n raise IntegrityError()\nsuper().save(*args, **kwargs)"
] | <|body_start_0|>
if not self.id or viewer.has_perm('bookwyrm.create_invites'):
return
raise PermissionDenied()
<|end_body_0|>
<|body_start_1|>
if not self.id and User.objects.filter(email=self.email).exists():
raise IntegrityError()
super().save(*args, **kwargs)
... | prospective users can request an invite | InviteRequest | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InviteRequest:
"""prospective users can request an invite"""
def raise_not_editable(self, viewer):
"""Only check perms on edit, not create"""
<|body_0|>
def save(self, *args, **kwargs):
"""don't create a request for a registered email"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_029452 | 8,920 | no_license | [
{
"docstring": "Only check perms on edit, not create",
"name": "raise_not_editable",
"signature": "def raise_not_editable(self, viewer)"
},
{
"docstring": "don't create a request for a registered email",
"name": "save",
"signature": "def save(self, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016825 | Implement the Python class `InviteRequest` described below.
Class description:
prospective users can request an invite
Method signatures and docstrings:
- def raise_not_editable(self, viewer): Only check perms on edit, not create
- def save(self, *args, **kwargs): don't create a request for a registered email | Implement the Python class `InviteRequest` described below.
Class description:
prospective users can request an invite
Method signatures and docstrings:
- def raise_not_editable(self, viewer): Only check perms on edit, not create
- def save(self, *args, **kwargs): don't create a request for a registered email
<|skel... | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | <|skeleton|>
class InviteRequest:
"""prospective users can request an invite"""
def raise_not_editable(self, viewer):
"""Only check perms on edit, not create"""
<|body_0|>
def save(self, *args, **kwargs):
"""don't create a request for a registered email"""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InviteRequest:
"""prospective users can request an invite"""
def raise_not_editable(self, viewer):
"""Only check perms on edit, not create"""
if not self.id or viewer.has_perm('bookwyrm.create_invites'):
return
raise PermissionDenied()
def save(self, *args, **kwar... | the_stack_v2_python_sparse | bookwyrm/models/site.py | bookwyrm-social/bookwyrm | train | 1,398 |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"squad_id = request.GET.get('id', None)\nif squad_id is not None:\n squad = get_object_or_404(Squad, id=squad_id)\n serializer = SquadSerializer(squad)\n return JsonResponse({'squads': [serializer.data]}, safe=False)\ntutor_username = request.GET.get('tutor_username', None)\nif tutor_username is not None:\... | <|body_start_0|>
squad_id = request.GET.get('id', None)
if squad_id is not None:
squad = get_object_or_404(Squad, id=squad_id)
serializer = SquadSerializer(squad)
return JsonResponse({'squads': [serializer.data]}, safe=False)
tutor_username = request.GET.get('... | 班级view | Squads | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Squads:
"""班级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|>
<|e... | stack_v2_sparse_classes_36k_train_029453 | 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_021619 | Implement the Python class `Squads` 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 `Squads` 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 Squads:
"""班级view"""
def get(self, request):
... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Squads:
"""班级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|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Squads:
"""班级view"""
def get(self, request):
"""查询班级"""
squad_id = request.GET.get('id', None)
if squad_id is not None:
squad = get_object_or_404(Squad, id=squad_id)
serializer = SquadSerializer(squad)
return JsonResponse({'squads': [serializer.... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
1f1fbebc67a57db32ae9d622dd1bf90ad796da30 | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_java_time.JavaTime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = AndroidTwitterSearchEventData()\nevent_data.creation_time = self._GetDateTimeRowValue(query_hash, row, 'time')\ne... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_java_time.JavaTime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = AndroidTwitterSearchEventData... | SQLite parser plugin for Twitter on Android database files. | AndroidTwitterPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that pro... | stack_v2_sparse_classes_36k_train_029454 | 21,169 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.JavaTime: date and time value or None if not available.",
"name"... | 4 | null | Implement the Python class `AndroidTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on Android database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash ... | Implement the Python class `AndroidTwitterPlugin` described below.
Class description:
SQLite parser plugin for Twitter on Android database files.
Method signatures and docstrings:
- def _GetDateTimeRowValue(self, query_hash, row, value_name): Retrieves a date and time value from the row. Args: query_hash (int): hash ... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AndroidTwitterPlugin:
"""SQLite parser plugin for Twitter on Android database files."""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/android_twitter.py | log2timeline/plaso | train | 1,506 |
64e15fa9ce188436ace05bcf08ff0538a4dc409f | [
"context = super().get_context_data(**kwargs)\nuser = get_user_model().objects.filter(id=kwargs['pk']).first()\nif not user:\n raise http.Http404(_('Unable to find user'))\ncontext['user'] = user\nreturn context",
"user = get_user_model().objects.filter(id=kwargs['pk']).first()\nif not user:\n raise http.Ht... | <|body_start_0|>
context = super().get_context_data(**kwargs)
user = get_user_model().objects.filter(id=kwargs['pk']).first()
if not user:
raise http.Http404(_('Unable to find user'))
context['user'] = user
return context
<|end_body_0|>
<|body_start_1|>
user ... | View to delete a "share" user in the workflow. | WorkflowShareDeleteView | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowShareDeleteView:
"""View to delete a "share" user in the workflow."""
def get_context_data(self, **kwargs):
"""Add pk and user email to the context."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Perform the share delete operation."""
... | stack_v2_sparse_classes_36k_train_029455 | 2,685 | permissive | [
{
"docstring": "Add pk and user email to the context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Perform the share delete operation.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001074 | Implement the Python class `WorkflowShareDeleteView` described below.
Class description:
View to delete a "share" user in the workflow.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add pk and user email to the context.
- def post(self, request, *args, **kwargs): Perform the share delete o... | Implement the Python class `WorkflowShareDeleteView` described below.
Class description:
View to delete a "share" user in the workflow.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add pk and user email to the context.
- def post(self, request, *args, **kwargs): Perform the share delete o... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class WorkflowShareDeleteView:
"""View to delete a "share" user in the workflow."""
def get_context_data(self, **kwargs):
"""Add pk and user email to the context."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Perform the share delete operation."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkflowShareDeleteView:
"""View to delete a "share" user in the workflow."""
def get_context_data(self, **kwargs):
"""Add pk and user email to the context."""
context = super().get_context_data(**kwargs)
user = get_user_model().objects.filter(id=kwargs['pk']).first()
if n... | the_stack_v2_python_sparse | ontask/workflow/views/share.py | abelardopardo/ontask_b | train | 43 |
6fb769f0ed9e9f247e6a0f9f046bab604207e85d | [
"valid_alleles = list()\nfor s in classification_tokens:\n for t in transcripts:\n errors = list()\n t = self.get_accession(t, classification)\n allele = None\n if s.reference_sequence == 'c':\n cds_start_end = self.uta.get_cds_start_end(t)\n if cds_start_end is ... | <|body_start_0|>
valid_alleles = list()
for s in classification_tokens:
for t in transcripts:
errors = list()
t = self.get_accession(t, classification)
allele = None
if s.reference_sequence == 'c':
cds_start_... | The Insertion Validator Base class. | InsertionBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InsertionBase:
"""The Insertion Validator Base class."""
def get_valid_invalid_results(self, classification_tokens, transcripts, classification, results, gene_tokens, normalize_endpoint, mane_data_found, is_identifier) -> None:
"""Add validation result objects to a list of results. :... | stack_v2_sparse_classes_36k_train_029456 | 5,710 | permissive | [
{
"docstring": "Add validation result objects to a list of results. :param list classification_tokens: A list of classification Tokens :param list transcripts: A list of transcript accessions :param Classification classification: A classification for a list of tokens :param list results: Stores validation resul... | 4 | stack_v2_sparse_classes_30k_train_003532 | Implement the Python class `InsertionBase` described below.
Class description:
The Insertion Validator Base class.
Method signatures and docstrings:
- def get_valid_invalid_results(self, classification_tokens, transcripts, classification, results, gene_tokens, normalize_endpoint, mane_data_found, is_identifier) -> No... | Implement the Python class `InsertionBase` described below.
Class description:
The Insertion Validator Base class.
Method signatures and docstrings:
- def get_valid_invalid_results(self, classification_tokens, transcripts, classification, results, gene_tokens, normalize_endpoint, mane_data_found, is_identifier) -> No... | d41e9ee786b14f47d17ea8e458eed08ec00ba339 | <|skeleton|>
class InsertionBase:
"""The Insertion Validator Base class."""
def get_valid_invalid_results(self, classification_tokens, transcripts, classification, results, gene_tokens, normalize_endpoint, mane_data_found, is_identifier) -> None:
"""Add validation result objects to a list of results. :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InsertionBase:
"""The Insertion Validator Base class."""
def get_valid_invalid_results(self, classification_tokens, transcripts, classification, results, gene_tokens, normalize_endpoint, mane_data_found, is_identifier) -> None:
"""Add validation result objects to a list of results. :param list cl... | the_stack_v2_python_sparse | variation/validators/insertion_base.py | richardhj/vicc-variation-normalization | train | 0 |
5aaa3345fa0600869a4dc30ea413e256479456fc | [
"active_users = get_user_model()._default_manager.filter(email__iexact=email, is_active=True)\nif user_type in ['expert', 'user']:\n active_users = active_users.filter(**{'%s__isnull' % user_type: False})\nreturn (u for u in active_users if u.has_usable_password())",
"email = self.cleaned_data['email']\nfor us... | <|body_start_0|>
active_users = get_user_model()._default_manager.filter(email__iexact=email, is_active=True)
if user_type in ['expert', 'user']:
active_users = active_users.filter(**{'%s__isnull' % user_type: False})
return (u for u in active_users if u.has_usable_password())
<|end_... | PasswordResetForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordResetForm:
def get_users(self, email, user_type=None):
"""Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their pa... | stack_v2_sparse_classes_36k_train_029457 | 4,832 | no_license | [
{
"docstring": "Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password.",
"name": "get_users",
"signature": "def get_users(self, e... | 2 | stack_v2_sparse_classes_30k_train_006434 | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def get_users(self, email, user_type=None): Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize ... | Implement the Python class `PasswordResetForm` described below.
Class description:
Implement the PasswordResetForm class.
Method signatures and docstrings:
- def get_users(self, email, user_type=None): Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize ... | 248a7b406686c0c98e944319a6eca08485104f5d | <|skeleton|>
class PasswordResetForm:
def get_users(self, email, user_type=None):
"""Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PasswordResetForm:
def get_users(self, email, user_type=None):
"""Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password."""
... | the_stack_v2_python_sparse | common/registration/forms.py | skshivammahajan/DRFChat | train | 0 | |
0c5a3818a46339c70220d9992bbbad6e8f416941 | [
"if head is None and tail is None:\n return None\nif target.val < head.val:\n return None\nelif target.val >= tail.val:\n return tail\nelse:\n smaller = None\n node = head\n while node != target:\n if node.val <= target.val:\n smaller = node\n node = node.next\n return ... | <|body_start_0|>
if head is None and tail is None:
return None
if target.val < head.val:
return None
elif target.val >= tail.val:
return tail
else:
smaller = None
node = head
while node != target:
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.... | stack_v2_sparse_classes_36k_train_029458 | 3,754 | no_license | [
{
"docstring": ">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point is ... | 2 | stack_v2_sparse_classes_30k_train_001393 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertion_point(self, head, tail, target): >>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, ta... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insertion_point(self, head, tail, target): >>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, ta... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def insertion_point(self, head, tail, target):
""">>> s = Solution() >>> head = LinkedList.fromList([7, 8]) >>> tail, target = head, head.next >>> point = s.insertion_point(head, tail, target) >>> point.val 7 >>> head = LinkedList.fromList([8, 7]) >>> tail, target = head, head.next >>> point... | the_stack_v2_python_sparse | insertion_sort_list.py | gsy/leetcode | train | 1 | |
2c0a69e60c963f3fc043c32823c358d7dcd4ba8f | [
"self.winners = []\nself.times = times\np2count = dict()\nmax_p = -1\nfor i, t in enumerate(times):\n p = persons[i]\n if max_p < 0:\n max_p = p\n p2count[p] = 1\n else:\n c = p2count.get(p, 0)\n if p == max_p:\n p2count[p] = c + 1\n elif c + 1 < p2count[max_p]... | <|body_start_0|>
self.winners = []
self.times = times
p2count = dict()
max_p = -1
for i, t in enumerate(times):
p = persons[i]
if max_p < 0:
max_p = p
p2count[p] = 1
else:
c = p2count.get(p, 0)
... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.winners = []
self.times ... | stack_v2_sparse_classes_36k_train_029459 | 2,341 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | null | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.winners = []
self.times = times
p2count = dict()
max_p = -1
for i, t in enumerate(times):
p = persons[i]
if max_p < 0:
... | the_stack_v2_python_sparse | solutions/binary.search/911.Online.Election.py | ljia2/leetcode.py | train | 0 | |
1fe2be8d6cd1f3f58f203370110d6feff5382e1a | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn FollowupFlag()",
"from .date_time_time_zone import DateTimeTimeZone\nfrom .followup_flag_status import FollowupFlagStatus\nfrom .date_time_time_zone import DateTimeTimeZone\nfrom .followup_flag_status import FollowupFlagStatus\nfields:... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return FollowupFlag()
<|end_body_0|>
<|body_start_1|>
from .date_time_time_zone import DateTimeTimeZone
from .followup_flag_status import FollowupFlagStatus
from .date_time_time_zone im... | FollowupFlag | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""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: ... | stack_v2_sparse_classes_36k_train_029460 | 3,941 | 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: FollowupFlag",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `FollowupFlag` described below.
Class description:
Implement the FollowupFlag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `FollowupFlag` described below.
Class description:
Implement the FollowupFlag class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""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: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FollowupFlag:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> FollowupFlag:
"""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: FollowupFlag""... | the_stack_v2_python_sparse | msgraph/generated/models/followup_flag.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
60726b77b088184efdeabb5df32fc0acaf1dc4cb | [
"super().__init__(reporters, max_iterations, evaluator, individual_generator, target_fitness)\nself.parent_count = parent_count\nself.children_count = children_count\nself.mutation = mutation\nself.elitism = elitism\nself.crossover = crossover\nself.population = individual_generator.batch_generate(self.parent_count... | <|body_start_0|>
super().__init__(reporters, max_iterations, evaluator, individual_generator, target_fitness)
self.parent_count = parent_count
self.children_count = children_count
self.mutation = mutation
self.elitism = elitism
self.crossover = crossover
self.popu... | Evolution strategy class | EvolutionStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporter... | stack_v2_sparse_classes_36k_train_029461 | 3,336 | no_license | [
{
"docstring": "Initialize hyperparamters of the algorithm. :param reporters: List of Reporter instances :param max_iterations: Max iterations of the algorithm :param evaluator: Evaluator instance :param individual_generator: Individual factory :param parent_count: mu - size of the parent population :param chil... | 3 | stack_v2_sparse_classes_30k_train_015868 | Implement the Python class `EvolutionStrategy` described below.
Class description:
Evolution strategy class
Method signatures and docstrings:
- def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None): In... | Implement the Python class `EvolutionStrategy` described below.
Class description:
Evolution strategy class
Method signatures and docstrings:
- def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None): In... | 30d87754ed22aa5aab7103d912c414f5a6150a34 | <|skeleton|>
class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporters: List of Re... | the_stack_v2_python_sparse | algorithms/evolution_strategy.py | Yabk/SF-Evolution | train | 0 |
c218549ae5fb3a3013325ae52db89c0837e88559 | [
"firstElement, secondElement = (None, None)\nprevElement = TreeNode(float('-inf'))\n\ndef traverse(root):\n nonlocal firstElement, secondElement, prevElement\n if root == None:\n return\n traverse(root.left)\n if firstElement == None and prevElement.val >= root.val:\n firstElement = prevEl... | <|body_start_0|>
firstElement, secondElement = (None, None)
prevElement = TreeNode(float('-inf'))
def traverse(root):
nonlocal firstElement, secondElement, prevElement
if root == None:
return
traverse(root.left)
if firstElement == ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_1... | stack_v2_sparse_classes_36k_train_029462 | 3,935 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self, root: TreeNode) -> None"
},
{
"docstring": ":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.",
"name": "recoverTree",
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root: TreeNode) -> None: Do not return anything, modify root in-place instead.
- def recoverTree(self, root): :type root: TreeNode :rtype: void Do not retur... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree(self, root):
""":type root: TreeNode :rtype: void Do not return anything, modify root in-place instead."""
<|body_1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""Do not return anything, modify root in-place instead."""
firstElement, secondElement = (None, None)
prevElement = TreeNode(float('-inf'))
def traverse(root):
nonlocal firstElement, secondElement, prevEleme... | the_stack_v2_python_sparse | python_leetcode_2020/Python_Leetcode_2020/99_recover_binary_search_tree.py | xiangcao/Leetcode | train | 0 | |
41a71410126c1af387fe438c68d43f0c6d25fbac | [
"m = len(matrix)\nn = len(matrix[0])\nheap = []\nfor i in range(m):\n for j in range(n):\n v = matrix[i][j]\n if len(heap) < k:\n heapq.heappush(heap, -v)\n elif v < -heap[0]:\n heapq.heappushpop(heap, -v)\nreturn -heap[0]",
"m = len(matrix)\nn = len(matrix[0])\nleft ... | <|body_start_0|>
m = len(matrix)
n = len(matrix[0])
heap = []
for i in range(m):
for j in range(n):
v = matrix[i][j]
if len(heap) < k:
heapq.heappush(heap, -v)
elif v < -heap[0]:
heapq.hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))"""
<|body_0|>
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Binary search approach Time co... | stack_v2_sparse_classes_36k_train_029463 | 1,448 | no_license | [
{
"docstring": "LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))",
"name": "kthSmallest",
"signature": "def kthSmallest(self, matrix: List[List[int]], k: int) -> int"
},
{
"docstring": "Binary search approach Time complexity: O(N * Log(31))",
"name": "kthSmall... | 2 | stack_v2_sparse_classes_30k_train_000616 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))
- def kthSmallest(self, matrix: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallest(self, matrix: List[List[int]], k: int) -> int: LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))
- def kthSmallest(self, matrix: Li... | 89b6c180bb772978b6646131f9734b122e745f9c | <|skeleton|>
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))"""
<|body_0|>
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""Binary search approach Time co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
"""LC 378. Kth Smallest Element in a Sorted Matrix Time complexity: O(N*N * Log(k))"""
m = len(matrix)
n = len(matrix[0])
heap = []
for i in range(m):
for j in range(n):
... | the_stack_v2_python_sparse | binary-search/python/kth-smallest-element-in-a-sorted-matrix.py | dyf102/LC-daily | train | 2 | |
73039ce8069918e0f2192da82ae9276e38581553 | [
"if dtype not in NUMERIC_TYPES:\n raise ValueError(\"invalid numeric type '{}'\".format(dtype))\nsuper(Numeric, self).__init__(dtype=dtype, name=name, index=index, label=label, help=help, default=default, required=required, group=group)\nself.constraint = constraint",
"if value in ['-inf', 'inf']:\n value =... | <|body_start_0|>
if dtype not in NUMERIC_TYPES:
raise ValueError("invalid numeric type '{}'".format(dtype))
super(Numeric, self).__init__(dtype=dtype, name=name, index=index, label=label, help=help, default=default, required=required, group=group)
self.constraint = constraint
<|end_b... | Base class for numeric parameter types. Extends the base class with an optional range constraint. | Numeric | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Numeric:
"""Base class for numeric parameter types. Extends the base class with an optional range constraint."""
def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optiona... | stack_v2_sparse_classes_36k_train_029464 | 16,105 | permissive | [
{
"docstring": "Initialize the base properties for a numeric parameter declaration. Parameters ---------- dtype: string Parameter type identifier. name: string Unique parameter identifier index: int Index position of the parameter (for display purposes). label: string Human-readable parameter name. help: string... | 4 | stack_v2_sparse_classes_30k_train_002547 | Implement the Python class `Numeric` described below.
Class description:
Base class for numeric parameter types. Extends the base class with an optional range constraint.
Method signatures and docstrings:
- def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str... | Implement the Python class `Numeric` described below.
Class description:
Base class for numeric parameter types. Extends the base class with an optional range constraint.
Method signatures and docstrings:
- def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str... | 7116b7060aa68ab36bf08e6393be166dc5db955f | <|skeleton|>
class Numeric:
"""Base class for numeric parameter types. Extends the base class with an optional range constraint."""
def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optiona... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Numeric:
"""Base class for numeric parameter types. Extends the base class with an optional range constraint."""
def __init__(self, dtype: str, name: str, index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Union[int, float]]=None, required: Optional[bool]=False... | the_stack_v2_python_sparse | flowserv/model/parameter/numeric.py | anrunw/flowserv-core-1 | train | 0 |
a3d37cdbece4472abe02b61d8967a98cbde05a85 | [
"if DEBUG:\n print('Reading from file: ' + fullFilename)\nmyFile = open(fullFilename, 'r')\nreadValue = myFile.read().strip()\nmyFile.close()\nreturn readValue",
"if DEBUG:\n print('Writing file: ' + fullFilename + ' with value ' + value)\nmyFile = open(fullFilename, 'w')\nmyFile.write(value)\nmyFile.close(... | <|body_start_0|>
if DEBUG:
print('Reading from file: ' + fullFilename)
myFile = open(fullFilename, 'r')
readValue = myFile.read().strip()
myFile.close()
return readValue
<|end_body_0|>
<|body_start_1|>
if DEBUG:
print('Writing file: ' + fullFilena... | A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance. | _Pins | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Pins:
"""A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance."""
def _ReadFile(self, fullFilename):
"""Created this to reduce typing"""
<|body_0|>
def _WriteFile(self, fullFilename, value):
"""Created this to re... | stack_v2_sparse_classes_36k_train_029465 | 43,792 | no_license | [
{
"docstring": "Created this to reduce typing",
"name": "_ReadFile",
"signature": "def _ReadFile(self, fullFilename)"
},
{
"docstring": "Created this to reduce typing",
"name": "_WriteFile",
"signature": "def _WriteFile(self, fullFilename, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003660 | Implement the Python class `_Pins` described below.
Class description:
A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance.
Method signatures and docstrings:
- def _ReadFile(self, fullFilename): Created this to reduce typing
- def _WriteFile(self, fullFilename, value... | Implement the Python class `_Pins` described below.
Class description:
A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance.
Method signatures and docstrings:
- def _ReadFile(self, fullFilename): Created this to reduce typing
- def _WriteFile(self, fullFilename, value... | 53392808e9992ca9d0a072937d71483bbb6d5dcd | <|skeleton|>
class _Pins:
"""A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance."""
def _ReadFile(self, fullFilename):
"""Created this to reduce typing"""
<|body_0|>
def _WriteFile(self, fullFilename, value):
"""Created this to re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _Pins:
"""A skeleton class so that I don't have to type these functions multiple times. Used only as inheratance."""
def _ReadFile(self, fullFilename):
"""Created this to reduce typing"""
if DEBUG:
print('Reading from file: ' + fullFilename)
myFile = open(fullFilename,... | the_stack_v2_python_sparse | src/sensorsExamples/galileo/pyGalileo/GalileoPins.py | WiserUFBA/soft-iot-tatu-python | train | 1 |
4a1bd0837aa04675b9c8b4774cd096e5b5b81cd1 | [
"self.model = None\nself.type = desc.type if 'type' in desc else None\nself.mean = desc.mean if 'mean' in desc else 0.0\nself.stddev = desc.stddev if 'stddev' in desc else 0.01\nself.factor = 1.0\nself.uniform = True\nself.mode = desc.mode",
"if self.model:\n return self.model\nelse:\n if self.type == 'trun... | <|body_start_0|>
self.model = None
self.type = desc.type if 'type' in desc else None
self.mean = desc.mean if 'mean' in desc else 0.0
self.stddev = desc.stddev if 'stddev' in desc else 0.01
self.factor = 1.0
self.uniform = True
self.mode = desc.mode
<|end_body_0|>... | Initializer. | Initializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initializer:
"""Initializer."""
def __init__(self, desc):
"""Init Initializer. :param desc: config dict"""
<|body_0|>
def get_real_model(self):
"""Get real model of initializer."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.model = None
... | stack_v2_sparse_classes_36k_train_029466 | 2,492 | permissive | [
{
"docstring": "Init Initializer. :param desc: config dict",
"name": "__init__",
"signature": "def __init__(self, desc)"
},
{
"docstring": "Get real model of initializer.",
"name": "get_real_model",
"signature": "def get_real_model(self)"
}
] | 2 | null | Implement the Python class `Initializer` described below.
Class description:
Initializer.
Method signatures and docstrings:
- def __init__(self, desc): Init Initializer. :param desc: config dict
- def get_real_model(self): Get real model of initializer. | Implement the Python class `Initializer` described below.
Class description:
Initializer.
Method signatures and docstrings:
- def __init__(self, desc): Init Initializer. :param desc: config dict
- def get_real_model(self): Get real model of initializer.
<|skeleton|>
class Initializer:
"""Initializer."""
def... | e4ef3a1c92d19d1d08c3ef0e2156b6fecefdbe04 | <|skeleton|>
class Initializer:
"""Initializer."""
def __init__(self, desc):
"""Init Initializer. :param desc: config dict"""
<|body_0|>
def get_real_model(self):
"""Get real model of initializer."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Initializer:
"""Initializer."""
def __init__(self, desc):
"""Init Initializer. :param desc: config dict"""
self.model = None
self.type = desc.type if 'type' in desc else None
self.mean = desc.mean if 'mean' in desc else 0.0
self.stddev = desc.stddev if 'stddev' in ... | the_stack_v2_python_sparse | zeus/networks/tensorflow/utils/hyperparams/initializer.py | huawei-noah/xingtian | train | 308 |
01f97726937d416623bdf47c764a0b0bdfb54089 | [
"self.maxsize = size\nself.sum = 0\nself.window = collections.deque()",
"self.window.append(val)\nif len(self.window) < self.maxsize:\n self.sum += val\nelse:\n self.sum += val - self.window.popleft()\nreturn self.sum / self.maxsize"
] | <|body_start_0|>
self.maxsize = size
self.sum = 0
self.window = collections.deque()
<|end_body_0|>
<|body_start_1|>
self.window.append(val)
if len(self.window) < self.maxsize:
self.sum += val
else:
self.sum += val - self.window.popleft()
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.maxsize = size
self.sum = 0
... | stack_v2_sparse_classes_36k_train_029467 | 842 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class Solution:
def __init__... | 5520dbcd26999b98e1229bf03c2f62dd690a2ddc | <|skeleton|>
class Solution:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.maxsize = size
self.sum = 0
self.window = collections.deque()
def next(self, val):
""":type val: int :rtype: float"""
self.window.append(val)
if len(... | the_stack_v2_python_sparse | movingAverage.py | pflun/advancedAlgorithms | train | 4 | |
2786c897b3bfa47724930c4c6540cd8794f9efd3 | [
"assert isinstance(output_size, (int, tuple))\nif isinstance(output_size, int):\n self.output_size = (output_size, output_size)\nelse:\n assert len(output_size) == 2\n self.output_size = output_size",
"imidx, image, label = (sample['imidx'], sample['image'], sample['label'])\nif random.random() >= 0.5:\n... | <|body_start_0|>
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_size) == 2
self.output_size = output_size
<|end_body_0|>
<|body_start_1|>
imidx, image... | RandomCrop operation | RandomCrop | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomCrop:
"""RandomCrop operation"""
def __init__(self, output_size):
"""RandomCrop definition"""
<|body_0|>
def __call__(self, sample):
"""RandomCrop compute"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
assert isinstance(output_size, (int,... | stack_v2_sparse_classes_36k_train_029468 | 14,055 | permissive | [
{
"docstring": "RandomCrop definition",
"name": "__init__",
"signature": "def __init__(self, output_size)"
},
{
"docstring": "RandomCrop compute",
"name": "__call__",
"signature": "def __call__(self, sample)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000947 | Implement the Python class `RandomCrop` described below.
Class description:
RandomCrop operation
Method signatures and docstrings:
- def __init__(self, output_size): RandomCrop definition
- def __call__(self, sample): RandomCrop compute | Implement the Python class `RandomCrop` described below.
Class description:
RandomCrop operation
Method signatures and docstrings:
- def __init__(self, output_size): RandomCrop definition
- def __call__(self, sample): RandomCrop compute
<|skeleton|>
class RandomCrop:
"""RandomCrop operation"""
def __init__(... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class RandomCrop:
"""RandomCrop operation"""
def __init__(self, output_size):
"""RandomCrop definition"""
<|body_0|>
def __call__(self, sample):
"""RandomCrop compute"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomCrop:
"""RandomCrop operation"""
def __init__(self, output_size):
"""RandomCrop definition"""
assert isinstance(output_size, (int, tuple))
if isinstance(output_size, int):
self.output_size = (output_size, output_size)
else:
assert len(output_s... | the_stack_v2_python_sparse | research/cv/u2net/src/data_loader.py | mindspore-ai/models | train | 301 |
c1fb96d281ff340126642b38e421cb45381803dd | [
"config = current_app.cea_config\ndashboards = cea.plots.read_dashboards(config, current_app.plot_cache)\nreturn dashboard_to_dict(dashboards[dashboard_index])['plots'][plot_index]",
"form = api.payload\nconfig = current_app.cea_config\ntemp_config = cea.config.Configuration()\ndashboards = cea.plots.read_dashboa... | <|body_start_0|>
config = current_app.cea_config
dashboards = cea.plots.read_dashboards(config, current_app.plot_cache)
return dashboard_to_dict(dashboards[dashboard_index])['plots'][plot_index]
<|end_body_0|>
<|body_start_1|>
form = api.payload
config = current_app.cea_config
... | DashboardPlot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DashboardPlot:
def get(self, dashboard_index, plot_index):
"""Get Dashboard Plot"""
<|body_0|>
def put(self, dashboard_index, plot_index):
"""Create/Replace a new Plot at specified index"""
<|body_1|>
def delete(self, dashboard_index, plot_index):
... | stack_v2_sparse_classes_36k_train_029469 | 9,106 | permissive | [
{
"docstring": "Get Dashboard Plot",
"name": "get",
"signature": "def get(self, dashboard_index, plot_index)"
},
{
"docstring": "Create/Replace a new Plot at specified index",
"name": "put",
"signature": "def put(self, dashboard_index, plot_index)"
},
{
"docstring": "Delete Plot ... | 3 | stack_v2_sparse_classes_30k_train_013920 | Implement the Python class `DashboardPlot` described below.
Class description:
Implement the DashboardPlot class.
Method signatures and docstrings:
- def get(self, dashboard_index, plot_index): Get Dashboard Plot
- def put(self, dashboard_index, plot_index): Create/Replace a new Plot at specified index
- def delete(s... | Implement the Python class `DashboardPlot` described below.
Class description:
Implement the DashboardPlot class.
Method signatures and docstrings:
- def get(self, dashboard_index, plot_index): Get Dashboard Plot
- def put(self, dashboard_index, plot_index): Create/Replace a new Plot at specified index
- def delete(s... | b84bcefdfdfc2bc0e009b5284b74391a957995ac | <|skeleton|>
class DashboardPlot:
def get(self, dashboard_index, plot_index):
"""Get Dashboard Plot"""
<|body_0|>
def put(self, dashboard_index, plot_index):
"""Create/Replace a new Plot at specified index"""
<|body_1|>
def delete(self, dashboard_index, plot_index):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DashboardPlot:
def get(self, dashboard_index, plot_index):
"""Get Dashboard Plot"""
config = current_app.cea_config
dashboards = cea.plots.read_dashboards(config, current_app.plot_cache)
return dashboard_to_dict(dashboards[dashboard_index])['plots'][plot_index]
def put(sel... | the_stack_v2_python_sparse | cea/interfaces/dashboard/api/dashboard.py | architecture-building-systems/CityEnergyAnalyst | train | 166 | |
b54599221fb15b711bb67ad62e7f128a8e33546f | [
"g_cfg = BED_CFG.GRASP_CONFIG\nself.yc = YOLO_CONV(options=g_cfg)\nself.yc.load_network()\nself.g_detector = GDetector(g_cfg, BED_CFG, yc=self.yc)",
"L2_results = []\nfor test_list in all_cv_files:\n with open(test_list, 'r') as f:\n data = pickle.load(f)\n print('loaded test data: {} (length {})'.fo... | <|body_start_0|>
g_cfg = BED_CFG.GRASP_CONFIG
self.yc = YOLO_CONV(options=g_cfg)
self.yc.load_network()
self.g_detector = GDetector(g_cfg, BED_CFG, yc=self.yc)
<|end_body_0|>
<|body_start_1|>
L2_results = []
for test_list in all_cv_files:
with open(test_list,... | Test | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
def __init__(self):
"""For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixed stem.) However, this requires an fg_cfg, which could be either the grasp or the success one... | stack_v2_sparse_classes_36k_train_029470 | 4,153 | no_license | [
{
"docstring": "For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixed stem.) However, this requires an fg_cfg, which could be either the grasp or the success one ... i.e., the cfg we used for traini... | 2 | stack_v2_sparse_classes_30k_train_002575 | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def __init__(self): For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixe... | Implement the Python class `Test` described below.
Class description:
Implement the Test class.
Method signatures and docstrings:
- def __init__(self): For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixe... | 98907194ae996291f326d8199229415900653a9a | <|skeleton|>
class Test:
def __init__(self):
"""For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixed stem.) However, this requires an fg_cfg, which could be either the grasp or the success one... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test:
def __init__(self):
"""For testing how to deploy the policy. As mentioned earlier, load in YOLO here and supply it to both of the detectors. (For now, assume both use YOLO pre-trained, fixed stem.) However, this requires an fg_cfg, which could be either the grasp or the success one ... i.e., the... | the_stack_v2_python_sparse | main/example_load_network_grasp_only.py | DanielTakeshi/IL_ROS_HSR | train | 12 | |
ac1c3aa9e64d4773e93327f3808d8d8b03cb45b5 | [
"self.pi_means = means\nself.pi_variances = variances\nself.relative_weight = relative_weight\nself.weight = weight\nself.rev_KL = MFN_MFN_reverse_KLD(means, variances)\nself.KL = MFN_MFN_KLD(means, variances)",
"revKL = self.rev_KL(q_params, q_parser, converter)\nKL = self.KL(q_params, q_parser, converter)\nretu... | <|body_start_0|>
self.pi_means = means
self.pi_variances = variances
self.relative_weight = relative_weight
self.weight = weight
self.rev_KL = MFN_MFN_reverse_KLD(means, variances)
self.KL = MFN_MFN_KLD(means, variances)
<|end_body_0|>
<|body_start_1|>
revKL = se... | Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q) | MFN_MFN_JeffreysD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_36k_train_029471 | 14,750 | no_license | [
{
"docstring": "MFN for prior specified by vector of means & variances",
"name": "__init__",
"signature": "def __init__(self, means, variances, relative_weight=0.5, weight=1.0)"
},
{
"docstring": "Compute relative_weight * KLD(q||pi) + (1-relw) * KLD(pi||q)",
"name": "prior_retularizer",
... | 2 | stack_v2_sparse_classes_30k_train_004266 | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | Implement the Python class `MFN_MFN_JeffreysD` described below.
Class description:
Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each va... | 6e51c10227ca8300853f2341906503d072cc0685 | <|skeleton|>
class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MFN_MFN_JeffreysD:
"""Jeffrey's Divergence where q and pi are both mean field normals. This is just KLD(q||pi) + KLD(pi||q) Internal states of the object: means Means of the prior (one mean for each variable) variances Variances of the prior (one for each variable) relative_weight relative_weight * KLD(q||pi)... | the_stack_v2_python_sparse | Divergence.py | JeremiasKnoblauch/GVI_consistency | train | 0 |
942f7e2ac06f33815a91e6f04e0527deb23a6d66 | [
"result = RecursiveFilter()\nself.assertIsNone(result.iterations)\nself.assertEqual(result.edge_width, 15)",
"iterations = 0\nmsg = 'Invalid number of iterations: must be >= 1: 0'\nwith self.assertRaisesRegex(ValueError, msg):\n RecursiveFilter(iterations=iterations, edge_width=1)",
"iterations = 5\nwarning_... | <|body_start_0|>
result = RecursiveFilter()
self.assertIsNone(result.iterations)
self.assertEqual(result.edge_width, 15)
<|end_body_0|>
<|body_start_1|>
iterations = 0
msg = 'Invalid number of iterations: must be >= 1: 0'
with self.assertRaisesRegex(ValueError, msg):
... | Test plugin initialisation. | Test__init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__init__:
"""Test plugin initialisation."""
def test_basic(self):
"""Test using the default arguments."""
<|body_0|>
def test_iterations(self):
"""Test when iterations value less than unity is given (invalid)."""
<|body_1|>
def test_iterations_wa... | stack_v2_sparse_classes_36k_train_029472 | 22,857 | permissive | [
{
"docstring": "Test using the default arguments.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test when iterations value less than unity is given (invalid).",
"name": "test_iterations",
"signature": "def test_iterations(self)"
},
{
"docstring": ... | 3 | null | Implement the Python class `Test__init__` described below.
Class description:
Test plugin initialisation.
Method signatures and docstrings:
- def test_basic(self): Test using the default arguments.
- def test_iterations(self): Test when iterations value less than unity is given (invalid).
- def test_iterations_warn(s... | Implement the Python class `Test__init__` described below.
Class description:
Test plugin initialisation.
Method signatures and docstrings:
- def test_basic(self): Test using the default arguments.
- def test_iterations(self): Test when iterations value less than unity is given (invalid).
- def test_iterations_warn(s... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__init__:
"""Test plugin initialisation."""
def test_basic(self):
"""Test using the default arguments."""
<|body_0|>
def test_iterations(self):
"""Test when iterations value less than unity is given (invalid)."""
<|body_1|>
def test_iterations_wa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__init__:
"""Test plugin initialisation."""
def test_basic(self):
"""Test using the default arguments."""
result = RecursiveFilter()
self.assertIsNone(result.iterations)
self.assertEqual(result.edge_width, 15)
def test_iterations(self):
"""Test when iterat... | the_stack_v2_python_sparse | improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py | metoppv/improver | train | 101 |
74cf2663c72e62fd7acaea89e5afe5b93977d1ae | [
"try:\n return QueryPlansAcquired.objects.get(pk=pk)\nexcept QueryPlansAcquired.DoesNotExist:\n raise Http404",
"client = request.user.id\nquery_set = self.get_detail_plan(code, client)\ntry:\n serializer = PlanDetailSerializer(query_set)\n return Response(serializer.data)\nexcept Exception as e:\n ... | <|body_start_0|>
try:
return QueryPlansAcquired.objects.get(pk=pk)
except QueryPlansAcquired.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
client = request.user.id
query_set = self.get_detail_plan(code, client)
try:
serializer = ... | Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente | ActivationPlanView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
<|body_0|>
def get(self, request, code):
"""Devuelve la in... | stack_v2_sparse_classes_36k_train_029473 | 44,248 | no_license | [
{
"docstring": "Buscar plan adquirido.",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Devuelve la informacion del plan segun el codigo pasado.",
"name": "get",
"signature": "def get(self, request, code)"
},
{
"docstring": "Activar producto, via... | 5 | stack_v2_sparse_classes_30k_train_004107 | Implement the Python class `ActivationPlanView` described below.
Class description:
Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente
Method signatures and docstrings:
- def get_object(self, pk): Buscar plan adquirido.
- def get(self, request, ... | Implement the Python class `ActivationPlanView` described below.
Class description:
Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente
Method signatures and docstrings:
- def get_object(self, pk): Buscar plan adquirido.
- def get(self, request, ... | 3135a4142c38f367a152e1fc79fee8af8fca4bcc | <|skeleton|>
class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
<|body_0|>
def get(self, request, code):
"""Devuelve la in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivationPlanView:
"""Activar pllan por codigo PIN. Si activa el plan y aun no tiene ninguno elegido para consultar este se elige automaticamente"""
def get_object(self, pk):
"""Buscar plan adquirido."""
try:
return QueryPlansAcquired.objects.get(pk=pk)
except QueryPl... | the_stack_v2_python_sparse | api/views/plan.py | darwinv/api-chat-lnk | train | 0 |
0650fc95a6963dea66476095cff56eb1fc78c5bb | [
"d = {}\nfor i, el in enumerate(nums):\n if el in d:\n if abs(d[el] - i) <= k:\n return True\n else:\n d[el] = i\n else:\n d[el] = i\nreturn False",
"arr = [(b, a) for a, b in enumerate(nums)]\narr.sort()\nn = len(nums)\nfor i in range(n - 1):\n if arr[i][0] == ... | <|body_start_0|>
d = {}
for i, el in enumerate(nums):
if el in d:
if abs(d[el] - i) <= k:
return True
else:
d[el] = i
else:
d[el] = i
return False
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate_nlogn(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_029474 | 1,131 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate_nlogn",
"signature": "def c... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate_nlogn(self, nums, k): :type nums: List[int] :type k: int... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate_nlogn(self, nums, k): :type nums: List[int] :type k: int... | b3a2013d1c3c7a5a16727dbc2ecbc934a01a3979 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate_nlogn(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
d = {}
for i, el in enumerate(nums):
if el in d:
if abs(d[el] - i) <= k:
return True
else:
d[e... | the_stack_v2_python_sparse | LeetcodePython/ContainsDuplicateII219.py | DianaLuca/Algorithms | train | 1 | |
407cefc3f44c7a0bab87186edcf12ca23bca9d64 | [
"is_added = Particip.objects.select_related().filter(user_id__username=self.USERNAME, table_id__url=self.table_ID)\nis_added = is_added.exists()\nreturn is_added",
"self.URL = request.path\nself.table_ID = get_table_url(request.path)\nself.USERNAME = request.user.username\nif request.user.is_authenticated:\n r... | <|body_start_0|>
is_added = Particip.objects.select_related().filter(user_id__username=self.USERNAME, table_id__url=self.table_ID)
is_added = is_added.exists()
return is_added
<|end_body_0|>
<|body_start_1|>
self.URL = request.path
self.table_ID = get_table_url(request.path)
... | permissions for allowing user read table content | CanSendNote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanSendNote:
"""permissions for allowing user read table content"""
def already_added(self) -> bool:
"""check if user is added to table"""
<|body_0|>
def has_permission(self, request, view) -> bool:
"""main function"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_029475 | 2,369 | no_license | [
{
"docstring": "check if user is added to table",
"name": "already_added",
"signature": "def already_added(self) -> bool"
},
{
"docstring": "main function",
"name": "has_permission",
"signature": "def has_permission(self, request, view) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_007424 | Implement the Python class `CanSendNote` described below.
Class description:
permissions for allowing user read table content
Method signatures and docstrings:
- def already_added(self) -> bool: check if user is added to table
- def has_permission(self, request, view) -> bool: main function | Implement the Python class `CanSendNote` described below.
Class description:
permissions for allowing user read table content
Method signatures and docstrings:
- def already_added(self) -> bool: check if user is added to table
- def has_permission(self, request, view) -> bool: main function
<|skeleton|>
class CanSen... | 25e1bf7a3ae4a75c02f576582778bb259d7d8d4a | <|skeleton|>
class CanSendNote:
"""permissions for allowing user read table content"""
def already_added(self) -> bool:
"""check if user is added to table"""
<|body_0|>
def has_permission(self, request, view) -> bool:
"""main function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanSendNote:
"""permissions for allowing user read table content"""
def already_added(self) -> bool:
"""check if user is added to table"""
is_added = Particip.objects.select_related().filter(user_id__username=self.USERNAME, table_id__url=self.table_ID)
is_added = is_added.exists()... | the_stack_v2_python_sparse | api/permissions.py | RandomGuy090/taskmanager | train | 0 |
a12aa5b4d0ce3dc99bdd10fee252dab015f9b2f1 | [
"IV_dict_sorted = sorted(IV_dict.items(), key=lambda x: x[1], reverse=True)\nivlist = [i[1] for i in IV_dict_sorted]\nindex = [i[0] for i in IV_dict_sorted]\nfig1 = plt.figure(figsize=figsize)\nax1 = fig1.add_subplot(1, 1, 1)\nx = np.arange(len(index)) + 1\nax1.bar(x, ivlist, width=0.5)\nax1.set_xticks(x)\nif xlabe... | <|body_start_0|>
IV_dict_sorted = sorted(IV_dict.items(), key=lambda x: x[1], reverse=True)
ivlist = [i[1] for i in IV_dict_sorted]
index = [i[0] for i in IV_dict_sorted]
fig1 = plt.figure(figsize=figsize)
ax1 = fig1.add_subplot(1, 1, 1)
x = np.arange(len(index)) + 1
... | 特征工程作图函数 | PlotFeatureEn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlotFeatureEn:
"""特征工程作图函数"""
def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False):
"""信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 _____________________ return draw_iv"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_029476 | 6,486 | no_license | [
{
"docstring": "信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 _____________________ return draw_iv",
"name": "draw_IV",
"signature": "def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_val_000856 | Implement the Python class `PlotFeatureEn` described below.
Class description:
特征工程作图函数
Method signatures and docstrings:
- def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False): 信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 ____... | Implement the Python class `PlotFeatureEn` described below.
Class description:
特征工程作图函数
Method signatures and docstrings:
- def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False): 信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 ____... | 468b57af341f6f9e887d284cc551b2428f709fe3 | <|skeleton|>
class PlotFeatureEn:
"""特征工程作图函数"""
def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False):
"""信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 _____________________ return draw_iv"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlotFeatureEn:
"""特征工程作图函数"""
def draw_IV(self, IV_dict, path, xlabel=None, figsize=(15, 7), is_save=False):
"""信息值IV柱状图 --------------------- param IV_dict: dict IV值字典 path: str 文件存储地址 xlabel: list x轴标签 figsize: tupe 图片大小 _____________________ return draw_iv"""
IV_dict_sorted = sorted(IV... | the_stack_v2_python_sparse | riskModel/utils/PltFunction.py | itbuyixiaogong/risk-model | train | 0 |
218804a4044b1345b0c3000929aa9a2a41ceb092 | [
"R = Resource.objects.addResource(request)\nP = Publication(resource=R, title=request['title'], authors=request['authors'], publicationDate=request['publicationDate'], organization=request['organization'], link=request['link'])\nP.save()\nreturn P",
"R = Resource.objects.editResource(request)\nP = Publication.obj... | <|body_start_0|>
R = Resource.objects.addResource(request)
P = Publication(resource=R, title=request['title'], authors=request['authors'], publicationDate=request['publicationDate'], organization=request['organization'], link=request['link'])
P.save()
return P
<|end_body_0|>
<|body_star... | PublicationManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicationManager:
def addPublication(self, request):
"""add new publication"""
<|body_0|>
def editPublication(self, request):
"""edit existing publication"""
<|body_1|>
def getDocumentById(self, request):
"""get publication details on the basis... | stack_v2_sparse_classes_36k_train_029477 | 2,839 | permissive | [
{
"docstring": "add new publication",
"name": "addPublication",
"signature": "def addPublication(self, request)"
},
{
"docstring": "edit existing publication",
"name": "editPublication",
"signature": "def editPublication(self, request)"
},
{
"docstring": "get publication details ... | 5 | null | Implement the Python class `PublicationManager` described below.
Class description:
Implement the PublicationManager class.
Method signatures and docstrings:
- def addPublication(self, request): add new publication
- def editPublication(self, request): edit existing publication
- def getDocumentById(self, request): g... | Implement the Python class `PublicationManager` described below.
Class description:
Implement the PublicationManager class.
Method signatures and docstrings:
- def addPublication(self, request): add new publication
- def editPublication(self, request): edit existing publication
- def getDocumentById(self, request): g... | 9673bf8b6094560f0e5cb60efb536139deaa965e | <|skeleton|>
class PublicationManager:
def addPublication(self, request):
"""add new publication"""
<|body_0|>
def editPublication(self, request):
"""edit existing publication"""
<|body_1|>
def getDocumentById(self, request):
"""get publication details on the basis... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicationManager:
def addPublication(self, request):
"""add new publication"""
R = Resource.objects.addResource(request)
P = Publication(resource=R, title=request['title'], authors=request['authors'], publicationDate=request['publicationDate'], organization=request['organization'], l... | the_stack_v2_python_sparse | Resource/models/Publication.py | IEEEDTU/CMS | train | 5 | |
4f17f068614e5feb117feee18b2a075bc575141c | [
"for row in matrix:\n for col in range(1, len(row)):\n row[col] += row[col - 1]\nself.matrix = matrix",
"original = self.matrix[row][col]\nif col != 0:\n original -= self.matrix[row][col - 1]\ndiff = original - val\nfor y in range(col, len(self.matrix[0])):\n self.matrix[row][y] -= diff",
"sum_ ... | <|body_start_0|>
for row in matrix:
for col in range(1, len(row)):
row[col] += row[col - 1]
self.matrix = matrix
<|end_body_0|>
<|body_start_1|>
original = self.matrix[row][col]
if col != 0:
original -= self.matrix[row][col - 1]
diff = ori... | NumMatrix1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix1:
def __init__(self, matrix):
"""initialize your data structure here."""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val."""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of e... | stack_v2_sparse_classes_36k_train_029478 | 3,097 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": "update the element at matrix[row,col] to val.",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": "sum of eleme... | 3 | stack_v2_sparse_classes_30k_val_001059 | Implement the Python class `NumMatrix1` described below.
Class description:
Implement the NumMatrix1 class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here.
- def update(self, row, col, val): update the element at matrix[row,col] to val.
- def sumRegion(self, row1, ... | Implement the Python class `NumMatrix1` described below.
Class description:
Implement the NumMatrix1 class.
Method signatures and docstrings:
- def __init__(self, matrix): initialize your data structure here.
- def update(self, row, col, val): update the element at matrix[row,col] to val.
- def sumRegion(self, row1, ... | 502e121cc25fcd81afe3d029145aeee56db794f0 | <|skeleton|>
class NumMatrix1:
def __init__(self, matrix):
"""initialize your data structure here."""
<|body_0|>
def update(self, row, col, val):
"""update the element at matrix[row,col] to val."""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
"""sum of e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix1:
def __init__(self, matrix):
"""initialize your data structure here."""
for row in matrix:
for col in range(1, len(row)):
row[col] += row[col - 1]
self.matrix = matrix
def update(self, row, col, val):
"""update the element at matrix[r... | the_stack_v2_python_sparse | 308NumMatrix.py | qinzhouhit/leetcode | train | 0 | |
f8bc0a3499add21413fe1b476454e413a99de115 | [
"super().__init__(grid)\nif grid.at_node['flow__receiver_node'].size != grid.size('node'):\n raise NotImplementedError('A route-to-multiple flow director has been run on this grid. The landlab development team has not verified that TransportLengthHillslopeDiffuser is compatible with route-to-multiple methods. Pl... | <|body_start_0|>
super().__init__(grid)
if grid.at_node['flow__receiver_node'].size != grid.size('node'):
raise NotImplementedError('A route-to-multiple flow director has been run on this grid. The landlab development team has not verified that TransportLengthHillslopeDiffuser is compatible ... | Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{dx}{(1 - (S / S_c)^2} Works on regular raster-type grid (RasterModelGrid, dx=dy). To be coupled with... | TransportLengthHillslopeDiffuser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransportLengthHillslopeDiffuser:
"""Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{dx}{(1 - (S / S_c)^2} Works on regular r... | stack_v2_sparse_classes_36k_train_029479 | 10,760 | permissive | [
{
"docstring": "Initialize Diffuser. Parameters ---------- grid : ModelGrid Landlab ModelGrid object erodibility: float Erodibility coefficient [L/T] slope_crit: float (default=1.) Critical slope [L/L]",
"name": "__init__",
"signature": "def __init__(self, grid, erodibility=0.001, slope_crit=1.0)"
},
... | 3 | null | Implement the Python class `TransportLengthHillslopeDiffuser` described below.
Class description:
Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{d... | Implement the Python class `TransportLengthHillslopeDiffuser` described below.
Class description:
Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{d... | 1cd72e5832ece1aa922cd1b239e2e94ed0f11f8b | <|skeleton|>
class TransportLengthHillslopeDiffuser:
"""Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{dx}{(1 - (S / S_c)^2} Works on regular r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransportLengthHillslopeDiffuser:
"""Transport length hillslope diffusion. Hillslope diffusion component in the style of Carretier et al. (2016, ESurf), and Davy and Lague (2009) .. math:: \\frac{dz}{dt} = -E + D (+ U) D = \\frac{q_s}{L} E = k S L = \\frac{dx}{(1 - (S / S_c)^2} Works on regular raster-type gr... | the_stack_v2_python_sparse | landlab/components/transport_length_diffusion/transport_length_hillslope_diffusion.py | landlab/landlab | train | 326 |
a462a969e0eec08f456f34f64f849b88965c4688 | [
"self.index = 0\nself.counter = 0\nself.amount = ''\nself.cs = compressedString\nself.leng = len(compressedString)\nself.char = ''\ni = self.index\nwhile i < self.leng:\n self.char = compressedString[i]\n stringnum = ''\n i += 1\n while not compressedString[i].isalpha():\n stringnum += compressed... | <|body_start_0|>
self.index = 0
self.counter = 0
self.amount = ''
self.cs = compressedString
self.leng = len(compressedString)
self.char = ''
i = self.index
while i < self.leng:
self.char = compressedString[i]
stringnum = ''
... | StringIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_029480 | 2,237 | no_license | [
{
"docstring": ":type compressedString: str",
"name": "__init__",
"signature": "def __init__(self, compressedString)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasN... | 3 | stack_v2_sparse_classes_30k_train_004217 | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool | Implement the Python class `StringIterator` described below.
Class description:
Implement the StringIterator class.
Method signatures and docstrings:
- def __init__(self, compressedString): :type compressedString: str
- def next(self): :rtype: str
- def hasNext(self): :rtype: bool
<|skeleton|>
class StringIterator:
... | 05d49ca91ac2a4d414dbb38b01266962ce68f34a | <|skeleton|>
class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StringIterator:
def __init__(self, compressedString):
""":type compressedString: str"""
self.index = 0
self.counter = 0
self.amount = ''
self.cs = compressedString
self.leng = len(compressedString)
self.char = ''
i = self.index
while i < ... | the_stack_v2_python_sparse | leetcode/contest/2017/june10/604.py | jonathantsang/CompetitiveProgramming | train | 2 | |
7d2dce8255c44722882b60932a9cbdefd24ab93e | [
"super(SimpleNet, self).__init__()\nself.fully_connected_1 = nn.Linear(input_dim, hidden_dim)\nself.fully_connected_2 = nn.Linear(hidden_dim, output_dim)\nself.drop_out = nn.Dropout(0.3)\nself.sigmoid = nn.Sigmoid()",
"out = f.relu(self.fully_connected_1(X))\nout = self.drop_out(out)\nout = self.fully_connected_2... | <|body_start_0|>
super(SimpleNet, self).__init__()
self.fully_connected_1 = nn.Linear(input_dim, hidden_dim)
self.fully_connected_2 = nn.Linear(hidden_dim, output_dim)
self.drop_out = nn.Dropout(0.3)
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
out = f.rel... | SimpleNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleNet:
def __init__(self, input_dim, hidden_dim, output_dim):
"""Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dimension of the hidden layer(s) :param output_dim: Number of outputs"""
<|body_0|>
def f... | stack_v2_sparse_classes_36k_train_029481 | 1,034 | no_license | [
{
"docstring": "Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dimension of the hidden layer(s) :param output_dim: Number of outputs",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, output_dim)"
},
{
... | 2 | null | Implement the Python class `SimpleNet` described below.
Class description:
Implement the SimpleNet class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim): Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dime... | Implement the Python class `SimpleNet` described below.
Class description:
Implement the SimpleNet class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, output_dim): Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dime... | 7da789ef34d5e5bcf9033cfbe0ff5df607b2437a | <|skeleton|>
class SimpleNet:
def __init__(self, input_dim, hidden_dim, output_dim):
"""Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dimension of the hidden layer(s) :param output_dim: Number of outputs"""
<|body_0|>
def f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleNet:
def __init__(self, input_dim, hidden_dim, output_dim):
"""Instantiates a neural network with the following attributes. :param input_dim: Number of features :param hidden_dim: Dimension of the hidden layer(s) :param output_dim: Number of outputs"""
super(SimpleNet, self).__init__()
... | the_stack_v2_python_sparse | sagemaker/scripts/model.py | calvinfeng/machine-learning-notebook | train | 38 | |
3237fd9296bda93a3196eeecf039920b8a16a93c | [
"super().__init__(name=name)\nself.agent = agent\nself.env = env\nself.return_obs = return_obs\nself.return_action = return_action\nself.GymOutput = GymOutput(self.return_obs, self.return_action)",
"action = hk.get_state('action', shape=[], init=lambda *_: self.GymState(self.agent(raw_obs)))\nrw, obs = self.env(a... | <|body_start_0|>
super().__init__(name=name)
self.agent = agent
self.env = env
self.return_obs = return_obs
self.return_action = return_action
self.GymOutput = GymOutput(self.return_obs, self.return_action)
<|end_body_0|>
<|body_start_1|>
action = hk.get_state('a... | Gym feedback between an agent and a Gym environment. | GymFeedback | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unro... | stack_v2_sparse_classes_36k_train_029482 | 3,205 | permissive | [
{
"docstring": "Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unroll the data and feed the agent. return_obs : if true return environment observation return_action : if true return agent action name : name of the module",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_003886 | Implement the Python class `GymFeedback` described below.
Class description:
Gym feedback between an agent and a Gym environment.
Method signatures and docstrings:
- def __init__(self, agent, env, return_obs=False, return_action=False, name=None): Initialize module. Args: agent : Gym environment used to unroll the da... | Implement the Python class `GymFeedback` described below.
Class description:
Gym feedback between an agent and a Gym environment.
Method signatures and docstrings:
- def __init__(self, agent, env, return_obs=False, return_action=False, name=None): Initialize module. Args: agent : Gym environment used to unroll the da... | ab18e064f9fa1c95458978f501efb6cde9ab64d5 | <|skeleton|>
class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GymFeedback:
"""Gym feedback between an agent and a Gym environment."""
def __init__(self, agent, env, return_obs=False, return_action=False, name=None):
"""Initialize module. Args: agent : Gym environment used to unroll the data and feed the agent. env : Gym environment used to unroll the data a... | the_stack_v2_python_sparse | wax/modules/gym_feedback.py | zggl/wax-ml | train | 0 |
e13cf3f205af120f300c10a42d01af455d4a7986 | [
"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... | Allows clients to query the Daml-LF packages that are supported by the server. | PackageServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackageServiceServicer:
"""Allows clients to query the Daml-LF packages that are supported by the server."""
def ListPackages(self, request, context):
"""Returns the identifiers of all supported packages."""
<|body_0|>
def GetPackage(self, request, context):
"""R... | stack_v2_sparse_classes_36k_train_029483 | 6,970 | permissive | [
{
"docstring": "Returns the identifiers of all supported packages.",
"name": "ListPackages",
"signature": "def ListPackages(self, request, context)"
},
{
"docstring": "Returns the contents of a single package.",
"name": "GetPackage",
"signature": "def GetPackage(self, request, context)"
... | 3 | null | Implement the Python class `PackageServiceServicer` described below.
Class description:
Allows clients to query the Daml-LF packages that are supported by the server.
Method signatures and docstrings:
- def ListPackages(self, request, context): Returns the identifiers of all supported packages.
- def GetPackage(self,... | Implement the Python class `PackageServiceServicer` described below.
Class description:
Allows clients to query the Daml-LF packages that are supported by the server.
Method signatures and docstrings:
- def ListPackages(self, request, context): Returns the identifiers of all supported packages.
- def GetPackage(self,... | efdbb00e54614c0af650d7440faaffbde92ad1f4 | <|skeleton|>
class PackageServiceServicer:
"""Allows clients to query the Daml-LF packages that are supported by the server."""
def ListPackages(self, request, context):
"""Returns the identifiers of all supported packages."""
<|body_0|>
def GetPackage(self, request, context):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PackageServiceServicer:
"""Allows clients to query the Daml-LF packages that are supported by the server."""
def ListPackages(self, request, context):
"""Returns the identifiers of all supported packages."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Meth... | the_stack_v2_python_sparse | python/dazl/_gen/com/daml/ledger/api/v1/package_service_pb2_grpc.py | digital-asset/dazl-client | train | 12 |
8a71b6f0e978e4b6adfa35cd3bf425a792a51733 | [
"pq = []\nres = []\nfor i in range(len(nums1)):\n for j in range(len(nums2)):\n heapq.heappush(pq, (nums1[i] + nums2[j], (nums1[i], nums2[j])))\nfor i in range(k):\n if pq:\n _, (n1, n2) = heapq.heappop(pq)\n res.append([n1, n2])\nreturn res",
"queue = []\n\ndef push(i, j):\n if i < ... | <|body_start_0|>
pq = []
res = []
for i in range(len(nums1)):
for j in range(len(nums2)):
heapq.heappush(pq, (nums1[i] + nums2[j], (nums1[i], nums2[j])))
for i in range(k):
if pq:
_, (n1, n2) = heapq.heappop(pq)
res.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairsFast(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_36k_train_029484 | 2,159 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"name": "kSmallestPairs",
"signature": "def kSmallestPairs(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairsFast(self, nums1, nums2, k): :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kSmallestPairs(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]
- def kSmallestPairsFast(self, nums1, nums2, k): :ty... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
<|body_0|>
def kSmallestPairsFast(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtyp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kSmallestPairs(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]]"""
pq = []
res = []
for i in range(len(nums1)):
for j in range(len(nums2)):
heapq.heappush(pq, (nums1[i] + nums... | the_stack_v2_python_sparse | F/FindKPairswithSmallestSums.py | bssrdf/pyleet | train | 2 | |
54af25741b68793d7e1de649df2f4d3af29fe226 | [
"if not len(result.affected_code) > 0:\n return 'The result is not associated with any source code.'\nfilenames = set((src.renamed_file(file_diff_dict) for src in result.affected_code))\nif not all((exists(filename) for filename in filenames)):\n return \"The result is associated with source code that doesn't... | <|body_start_0|>
if not len(result.affected_code) > 0:
return 'The result is not associated with any source code.'
filenames = set((src.renamed_file(file_diff_dict) for src in result.affected_code))
if not all((exists(filename) for filename in filenames)):
return "The res... | OpenEditorAction | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
<|body_0|>
def build_editor_call_args(self, editor, edi... | stack_v2_sparse_classes_36k_train_029485 | 6,600 | no_license | [
{
"docstring": "For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted.",
"name": "is_applicable",
"signature": "def is_applicable(result: Result, original_file_dict, file_diff_dict)"
},
{
"docstring": "Create argument list whi... | 3 | stack_v2_sparse_classes_30k_train_000942 | Implement the Python class `OpenEditorAction` described below.
Class description:
Implement the OpenEditorAction class.
Method signatures and docstrings:
- def is_applicable(result: Result, original_file_dict, file_diff_dict): For being applicable, the result has to point to a number of files that have to exist i.e. ... | Implement the Python class `OpenEditorAction` described below.
Class description:
Implement the OpenEditorAction class.
Method signatures and docstrings:
- def is_applicable(result: Result, original_file_dict, file_diff_dict): For being applicable, the result has to point to a number of files that have to exist i.e. ... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
<|body_0|>
def build_editor_call_args(self, editor, edi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpenEditorAction:
def is_applicable(result: Result, original_file_dict, file_diff_dict):
"""For being applicable, the result has to point to a number of files that have to exist i.e. have not been previously deleted."""
if not len(result.affected_code) > 0:
return 'The result is no... | the_stack_v2_python_sparse | python/coala_coala/coala-master/coalib/results/result_actions/OpenEditorAction.py | LiuFang816/SALSTM_py_data | train | 10 | |
892cbc07a1524f47caaf9eddeb1e1485bb79c915 | [
"data = form.cleaned_data\nself.success_url = reverse('register_courses', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})\nreturn super().form_valid(form)",
"context = super().get_context_data(**kwargs)\ncontext['title_text'] = 'Choose Where To Register Courses'\ncontext['detail_text'] = ... | <|body_start_0|>
data = form.cleaned_data
self.success_url = reverse('register_courses', kwargs={'level': int(data['level']), 'semester': int(data['semester'])})
return super().form_valid(form)
<|end_body_0|>
<|body_start_1|>
context = super().get_context_data(**kwargs)
context[... | View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid. | RegisterCourseView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterCourseView:
"""View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
def get_... | stack_v2_sparse_classes_36k_train_029486 | 29,759 | no_license | [
{
"docstring": "Compute the success URL and call super.form_valid()",
"name": "form_valid",
"signature": "def form_valid(self, form)"
},
{
"docstring": "Return the data used in the templates rendering.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
}
... | 2 | stack_v2_sparse_classes_30k_train_009983 | Implement the Python class `RegisterCourseView` described below.
Class description:
View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL and ca... | Implement the Python class `RegisterCourseView` described below.
Class description:
View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid.
Method signatures and docstrings:
- def form_valid(self, form): Compute the success URL and ca... | 06bc577d01d3dbf6c425e03dcb903977a38e377c | <|skeleton|>
class RegisterCourseView:
"""View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
<|body_0|>
def get_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterCourseView:
"""View for choosing the courses to register. Check that the user's account is still active. Redirects to register_courses view on form valid."""
def form_valid(self, form):
"""Compute the success URL and call super.form_valid()"""
data = form.cleaned_data
self... | the_stack_v2_python_sparse | cbt/views.py | Festusali/CBTest | train | 6 |
2eb41f58fc206d51ecec280726d9ef71e020907a | [
"context = super(DeleteView, self).get_context_data(**kwargs)\ncontext['user_type'] = get_user_type(self.request.user)\nreturn context",
"self.object = self.get_object()\nif request.POST.get('goback'):\n url = '/updateAppointment/' + str(self.get_object().id)\n return HttpResponseRedirect(url)\nelse:\n i... | <|body_start_0|>
context = super(DeleteView, self).get_context_data(**kwargs)
context['user_type'] = get_user_type(self.request.user)
return context
<|end_body_0|>
<|body_start_1|>
self.object = self.get_object()
if request.POST.get('goback'):
url = '/updateAppointme... | Deletes the Appointment | DeleteAppointment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Validates info :param request: :param args: arrgume... | stack_v2_sparse_classes_36k_train_029487 | 14,106 | no_license | [
{
"docstring": "Sends info to the template :param kwargs: kwarguments :return:",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Validates info :param request: :param args: arrguments :param kwargs: kwarguments :return:",
"name": "post",
... | 2 | stack_v2_sparse_classes_30k_test_000367 | Implement the Python class `DeleteAppointment` described below.
Class description:
Deletes the Appointment
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Sends info to the template :param kwargs: kwarguments :return:
- def post(self, request, *args, **kwargs): Validates info :param request:... | Implement the Python class `DeleteAppointment` described below.
Class description:
Deletes the Appointment
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Sends info to the template :param kwargs: kwarguments :return:
- def post(self, request, *args, **kwargs): Validates info :param request:... | 20b446da14ee3b44f9e184c4be48e23805fb5f10 | <|skeleton|>
class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Validates info :param request: :param args: arrgume... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteAppointment:
"""Deletes the Appointment"""
def get_context_data(self, **kwargs):
"""Sends info to the template :param kwargs: kwarguments :return:"""
context = super(DeleteView, self).get_context_data(**kwargs)
context['user_type'] = get_user_type(self.request.user)
... | the_stack_v2_python_sparse | HealthApps/views/appointment.py | KevKode/HealthNet | train | 0 |
33503f923c891efbc5642917745ee32465f3430d | [
"vocab_size = 100\nsequence_length = 512\nd_model = 64\nd_latents = 48\nnum_layers = 2\nencoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, num_self_attends_per_block=num_layers)\nsequence_encoder_cfg = cfg.SequenceEncoderConfig(d_model=d_model, d_latents=d_latents, vocab_size=vocab_size, encoder=encoder_cfg)\nte... | <|body_start_0|>
vocab_size = 100
sequence_length = 512
d_model = 64
d_latents = 48
num_layers = 2
encoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, num_self_attends_per_block=num_layers)
sequence_encoder_cfg = cfg.SequenceEncoderConfig(d_model=d_model, d_late... | ClassifierTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_head):
"""Validate that the Keras object can be invoked."""
<|b... | stack_v2_sparse_classes_36k_train_029488 | 8,478 | permissive | [
{
"docstring": "Validate that the Keras object can be created.",
"name": "test_perceiver_trainer",
"signature": "def test_perceiver_trainer(self, num_classes)"
},
{
"docstring": "Validate that the Keras object can be invoked.",
"name": "test_perceiver_trainer_tensor_call",
"signature": "... | 3 | stack_v2_sparse_classes_30k_train_005642 | Implement the Python class `ClassifierTest` described below.
Class description:
Implement the ClassifierTest class.
Method signatures and docstrings:
- def test_perceiver_trainer(self, num_classes): Validate that the Keras object can be created.
- def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_h... | Implement the Python class `ClassifierTest` described below.
Class description:
Implement the ClassifierTest class.
Method signatures and docstrings:
- def test_perceiver_trainer(self, num_classes): Validate that the Keras object can be created.
- def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_h... | d3507b550a3ade40cade60a79eb5b8978b56c7ae | <|skeleton|>
class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_perceiver_trainer_tensor_call(self, num_classes, use_custom_head):
"""Validate that the Keras object can be invoked."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClassifierTest:
def test_perceiver_trainer(self, num_classes):
"""Validate that the Keras object can be created."""
vocab_size = 100
sequence_length = 512
d_model = 64
d_latents = 48
num_layers = 2
encoder_cfg = cfg.EncoderConfig(v_last_dim=d_latents, nu... | the_stack_v2_python_sparse | official/projects/perceiver/modeling/models/classifier_test.py | jianzhnie/models | train | 2 | |
d1e5cdd2c43b933bf6c45b09e8e92bdd19d417f2 | [
"super(Repoquery, self).__init__(None)\nself.name = name\nself.query_type = query_type\nself.show_duplicates = show_duplicates\nself.match_version = match_version\nself.verbose = verbose\nif self.match_version:\n self.show_duplicates = True\nself.query_format = '%{version}|%{release}|%{arch}|%{repo}|%{version}-%... | <|body_start_0|>
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show_duplicates
self.match_version = match_version
self.verbose = verbose
if self.match_version:
self.show_duplicates = True
... | Class to wrap the repoquery | Repoquery | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_36k_train_029489 | 4,645 | permissive | [
{
"docstring": "Constructor for YumList",
"name": "__init__",
"signature": "def __init__(self, name, query_type, show_duplicates, match_version, verbose)"
},
{
"docstring": "build the repoquery cmd options",
"name": "build_cmd",
"signature": "def build_cmd(self)"
},
{
"docstring"... | 5 | stack_v2_sparse_classes_30k_train_011208 | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | Implement the Python class `Repoquery` described below.
Class description:
Class to wrap the repoquery
Method signatures and docstrings:
- def __init__(self, name, query_type, show_duplicates, match_version, verbose): Constructor for YumList
- def build_cmd(self): build the repoquery cmd options
- def process_version... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
<|body_0|>
def build_cmd(self):
"""build the repoquery cmd options"""
<|body_1|>
def process_ver... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Repoquery:
"""Class to wrap the repoquery"""
def __init__(self, name, query_type, show_duplicates, match_version, verbose):
"""Constructor for YumList"""
super(Repoquery, self).__init__(None)
self.name = name
self.query_type = query_type
self.show_duplicates = show... | the_stack_v2_python_sparse | ansible/roles/lib_repoquery/build/src/repoquery.py | openshift/openshift-tools | train | 170 |
630c743dd7089318ff2d657161586abe52ef47da | [
"lines = system_command.split_lines(text)\nheader = clazz._parse_header(lines.pop(0))\nitems = []\nfor line in lines:\n item = clazz._parse_one_line(line, header['NAME'])\n if item:\n items.append(item)\nreturn items",
"name = line[name_index:] or None\nparts = system_command.split_by_white_space(lin... | <|body_start_0|>
lines = system_command.split_lines(text)
header = clazz._parse_header(lines.pop(0))
items = []
for line in lines:
item = clazz._parse_one_line(line, header['NAME'])
if item:
items.append(item)
return items
<|end_body_0|>
<... | Class to parse the output of "lsof" on unix | lsof_output_parser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lsof_output_parser:
"""Class to parse the output of "lsof" on unix"""
def parse_lsof_output(clazz, text):
"""Parse one line of ps aux output."""
<|body_0|>
def _parse_one_line(clazz, line, name_index):
"""Parse one item."""
<|body_1|>
def _parse_head... | stack_v2_sparse_classes_36k_train_029490 | 1,402 | permissive | [
{
"docstring": "Parse one line of ps aux output.",
"name": "parse_lsof_output",
"signature": "def parse_lsof_output(clazz, text)"
},
{
"docstring": "Parse one item.",
"name": "_parse_one_line",
"signature": "def _parse_one_line(clazz, line, name_index)"
},
{
"docstring": "Parse l... | 3 | null | Implement the Python class `lsof_output_parser` described below.
Class description:
Class to parse the output of "lsof" on unix
Method signatures and docstrings:
- def parse_lsof_output(clazz, text): Parse one line of ps aux output.
- def _parse_one_line(clazz, line, name_index): Parse one item.
- def _parse_header(c... | Implement the Python class `lsof_output_parser` described below.
Class description:
Class to parse the output of "lsof" on unix
Method signatures and docstrings:
- def parse_lsof_output(clazz, text): Parse one line of ps aux output.
- def _parse_one_line(clazz, line, name_index): Parse one item.
- def _parse_header(c... | b9dd35b518848cea82e43d5016e425cc7dac32e5 | <|skeleton|>
class lsof_output_parser:
"""Class to parse the output of "lsof" on unix"""
def parse_lsof_output(clazz, text):
"""Parse one line of ps aux output."""
<|body_0|>
def _parse_one_line(clazz, line, name_index):
"""Parse one item."""
<|body_1|>
def _parse_head... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class lsof_output_parser:
"""Class to parse the output of "lsof" on unix"""
def parse_lsof_output(clazz, text):
"""Parse one line of ps aux output."""
lines = system_command.split_lines(text)
header = clazz._parse_header(lines.pop(0))
items = []
for line in lines:
... | the_stack_v2_python_sparse | lib/bes/unix/lsof/lsof_output_parser.py | reconstruir/bes | train | 0 |
872456fdaf9aec2fccae4fba10d62ef84a223ec5 | [
"super().setUp()\nc = self.c\ng.app.idleTimeManager = leoApp.IdleTimeManager()\ng.app.idleTimeManager.start()\ng.app.externalFilesController = leoExternalFiles.ExternalFilesController(c=c)",
"efc = g.app.externalFilesController\nfor i in range(100):\n efc.on_idle()"
] | <|body_start_0|>
super().setUp()
c = self.c
g.app.idleTimeManager = leoApp.IdleTimeManager()
g.app.idleTimeManager.start()
g.app.externalFilesController = leoExternalFiles.ExternalFilesController(c=c)
<|end_body_0|>
<|body_start_1|>
efc = g.app.externalFilesController
... | TestExternalFiles | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestExternalFiles:
def setUp(self):
"""setUp for TestFind class"""
<|body_0|>
def test_on_idle(self):
"""A minimal test of the on_idle and all its helpers. More detail tests would be difficult."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super()... | stack_v2_sparse_classes_36k_train_029491 | 1,137 | permissive | [
{
"docstring": "setUp for TestFind class",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "A minimal test of the on_idle and all its helpers. More detail tests would be difficult.",
"name": "test_on_idle",
"signature": "def test_on_idle(self)"
}
] | 2 | null | Implement the Python class `TestExternalFiles` described below.
Class description:
Implement the TestExternalFiles class.
Method signatures and docstrings:
- def setUp(self): setUp for TestFind class
- def test_on_idle(self): A minimal test of the on_idle and all its helpers. More detail tests would be difficult. | Implement the Python class `TestExternalFiles` described below.
Class description:
Implement the TestExternalFiles class.
Method signatures and docstrings:
- def setUp(self): setUp for TestFind class
- def test_on_idle(self): A minimal test of the on_idle and all its helpers. More detail tests would be difficult.
<|... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class TestExternalFiles:
def setUp(self):
"""setUp for TestFind class"""
<|body_0|>
def test_on_idle(self):
"""A minimal test of the on_idle and all its helpers. More detail tests would be difficult."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestExternalFiles:
def setUp(self):
"""setUp for TestFind class"""
super().setUp()
c = self.c
g.app.idleTimeManager = leoApp.IdleTimeManager()
g.app.idleTimeManager.start()
g.app.externalFilesController = leoExternalFiles.ExternalFilesController(c=c)
def te... | the_stack_v2_python_sparse | leo/unittests/core/test_leoExternalFiles.py | leo-editor/leo-editor | train | 1,671 | |
9fd41adb826028b8f2c20b4c79f621e32494de74 | [
"dt = dict()\nfor n in arr:\n if n in dt:\n dt[n] += 1\n else:\n dt[n] = 1\nret = -1\nfor k, v in dt.items():\n if k == v:\n ret = max(ret, k)\nreturn ret",
"dt = collections.Counter(arr)\nret = -1\nfor k, v in dt.items():\n if k == v:\n ret = max(ret, k)\nreturn ret"
] | <|body_start_0|>
dt = dict()
for n in arr:
if n in dt:
dt[n] += 1
else:
dt[n] = 1
ret = -1
for k, v in dt.items():
if k == v:
ret = max(ret, k)
return ret
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min."""
<|body_0|>
def findLucky2(self, arr):
""":type arr: List[int] :rtype: int thought: hashmap to ch... | stack_v2_sparse_classes_36k_train_029492 | 1,591 | no_license | [
{
"docstring": ":type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min.",
"name": "findLucky",
"signature": "def findLucky(self, arr)"
},
{
"docstring": ":type arr: List[int] :rtype: int thought: hashmap to check k = v 04/0... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr): :type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min.
- def findLucky2(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findLucky(self, arr): :type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min.
- def findLucky2(self, ... | 02726da394971ef02616a038dadc126c6ff260de | <|skeleton|>
class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min."""
<|body_0|>
def findLucky2(self, arr):
""":type arr: List[int] :rtype: int thought: hashmap to ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findLucky(self, arr):
""":type arr: List[int] :rtype: int thought: hashmap to check k = v 04/06/2022 15:08 Accepted 70 ms 13.8 MB python easy 5 - 10 min."""
dt = dict()
for n in arr:
if n in dt:
dt[n] += 1
else:
dt[n... | the_stack_v2_python_sparse | N1394_FindLuckyIntegerinanArray.py | zerghua/leetcode-python | train | 2 | |
74740fad7b96eeb46118e5d97bf81abef5df8f6e | [
"super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_voltage')\nself._attr_name = f'Phase {phase} voltage'\nself._phase = phase",
"phase_sensor = getattr(self.coordinator.data, f'phase{self._phase}', None)\nif phase_sensor is None:\n return None\nreturn phase_sensor.voltage"
] | <|body_start_0|>
super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_voltage')
self._attr_name = f'Phase {phase} voltage'
self._phase = phase
<|end_body_0|>
<|body_start_1|>
phase_sensor = getattr(self.coordinator.data, f'phase{self._phase}', None)
if ... | The current voltage of a single phase. | PhaseVoltageSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PhaseVoltageSensor:
"""The current voltage of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the voltage phase sensor."""
<|body_0|>
def get_sensor(self) -> YoulessSensor | None:
... | stack_v2_sparse_classes_36k_train_029493 | 11,812 | permissive | [
{
"docstring": "Initialize the voltage phase sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None"
},
{
"docstring": "Get the sensor value from the coordinator for phase voltage.",
"name": "get_sensor"... | 2 | null | Implement the Python class `PhaseVoltageSensor` described below.
Class description:
The current voltage of a single phase.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None: Initialize the voltage phase sensor.
- def get_sensor(self... | Implement the Python class `PhaseVoltageSensor` described below.
Class description:
The current voltage of a single phase.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None: Initialize the voltage phase sensor.
- def get_sensor(self... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class PhaseVoltageSensor:
"""The current voltage of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the voltage phase sensor."""
<|body_0|>
def get_sensor(self) -> YoulessSensor | None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PhaseVoltageSensor:
"""The current voltage of a single phase."""
def __init__(self, coordinator: DataUpdateCoordinator[YoulessAPI], device: str, phase: int) -> None:
"""Initialize the voltage phase sensor."""
super().__init__(coordinator, device, 'power', 'Energy usage', f'phase_{phase}_v... | the_stack_v2_python_sparse | homeassistant/components/youless/sensor.py | home-assistant/core | train | 35,501 |
0df84decc24ae7a3ffdee03c7d344eec7c3ad6e1 | [
"path = path or self.location(cwd)\nif path is not None:\n self.path = path\nself.patterns = []\nself.parse()",
"cwd = cwd or os.getcwd()\nfor location in self.KNOWN_LOCATIONS:\n path = os.path.join(cwd, location)\n if os.path.isfile(path):\n return path\nraise ValueError('CODEOWNERS file not foun... | <|body_start_0|>
path = path or self.location(cwd)
if path is not None:
self.path = path
self.patterns = []
self.parse()
<|end_body_0|>
<|body_start_1|>
cwd = cwd or os.getcwd()
for location in self.KNOWN_LOCATIONS:
path = os.path.join(cwd, locati... | Provide interface to parse CODEOWNERS file and match a given path against it. | Codeowners | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codeowners:
"""Provide interface to parse CODEOWNERS file and match a given path against it."""
def __init__(self, path=None, cwd=None):
"""Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use any from known locations"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_029494 | 7,323 | permissive | [
{
"docstring": "Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use any from known locations",
"name": "__init__",
"signature": "def __init__(self, path=None, cwd=None)"
},
{
"docstring": "Return the location of the CODEOWNERS file.",
"name": "location",
... | 4 | stack_v2_sparse_classes_30k_train_014481 | Implement the Python class `Codeowners` described below.
Class description:
Provide interface to parse CODEOWNERS file and match a given path against it.
Method signatures and docstrings:
- def __init__(self, path=None, cwd=None): Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use... | Implement the Python class `Codeowners` described below.
Class description:
Provide interface to parse CODEOWNERS file and match a given path against it.
Method signatures and docstrings:
- def __init__(self, path=None, cwd=None): Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use... | 1e3bd6d4edef5cda5a0831a6a7ec8e4046659d17 | <|skeleton|>
class Codeowners:
"""Provide interface to parse CODEOWNERS file and match a given path against it."""
def __init__(self, path=None, cwd=None):
"""Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use any from known locations"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codeowners:
"""Provide interface to parse CODEOWNERS file and match a given path against it."""
def __init__(self, path=None, cwd=None):
"""Initialize Codeowners object. :param path: path to CODEOWNERS file otherwise try to use any from known locations"""
path = path or self.location(cwd)... | the_stack_v2_python_sparse | ddtrace/internal/codeowners.py | DataDog/dd-trace-py | train | 461 |
c8b08dd0624b3a0a305dd9b6e724a1e7ed61e0c7 | [
"ObjectManager.__init__(self)\nself.setters.update({'name': 'set_general', 'ac_check_methods': 'set_many', 'acl': 'set_acl'})\nself.getters.update({'name': 'get_general', 'ac_check_methods': 'get_many_to_many', 'acl': 'get_acl'})\nself.my_django_model = facade.models.Role",
"r = self.my_django_model(name=name)\nr... | <|body_start_0|>
ObjectManager.__init__(self)
self.setters.update({'name': 'set_general', 'ac_check_methods': 'set_many', 'acl': 'set_acl'})
self.getters.update({'name': 'get_general', 'ac_check_methods': 'get_many_to_many', 'acl': 'get_acl'})
self.my_django_model = facade.models.Role
<|... | Manage Roles in the Power Reg system | RoleManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleManager:
"""Manage Roles in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name):
"""Create a new Role @param name name of the Role @return a reference to the newly created Role struct with new primary ke... | stack_v2_sparse_classes_36k_train_029495 | 1,338 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new Role @param name name of the Role @return a reference to the newly created Role struct with new primary key indexed as 'id'",
"name": "create",
"signature": "def create(sel... | 2 | null | Implement the Python class `RoleManager` described below.
Class description:
Manage Roles in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name): Create a new Role @param name name of the Role @return a reference to the newly created Role struc... | Implement the Python class `RoleManager` described below.
Class description:
Manage Roles in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name): Create a new Role @param name name of the Role @return a reference to the newly created Role struc... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class RoleManager:
"""Manage Roles in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name):
"""Create a new Role @param name name of the Role @return a reference to the newly created Role struct with new primary ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleManager:
"""Manage Roles in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.setters.update({'name': 'set_general', 'ac_check_methods': 'set_many', 'acl': 'set_acl'})
self.getters.update({'name': 'get_general', 'ac_check_m... | the_stack_v2_python_sparse | pr_services/role_manager.py | ninemoreminutes/openassign-server | train | 0 |
5f3a445898b096e21ec5b174ec7f46d36c60555a | [
"dfile_dct = {} if dfile_dct is None else dfile_dct\nassert isinstance(ddir, DataDir)\nself.dir = ddir\nself.file = types.SimpleNamespace()\nfor name, obj in dfile_dct.items():\n assert isinstance(name, str)\n assert isinstance(obj, DataFile)\n setattr(self.file, name, obj)",
"ddir = self.dir.stacked_ove... | <|body_start_0|>
dfile_dct = {} if dfile_dct is None else dfile_dct
assert isinstance(ddir, DataDir)
self.dir = ddir
self.file = types.SimpleNamespace()
for name, obj in dfile_dct.items():
assert isinstance(name, str)
assert isinstance(obj, DataFile)
... | a single-layered system of directories and files | DataLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
<|bod... | stack_v2_sparse_classes_36k_train_029496 | 6,832 | permissive | [
{
"docstring": ":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`",
"name": "__init__",
"signature": "def __init__(self, ddir, dfile_dct=None)"
},
{
"docstring": "get a copy of this DataLay... | 2 | stack_v2_sparse_classes_30k_train_004555 | Implement the Python class `DataLayer` described below.
Class description:
a single-layered system of directories and files
Method signatures and docstrings:
- def __init__(self, ddir, dfile_dct=None): :param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance th... | Implement the Python class `DataLayer` described below.
Class description:
a single-layered system of directories and files
Method signatures and docstrings:
- def __init__(self, ddir, dfile_dct=None): :param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance th... | e52341a2b77b5e79b0e2cee73f48735d00fd6209 | <|skeleton|>
class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataLayer:
"""a single-layered system of directories and files"""
def __init__(self, ddir, dfile_dct=None):
""":param ddir: a DataDir object :param dfiles: a sequence of pairs `(name, obj)` where `obj` is a DataFile instance that will be accessible as `obj.file.name`"""
dfile_dct = {} if ... | the_stack_v2_python_sparse | old_autodir/factory.py | avcopan/filesystem | train | 0 |
6f57edb78cd065201968fd77094b217a2098e073 | [
"length = len(s)\nif length == 0:\n return 0\nwinner, i, j = (0, 0, 0)\ndictA = {}\nwhile (i < length) & (j < length):\n if s[j] not in dictA:\n dictA[s[j]] = j\n j += 1\n winner = max(winner, j - i)\n else:\n i = max(i, dictA[s[j]] + 1)\n dictA[s[j]] = j\n j += 1\... | <|body_start_0|>
length = len(s)
if length == 0:
return 0
winner, i, j = (0, 0, 0)
dictA = {}
while (i < length) & (j < length):
if s[j] not in dictA:
dictA[s[j]] = j
j += 1
winner = max(winner, j - i)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring_best(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def lengthOfLongestSubstring_sliding_opt(self, s):
""":type s: str :r... | stack_v2_sparse_classes_36k_train_029497 | 4,334 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring",
"signature": "def lengthOfLongestSubstring(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "lengthOfLongestSubstring_best",
"signature": "def lengthOfLongestSubstring_best(self, s)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_011880 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_best(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_sliding_opt(... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLongestSubstring(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_best(self, s): :type s: str :rtype: int
- def lengthOfLongestSubstring_sliding_opt(... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def lengthOfLongestSubstring_best(self, s):
""":type s: str :rtype: int"""
<|body_1|>
def lengthOfLongestSubstring_sliding_opt(self, s):
""":type s: str :r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLongestSubstring(self, s):
""":type s: str :rtype: int"""
length = len(s)
if length == 0:
return 0
winner, i, j = (0, 0, 0)
dictA = {}
while (i < length) & (j < length):
if s[j] not in dictA:
dictA[s[... | the_stack_v2_python_sparse | 3.lengthOfLongestSubstring.py | JerryRoc/leetcode | train | 0 | |
124d89a73fb7dd1d1fc6c57a25db1d25148e74f5 | [
"assert modality in {'rgb', 'flow', 'gray'}, 'Invalid modality.'\nsuper().__init__(modality, dropout_prob, weights_path=weights_path)\nself.conv3d_0c_1x1 = None\nself.avg_pool = None",
"input_tensor = input_tensor.permute((0, 4, 1, 2, 3))\nout = self.conv3d_1a_7x7(input_tensor)\nout = self.maxPool3d_2a_3x3(out)\n... | <|body_start_0|>
assert modality in {'rgb', 'flow', 'gray'}, 'Invalid modality.'
super().__init__(modality, dropout_prob, weights_path=weights_path)
self.conv3d_0c_1x1 = None
self.avg_pool = None
<|end_body_0|>
<|body_start_1|>
input_tensor = input_tensor.permute((0, 4, 1, 2, 3)... | I3DEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class I3DEncoder:
def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
<|body_0|>
def forward(self, input_tensor):
"""Encodes a stack of images. args:... | stack_v2_sparse_classes_36k_train_029498 | 1,641 | no_license | [
{
"docstring": "I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)",
"name": "__init__",
"signature": "def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None)"
},
{
"docstring": "Encodes a stack of images. args: input_tensor (torch.te... | 2 | stack_v2_sparse_classes_30k_val_000955 | Implement the Python class `I3DEncoder` described below.
Class description:
Implement the I3DEncoder class.
Method signatures and docstrings:
- def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None): I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)
- de... | Implement the Python class `I3DEncoder` described below.
Class description:
Implement the I3DEncoder class.
Method signatures and docstrings:
- def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None): I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)
- de... | ad0eec4a5691b43a1708a4d9f599a6d7725092dd | <|skeleton|>
class I3DEncoder:
def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
<|body_0|>
def forward(self, input_tensor):
"""Encodes a stack of images. args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class I3DEncoder:
def __init__(self, modality='gray', attention=False, dropout_prob=0, weights_path=None):
"""I3D encoder that encodes a stack of images into a block of size (length x 7 x 7)"""
assert modality in {'rgb', 'flow', 'gray'}, 'Invalid modality.'
super().__init__(modality, dropout... | the_stack_v2_python_sparse | cow_tus/models/modules/encoders.py | geoffreyangus/cow-tus | train | 0 | |
9060d1048a228b658c4b87e3cdb830835725f365 | [
"params = base.get_params(None, locals())\nrequest = http.Request('GET', self.get_url(), params)\nreturn (request, parsers.parse_json)",
"params = base.get_params(None, locals())\nrequest = http.Request('DELETE', self.get_url(), params)\nreturn (request, parsers.parse_json)"
] | <|body_start_0|>
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return (request, parsers.parse_json)
<|end_body_0|>
<|body_start_1|>
params = base.get_params(None, locals())
request = http.Request('DELETE', self.get_url(), params)
... | Products | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Products:
def get(self, start=None, limit=None):
"""Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals"""
<|body_0|>
def delete(self, product_attachment_id):
"""Deletes a product attachment from a deal, using ... | stack_v2_sparse_classes_36k_train_029499 | 6,104 | permissive | [
{
"docstring": "Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals",
"name": "get",
"signature": "def get(self, start=None, limit=None)"
},
{
"docstring": "Deletes a product attachment from a deal, using the product_attachment_id. Upstrea... | 2 | null | Implement the Python class `Products` described below.
Class description:
Implement the Products class.
Method signatures and docstrings:
- def get(self, start=None, limit=None): Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals
- def delete(self, product_att... | Implement the Python class `Products` described below.
Class description:
Implement the Products class.
Method signatures and docstrings:
- def get(self, start=None, limit=None): Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals
- def delete(self, product_att... | 25caa745a104c8dc209584fa359294c65dbf88bb | <|skeleton|>
class Products:
def get(self, start=None, limit=None):
"""Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals"""
<|body_0|>
def delete(self, product_attachment_id):
"""Deletes a product attachment from a deal, using ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Products:
def get(self, start=None, limit=None):
"""Lists products attached to a deal. Upstream documentation: https://developers.pipedrive.com/v1#methods-Deals"""
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return (request, pa... | the_stack_v2_python_sparse | libsaas/services/pipedrive/deals.py | piplcom/libsaas | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.