blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
744dcd144aab26d6fa138a570792b20f1ff9a44c | [
"self.min = np.array([0.0, 0.0])\nself.value = 0.0\nself.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, False, False]\nself.latex_name = 'Griewank Function'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = \\\\sum_{i=0}^{d... | <|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])
self.n = 2
self.smooth = True
self.info = [True, False, False]
self.latex_name = 'Griewank Function'
self.latex_type = 'Many Local ... | Griewank Function. | Griewank | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domai... | stack_v2_sparse_classes_10k_train_005100 | 1,071 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000328 | Implement the Python class `Griewank` described below.
Class description:
Griewank Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Griewank` described below.
Class description:
Griewank Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Griewank:
"""Griewank Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([0.0, 0.0])
self.value = 0.0
self.domain = np.array([[-600.0, 600.0], [-600.0, 600.0]])
self.n = 2
self.smooth = True
self.info = [True, False, False]
... | the_stack_v2_python_sparse | ctf/functions2d/griewank.py | cntaylor/ctf | train | 1 |
5224be02e393d49a774da1d46fa588c63113aa67 | [
"x_bytes = int(math.ceil(math.log(x, 2) / 8.0))\ny_bytes = int(math.ceil(math.log(y, 2) / 8.0))\nnum_bytes = max(x_bytes, y_bytes)\nbyte_string = b'\\x04'\nbyte_string += int_to_bytes(x, width=num_bytes)\nbyte_string += int_to_bytes(y, width=num_bytes)\nreturn cls(byte_string)",
"data = self.native\nfirst_byte = ... | <|body_start_0|>
x_bytes = int(math.ceil(math.log(x, 2) / 8.0))
y_bytes = int(math.ceil(math.log(y, 2) / 8.0))
num_bytes = max(x_bytes, y_bytes)
byte_string = b'\x04'
byte_string += int_to_bytes(x, width=num_bytes)
byte_string += int_to_bytes(y, width=num_bytes)
r... | In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates. | _ECPoint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ECPoint:
"""In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates."""
def from_coords(cls, x, y):
... | stack_v2_sparse_classes_10k_train_005101 | 37,863 | permissive | [
{
"docstring": "Creates an ECPoint object from the X and Y integer coordinates of the point :param x: The X coordinate, as an integer :param y: The Y coordinate, as an integer :return: An ECPoint object",
"name": "from_coords",
"signature": "def from_coords(cls, x, y)"
},
{
"docstring": "Returns... | 2 | null | Implement the Python class `_ECPoint` described below.
Class description:
In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates.
... | Implement the Python class `_ECPoint` described below.
Class description:
In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates.
... | 4cd721be8595db52b620cc26cd455d95bf56b85b | <|skeleton|>
class _ECPoint:
"""In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates."""
def from_coords(cls, x, y):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _ECPoint:
"""In both PublicKeyInfo and PrivateKeyInfo, the EC public key is a byte string that is encoded as a bit string. This class adds convenience methods for converting to and from the byte string to a pair of integers that are the X and Y coordinates."""
def from_coords(cls, x, y):
"""Creat... | the_stack_v2_python_sparse | jc/parsers/asn1crypto/keys.py | kellyjonbrazil/jc | train | 6,278 |
603ff58f6b74cde8a2e55861f2782c285b3c39ae | [
"self._size = size\nself._window = [None] * self._size\nself._len = 0\nself._ix = 0\nself._sum = 0",
"if self._window[self._ix]:\n self._sum -= self._window[self._ix]\nself._window[self._ix] = val\nself._ix = (self._ix + 1) % self._size\nself._sum += val\nself._len = min(self._size, self._len + 1)\nreturn self... | <|body_start_0|>
self._size = size
self._window = [None] * self._size
self._len = 0
self._ix = 0
self._sum = 0
<|end_body_0|>
<|body_start_1|>
if self._window[self._ix]:
self._sum -= self._window[self._ix]
self._window[self._ix] = val
self._ix... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
<|body_0|>
def next(self, val: int) -> float:
"""O(1)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self._size = size
self._window = [None] * self._size
self._len =... | stack_v2_sparse_classes_10k_train_005102 | 596 | no_license | [
{
"docstring": "Space: O(size)",
"name": "__init__",
"signature": "def __init__(self, size: int)"
},
{
"docstring": "O(1)",
"name": "next",
"signature": "def next(self, val: int) -> float"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Space: O(size)
- def next(self, val: int) -> float: O(1) | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size: int): Space: O(size)
- def next(self, val: int) -> float: O(1)
<|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"... | 9a20e1835652f5e6c33ef5c238f622e81f84ca26 | <|skeleton|>
class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
<|body_0|>
def next(self, val: int) -> float:
"""O(1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size: int):
"""Space: O(size)"""
self._size = size
self._window = [None] * self._size
self._len = 0
self._ix = 0
self._sum = 0
def next(self, val: int) -> float:
"""O(1)"""
if self._window[self._ix]:
... | the_stack_v2_python_sparse | leetcode/p0346_moving_average_from_data_stream.py | weak-head/leetcode | train | 0 | |
4992ca924ae1eda0db1eebd2229a64057548637c | [
"self._name = name or 'bond'\nif holiday_calendar is None:\n holiday_calendar = dates.create_holiday_calendar(weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY)\nwith tf.name_scope(self._name):\n self._dtype = dtype\n self._settlement_date = dates.convert_to_date_tensor(settlement_date)\n self._maturity_da... | <|body_start_0|>
self._name = name or 'bond'
if holiday_calendar is None:
holiday_calendar = dates.create_holiday_calendar(weekend_mask=dates.WeekendMask.SATURDAY_SUNDAY)
with tf.name_scope(self._name):
self._dtype = dtype
self._settlement_date = dates.convert... | Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made periodically (for example quarterly or semi-annually) where the last pay... | Bond | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bond:
"""Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made periodically (for example quarterly or s... | stack_v2_sparse_classes_10k_train_005103 | 8,789 | permissive | [
{
"docstring": "Initialize a batch of fixed coupon bonds. Args: settlement_date: A rank 1 `DateTensor` specifying the settlement date of the bonds. maturity_date: A rank 1 `DateTensor` specifying the maturity dates of the bonds. The shape of the input should be the same as that of `settlement_date`. coupon_spec... | 3 | stack_v2_sparse_classes_30k_train_004165 | Implement the Python class `Bond` described below.
Class description:
Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made p... | Implement the Python class `Bond` described below.
Class description:
Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made p... | 0d3a2193c0f2d320b65e602cf01d7a617da484df | <|skeleton|>
class Bond:
"""Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made periodically (for example quarterly or s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Bond:
"""Represents a batch of fixed coupon bonds. Bonds are fixed income securities where the issuer makes periodic payments (or coupons) on a principal amount (also known as the face value) based on a fixed annualized interest rate. The payments are made periodically (for example quarterly or semi-annually)... | the_stack_v2_python_sparse | tf_quant_finance/experimental/instruments/bond.py | google/tf-quant-finance | train | 4,165 |
5d3215aed2f7a7efbe1d2107b7d4bb3f2fc89682 | [
"try:\n qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validate(self.get_query_args())\nexcept SchemaError as e:\n logging.warn(... | <|body_start_0|>
try:
qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validate(self.get_query_args())
except Sc... | Node | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|>
def post(self):
"""站点添加 :return:"""
<|body_1|>
def delete(self):
"""站点删除 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
qs = Schema({Optional('page',... | stack_v2_sparse_classes_10k_train_005104 | 24,267 | permissive | [
{
"docstring": "站点列表 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "站点添加 :return:",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "站点删除 :return:",
"name": "delete",
"signature": "def delete(self)"
}
] | 3 | stack_v2_sparse_classes_30k_train_003118 | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): 站点列表 :return:
- def post(self): 站点添加 :return:
- def delete(self): 站点删除 :return: | Implement the Python class `Node` described below.
Class description:
Implement the Node class.
Method signatures and docstrings:
- def get(self): 站点列表 :return:
- def post(self): 站点添加 :return:
- def delete(self): 站点删除 :return:
<|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|... | a7c9567975b5372b2edabddb0fec8d73bc01c3dc | <|skeleton|>
class Node:
def get(self):
"""站点列表 :return:"""
<|body_0|>
def post(self):
"""站点添加 :return:"""
<|body_1|>
def delete(self):
"""站点删除 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Node:
def get(self):
"""站点列表 :return:"""
try:
qs = Schema({Optional('page', default=1): schema_int, Optional('count', default=20): schema_int, Optional('limit', default=1): schema_bool, Optional('only'): schema_unicode, Optional('order_by', default='name'): schema_unicode}).validat... | the_stack_v2_python_sparse | Dispatcher/api_gateway/express/handlers/yun.py | cash2one/Logistics | train | 0 | |
f77e4a6a531897333011cdc2b314447b56386524 | [
"with tempfile.TemporaryDirectory() as tmp_dir:\n out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False)\n self.assertEqual(err_code, 0)\n self.assertEqual(err, '')\n self.assertEqual(out, '')\n out, err, err_code = utils.execute(['mkdir', 'tmp'], location=tmp_dir, chec... | <|body_start_0|>
with tempfile.TemporaryDirectory() as tmp_dir:
out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False)
self.assertEqual(err_code, 0)
self.assertEqual(err, '')
self.assertEqual(out, '')
out, err, err_code =... | Tests the execute function. | ExecuteTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExecuteTest:
"""Tests the execute function."""
def test_valid_command(self):
"""Tests that execute can produce valid output."""
<|body_0|>
def test_error_command(self):
"""Tests that execute can correctly surface errors."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_10k_train_005105 | 5,775 | permissive | [
{
"docstring": "Tests that execute can produce valid output.",
"name": "test_valid_command",
"signature": "def test_valid_command(self)"
},
{
"docstring": "Tests that execute can correctly surface errors.",
"name": "test_error_command",
"signature": "def test_error_command(self)"
}
] | 2 | null | Implement the Python class `ExecuteTest` described below.
Class description:
Tests the execute function.
Method signatures and docstrings:
- def test_valid_command(self): Tests that execute can produce valid output.
- def test_error_command(self): Tests that execute can correctly surface errors. | Implement the Python class `ExecuteTest` described below.
Class description:
Tests the execute function.
Method signatures and docstrings:
- def test_valid_command(self): Tests that execute can produce valid output.
- def test_error_command(self): Tests that execute can correctly surface errors.
<|skeleton|>
class E... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class ExecuteTest:
"""Tests the execute function."""
def test_valid_command(self):
"""Tests that execute can produce valid output."""
<|body_0|>
def test_error_command(self):
"""Tests that execute can correctly surface errors."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExecuteTest:
"""Tests the execute function."""
def test_valid_command(self):
"""Tests that execute can produce valid output."""
with tempfile.TemporaryDirectory() as tmp_dir:
out, err, err_code = utils.execute(['ls', '.'], location=tmp_dir, check_result=False)
self... | the_stack_v2_python_sparse | infra/utils_test.py | google/oss-fuzz | train | 9,438 |
ee7b20c899045c355f143aaf05dd736a276a9ae8 | [
"self.session = Session()\nself.encode = 'utf-8'\nself.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Host': 'www... | <|body_start_0|>
self.session = Session()
self.encode = 'utf-8'
self.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6', 'Cache-Control': 'max-age=0', 'Conne... | 父类 | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""父类"""
def __init__(self, encode=None):
"""init"""
<|body_0|>
def request(self, url):
"""request active"""
<|body_1|>
def parse(self, html, path):
"""parse page element"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005106 | 2,967 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, encode=None)"
},
{
"docstring": "request active",
"name": "request",
"signature": "def request(self, url)"
},
{
"docstring": "parse page element",
"name": "parse",
"signature": "def parse(self, ht... | 3 | stack_v2_sparse_classes_30k_val_000128 | Implement the Python class `Base` described below.
Class description:
父类
Method signatures and docstrings:
- def __init__(self, encode=None): init
- def request(self, url): request active
- def parse(self, html, path): parse page element | Implement the Python class `Base` described below.
Class description:
父类
Method signatures and docstrings:
- def __init__(self, encode=None): init
- def request(self, url): request active
- def parse(self, html, path): parse page element
<|skeleton|>
class Base:
"""父类"""
def __init__(self, encode=None):
... | b8dd4dd6dafaf9899e97bbb75a3ef80246ec427b | <|skeleton|>
class Base:
"""父类"""
def __init__(self, encode=None):
"""init"""
<|body_0|>
def request(self, url):
"""request active"""
<|body_1|>
def parse(self, html, path):
"""parse page element"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Base:
"""父类"""
def __init__(self, encode=None):
"""init"""
self.session = Session()
self.encode = 'utf-8'
self.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch, br', 'Accept-Language'... | the_stack_v2_python_sparse | fourth_week/seventh_day/encapsulation.py | czkun1986/Let-s-go-python- | train | 0 |
1b91455b101913a67ef290ee5e76c04419515f47 | [
"increase_height = [-1]\nmax_area = 0\nfor idx, height in enumerate(heights):\n while increase_height[-1] != -1 and heights[increase_height[-1]] >= height:\n max_area = max(max_area, heights[increase_height.pop()] * (idx - increase_height[-1] - 1))\n increase_height.append(idx)\nwhile increase_height[-... | <|body_start_0|>
increase_height = [-1]
max_area = 0
for idx, height in enumerate(heights):
while increase_height[-1] != -1 and heights[increase_height[-1]] >= height:
max_area = max(max_area, heights[increase_height.pop()] * (idx - increase_height[-1] - 1))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
increase_height... | stack_v2_sparse_classes_10k_train_005107 | 1,463 | no_license | [
{
"docstring": ":type heights: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, heights)"
},
{
"docstring": ":type matrix: List[List[str]] :rtype: int",
"name": "maximalRectangle",
"signature": "def maximalRectangle(self, matrix)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, heights): :type heights: List[int] :rtype: int
- def maximalRectangle(self, matrix): :type matrix: List[List[str]] :rtype: int
<|skeleton|>
class ... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
<|body_0|>
def maximalRectangle(self, matrix):
""":type matrix: List[List[str]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, heights):
""":type heights: List[int] :rtype: int"""
increase_height = [-1]
max_area = 0
for idx, height in enumerate(heights):
while increase_height[-1] != -1 and heights[increase_height[-1]] >= height:
max_a... | the_stack_v2_python_sparse | LeetCodes/facebook/Maximal Rectangle.py | chutianwen/LeetCodes | train | 0 | |
10da93c0d7f5ef64418ea9b565226d9d449d84f1 | [
"flag = True\na_index = 0\nb_index = 0\nresult = ''\nwhile a_index < A or b_index < B:\n if flag:\n if A - a_index >= 2:\n result += 'aa'\n elif A - a_index >= 1:\n result += 'a'\n a_index += 2\n else:\n if B - b_index >= 2:\n result += 'bb'\n ... | <|body_start_0|>
flag = True
a_index = 0
b_index = 0
result = ''
while a_index < A or b_index < B:
if flag:
if A - a_index >= 2:
result += 'aa'
elif A - a_index >= 1:
result += 'a'
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _strWithout3a3b(self, A, B):
""":type A: int :type B: int :rtype: str"""
<|body_0|>
def _strWithout3a3b(self, A, B):
""":type A: int :type B: int :rtype: str"""
<|body_1|>
def strWithout3a3b(self, A, B):
""":type A: int :type B: int... | stack_v2_sparse_classes_10k_train_005108 | 3,244 | permissive | [
{
"docstring": ":type A: int :type B: int :rtype: str",
"name": "_strWithout3a3b",
"signature": "def _strWithout3a3b(self, A, B)"
},
{
"docstring": ":type A: int :type B: int :rtype: str",
"name": "_strWithout3a3b",
"signature": "def _strWithout3a3b(self, A, B)"
},
{
"docstring":... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _strWithout3a3b(self, A, B): :type A: int :type B: int :rtype: str
- def _strWithout3a3b(self, A, B): :type A: int :type B: int :rtype: str
- def strWithout3a3b(self, A, B): ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _strWithout3a3b(self, A, B): :type A: int :type B: int :rtype: str
- def _strWithout3a3b(self, A, B): :type A: int :type B: int :rtype: str
- def strWithout3a3b(self, A, B): ... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _strWithout3a3b(self, A, B):
""":type A: int :type B: int :rtype: str"""
<|body_0|>
def _strWithout3a3b(self, A, B):
""":type A: int :type B: int :rtype: str"""
<|body_1|>
def strWithout3a3b(self, A, B):
""":type A: int :type B: int... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _strWithout3a3b(self, A, B):
""":type A: int :type B: int :rtype: str"""
flag = True
a_index = 0
b_index = 0
result = ''
while a_index < A or b_index < B:
if flag:
if A - a_index >= 2:
result += 'aa'
... | the_stack_v2_python_sparse | 984.string-without-aaa-or-bbb.py | windard/leeeeee | train | 0 | |
dfda78681fe7f41c8f6aecdce8fffbffdbf9448f | [
"self.explanation_type = explanation_type\nself._internal_obj = internal_obj\nself.feature_names = feature_names\nself.feature_types = feature_types\nself.name = name\nself.selector = selector",
"if key is None:\n return self._internal_obj['overall']\nreturn None",
"from ..visual.plot import plot_density\nda... | <|body_start_0|>
self.explanation_type = explanation_type
self._internal_obj = internal_obj
self.feature_names = feature_names
self.feature_types = feature_types
self.name = name
self.selector = selector
<|end_body_0|>
<|body_start_1|>
if key is None:
... | Produces explanation specific to regression metrics. | RegressionExplanation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegressionExplanation:
"""Produces explanation specific to regression metrics."""
def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None):
"""Initializes class. Args: explanation_type: Type of explanation. internal_obj: A j... | stack_v2_sparse_classes_10k_train_005109 | 5,223 | permissive | [
{
"docstring": "Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable object that backs the explanation. feature_names: List of feature names. feature_types: List of feature types. name: User-defined name of explanation. selector: A dataframe whose indices correspond to explan... | 3 | stack_v2_sparse_classes_30k_train_000883 | Implement the Python class `RegressionExplanation` described below.
Class description:
Produces explanation specific to regression metrics.
Method signatures and docstrings:
- def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args:... | Implement the Python class `RegressionExplanation` described below.
Class description:
Produces explanation specific to regression metrics.
Method signatures and docstrings:
- def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None): Initializes class. Args:... | e6f38ea195aecbbd9d28c7183a83c65ada16e1ae | <|skeleton|>
class RegressionExplanation:
"""Produces explanation specific to regression metrics."""
def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None):
"""Initializes class. Args: explanation_type: Type of explanation. internal_obj: A j... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RegressionExplanation:
"""Produces explanation specific to regression metrics."""
def __init__(self, explanation_type, internal_obj, feature_names=None, feature_types=None, name=None, selector=None):
"""Initializes class. Args: explanation_type: Type of explanation. internal_obj: A jsonable objec... | the_stack_v2_python_sparse | python/interpret-core/interpret/perf/_regression.py | interpretml/interpret | train | 3,731 |
67fc9579458ee8f14dacf7fad3660eb88aa8cef7 | [
"self.rects = rects\nself.weight = []\ns = 0\nfor rect in rects:\n area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)\n s += area\n self.weight.append(s)",
"index = bisect_left(self.weight, randint(1, self.weight[-1]))\nrect = self.rects[index]\nreturn [randint(rect[0], rect[2]), randint(rect[1], r... | <|body_start_0|>
self.rects = rects
self.weight = []
s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
s += area
self.weight.append(s)
<|end_body_0|>
<|body_start_1|>
index = bisect_left(self.weight, randint(1, ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rects = rects
self.weight = []
s = 0
for rect in rec... | stack_v2_sparse_classes_10k_train_005110 | 1,307 | no_license | [
{
"docstring": ":type rects: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, rects)"
},
{
"docstring": ":rtype: List[int]",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007089 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, rects): :type rects: List[List[int]]
- def pick(self): :rtype: List[int]
<|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: ... | d156c6a13c89727f80ed6244cae40574395ecf34 | <|skeleton|>
class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
<|body_0|>
def pick(self):
""":rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, rects):
""":type rects: List[List[int]]"""
self.rects = rects
self.weight = []
s = 0
for rect in rects:
area = (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1)
s += area
self.weight.append(s)
def pic... | the_stack_v2_python_sparse | normal/497.py | longhao54/leetcode | train | 0 | |
7fbb463e4bb3a49eae4d633c246a094666ce1add | [
"self.product_code = product_code\nself.description = description\nself.market_price = market_price\nself.rental_price = rental_price",
"output_dict = {}\noutput_dict['productCode'] = self.product_code\noutput_dict['description'] = self.description\noutput_dict['marketPrice'] = self.market_price\noutput_dict['ren... | <|body_start_0|>
self.product_code = product_code
self.description = description
self.market_price = market_price
self.rental_price = rental_price
<|end_body_0|>
<|body_start_1|>
output_dict = {}
output_dict['productCode'] = self.product_code
output_dict['descrip... | Invetory class definiton | Inventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""... | stack_v2_sparse_classes_10k_train_005111 | 1,035 | no_license | [
{
"docstring": ":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_005117 | Implement the Python class `Inventory` described below.
Class description:
Invetory class definiton
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): :param product_code: :type product_code: :param description: :type description: :param market_price: :type ... | Implement the Python class `Inventory` described below.
Class description:
Invetory class definiton
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price): :param product_code: :type product_code: :param description: :type description: :param market_price: :type ... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Inventory:
"""Invetory class definiton"""
def __init__(self, product_code, description, market_price, rental_price):
""":param product_code: :type product_code: :param description: :type description: :param market_price: :type market_price: :param rental_price: :type rental_price:"""
self... | the_stack_v2_python_sparse | students/vmedina/lesson_01/inventory_management/inventory_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
5dcb144d969c42513703b600c0d2259a0b8e175e | [
"self.state_list = state_list\nself.action_list = action_list\nself.value_function = dict([(s, 0) for s in state_list])\nself.dynamics_model = dynamics_model\nself.reward_function = reward_function\nself.policy = dict([(s, 0) for s in state_list])\nself.fitted = False",
"for t in range(horizon):\n self._one_st... | <|body_start_0|>
self.state_list = state_list
self.action_list = action_list
self.value_function = dict([(s, 0) for s in state_list])
self.dynamics_model = dynamics_model
self.reward_function = reward_function
self.policy = dict([(s, 0) for s in state_list])
self.... | ValueIteration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueIteration:
def __init__(self, state_list, action_list, dynamics_model, reward_function):
"""Pass in an iterable of states, actions, dynamics_model, reward_function Positional arguments: state_list -- list of all feasible states action_list -- list of all feasible actions dynamics_mo... | stack_v2_sparse_classes_10k_train_005112 | 3,542 | no_license | [
{
"docstring": "Pass in an iterable of states, actions, dynamics_model, reward_function Positional arguments: state_list -- list of all feasible states action_list -- list of all feasible actions dynamics_model -- map from (state,action) to a list of (state, prob) tuples",
"name": "__init__",
"signature... | 5 | stack_v2_sparse_classes_30k_train_006903 | Implement the Python class `ValueIteration` described below.
Class description:
Implement the ValueIteration class.
Method signatures and docstrings:
- def __init__(self, state_list, action_list, dynamics_model, reward_function): Pass in an iterable of states, actions, dynamics_model, reward_function Positional argum... | Implement the Python class `ValueIteration` described below.
Class description:
Implement the ValueIteration class.
Method signatures and docstrings:
- def __init__(self, state_list, action_list, dynamics_model, reward_function): Pass in an iterable of states, actions, dynamics_model, reward_function Positional argum... | 468d2dab6fbf8f4135d52d5e670815008cb8d56d | <|skeleton|>
class ValueIteration:
def __init__(self, state_list, action_list, dynamics_model, reward_function):
"""Pass in an iterable of states, actions, dynamics_model, reward_function Positional arguments: state_list -- list of all feasible states action_list -- list of all feasible actions dynamics_mo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ValueIteration:
def __init__(self, state_list, action_list, dynamics_model, reward_function):
"""Pass in an iterable of states, actions, dynamics_model, reward_function Positional arguments: state_list -- list of all feasible states action_list -- list of all feasible actions dynamics_model -- map fro... | the_stack_v2_python_sparse | segmentcentroid/planner/value_iteration.py | royf/ddo | train | 2 | |
29bca8ed922d090c4488f1303dfc0fd2cc02bbfe | [
"Environment_Base.__init__(self)\nself.num_cars = [num_cars_init, num_cars_init]\nself.num_cars_max = num_cars_max\nself.done = False\nself.reward = None\nself.cars_rent = [3, 4]\nself.cars_return = [3, 4]\nself.credit_one_car = 10\nself.cost_trans = 2",
"if num >= self.num_cars_max:\n diff = 0\n val_return... | <|body_start_0|>
Environment_Base.__init__(self)
self.num_cars = [num_cars_init, num_cars_init]
self.num_cars_max = num_cars_max
self.done = False
self.reward = None
self.cars_rent = [3, 4]
self.cars_return = [3, 4]
self.credit_one_car = 10
self.co... | Rewrite the Env_base and realize the file of Car_Rental | Car_Rental | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
<|body_0|>... | stack_v2_sparse_classes_10k_train_005113 | 3,485 | no_license | [
{
"docstring": "for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations",
"name": "__init__",
"signature": "def __init__(self, num_cars_init, num_cars_max)"
},
{
"docstring": "this func for number check return the d... | 3 | stack_v2_sparse_classes_30k_train_000545 | Implement the Python class `Car_Rental` described below.
Class description:
Rewrite the Env_base and realize the file of Car_Rental
Method signatures and docstrings:
- def __init__(self, num_cars_init, num_cars_max): for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max n... | Implement the Python class `Car_Rental` described below.
Class description:
Rewrite the Env_base and realize the file of Car_Rental
Method signatures and docstrings:
- def __init__(self, num_cars_init, num_cars_max): for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max n... | 180cc4d6370953e52b02822e7f7b54030ba656fa | <|skeleton|>
class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
<|body_0|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Car_Rental:
"""Rewrite the Env_base and realize the file of Car_Rental"""
def __init__(self, num_cars_init, num_cars_max):
"""for init the env arg: num_cars_init: the num of the cars of the two locations num_cars_max: the max num of the cars in the two locations"""
Environment_Base.__init... | the_stack_v2_python_sparse | car_rental/car_rental.py | DKuan/Reinforcement_Learning2018 | train | 0 |
e8e05023d5d3a4d7d689422fe3aae4b55299e097 | [
"data = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.4.3.1-1.4.3.5', '1.4.3.6-1.4.3.9']}\nlimit = 3\ndata = limit_ip_results(data, limit)\nassert len(data['Address']) == 2\nassert len(data['Range']) == 1",
"data = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.4.3.1-1.4.3.5', '1.4.3.6-1.4.3.9']}\nlimit = 1\... | <|body_start_0|>
data = {'Address': ['1.1.1.1', '1.2.3.4'], 'Range': ['1.4.3.1-1.4.3.5', '1.4.3.6-1.4.3.9']}
limit = 3
data = limit_ip_results(data, limit)
assert len(data['Address']) == 2
assert len(data['Range']) == 1
<|end_body_0|>
<|body_start_1|>
data = {'Address': ... | TestLimitIPResults | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestLimitIPResults:
def test_limit_ip_results_high_limit(self):
"""Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so data will be taken from both lists Then - Change the lists so all addresses will show and part of the Range... | stack_v2_sparse_classes_10k_train_005114 | 44,285 | permissive | [
{
"docstring": "Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so data will be taken from both lists Then - Change the lists so all addresses will show and part of the Ranges",
"name": "test_limit_ip_results_high_limit",
"signature": "def t... | 4 | null | Implement the Python class `TestLimitIPResults` described below.
Class description:
Implement the TestLimitIPResults class.
Method signatures and docstrings:
- def test_limit_ip_results_high_limit(self): Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so ... | Implement the Python class `TestLimitIPResults` described below.
Class description:
Implement the TestLimitIPResults class.
Method signatures and docstrings:
- def test_limit_ip_results_high_limit(self): Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestLimitIPResults:
def test_limit_ip_results_high_limit(self):
"""Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so data will be taken from both lists Then - Change the lists so all addresses will show and part of the Range... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestLimitIPResults:
def test_limit_ip_results_high_limit(self):
"""Given - IPs data that contains both single IP's and ranges - Limit value When - the limit value is high enough so data will be taken from both lists Then - Change the lists so all addresses will show and part of the Ranges"""
d... | the_stack_v2_python_sparse | Packs/qualys/Integrations/Qualysv2/Qualysv2_test.py | demisto/content | train | 1,023 | |
38c102ae9d0072801b1aa3fce012f8b4ce78fad2 | [
"super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)\nself.nodes = nodes\nself.procs_per_node = procs_per_node\nself.reservation = reservation\nself.launcher = launcher\nself.launcher_args = launcher_args\nself.add_header_line(f'#BSUB -cwd {self.work_dir}')\nself.add_header_line(f'... | <|body_start_0|>
super().__init__(script_file=script_file, work_dir=work_dir, interpreter=interpreter)
self.nodes = nodes
self.procs_per_node = procs_per_node
self.reservation = reservation
self.launcher = launcher
self.launcher_args = launcher_args
self.add_heade... | Utility class to write LSF batch scripts. | LSFBatchScript | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_10k_train_005115 | 6,308 | permissive | [
{
"docstring": "Construct LSF batch script manager. Args: script_file (str): Script file. work_dir (str, optional): Working directory (default: current working directory). nodes (int, optional): Number of compute nodes (default: 1). procs_per_node (int, optional): Parallel processes per compute node (default: 1... | 3 | stack_v2_sparse_classes_30k_train_003808 | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | Implement the Python class `LSFBatchScript` described below.
Class description:
Utility class to write LSF batch scripts.
Method signatures and docstrings:
- def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=... | e8cf85eed2acbd3383892bf7cb2d88b44c194f4f | <|skeleton|>
class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LSFBatchScript:
"""Utility class to write LSF batch scripts."""
def __init__(self, script_file=None, work_dir=os.getcwd(), nodes=1, procs_per_node=1, time_limit=None, job_name=None, partition=None, account=None, reservation=None, launcher='jsrun', launcher_args=[], interpreter='/bin/bash'):
"""Co... | the_stack_v2_python_sparse | python/lbann/launcher/lsf.py | LLNL/lbann | train | 225 |
25fde73b55ae5d8b870bc3212ad0613fe0f99a8f | [
"import collections\nm = collections.defaultdict(int)\nfor num in nums:\n m[num] += 1\n if m[num] > 1:\n return num\nreturn -1",
"i = 0\nwhile i < len(nums):\n if nums[i] == i:\n i += 1\n continue\n if nums[nums[i]] == nums[i]:\n return nums[i]\n nums[nums[i]], nums[i] =... | <|body_start_0|>
import collections
m = collections.defaultdict(int)
for num in nums:
m[num] += 1
if m[num] > 1:
return num
return -1
<|end_body_0|>
<|body_start_1|>
i = 0
while i < len(nums):
if nums[i] == i:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findRepeatNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
import collections
m = coll... | stack_v2_sparse_classes_10k_train_005116 | 964 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findRepeatNumber",
"signature": "def findRepeatNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findRepeatNumber",
"signature": "def findRepeatNumber(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int
- def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int
- def findRepeatNumber(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def f... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def findRepeatNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findRepeatNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findRepeatNumber(self, nums):
""":type nums: List[int] :rtype: int"""
import collections
m = collections.defaultdict(int)
for num in nums:
m[num] += 1
if m[num] > 1:
return num
return -1
def findRepeatNumber(sel... | the_stack_v2_python_sparse | 剑指 Offer 03. 数组中重复的数字.py | yangyuxiang1996/leetcode | train | 0 | |
711f3026c3542b1c071c37ba1e6cdd34aeec1dfd | [
"assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nC = self.COEFFS[imt]\nimean = self._compute_magnitude_scaling(C, rup.mag) + self._compute_distance_scaling(C, dists.rrup, rup.mag)\nmean = np.log(10.0 ** (imean - 2.0) / g)\nmean = self._compute_site_scaling(sit... | <|body_start_0|>
assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))
C = self.COEFFS[imt]
imean = self._compute_magnitude_scaling(C, rup.mag) + self._compute_distance_scaling(C, dists.rrup, rup.mag)
mean = np.log(10.0 ** (imean - 2.0) / ... | Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classification is not known, so it is assumed that in this context "average" site conditions refer to N... | FukushimaTanakaSite1990 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FukushimaTanakaSite1990:
"""Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classification is not known, so it is assumed that i... | stack_v2_sparse_classes_10k_train_005117 | 6,513 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Scales the ground m... | 2 | stack_v2_sparse_classes_30k_train_005713 | Implement the Python class `FukushimaTanakaSite1990` described below.
Class description:
Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classificatio... | Implement the Python class `FukushimaTanakaSite1990` described below.
Class description:
Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classificatio... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class FukushimaTanakaSite1990:
"""Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classification is not known, so it is assumed that i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FukushimaTanakaSite1990:
"""Implements the Fukushima and Tanaka (1990) model correcting for site class. The authors specify that the ground motions should be raised by 40 % on soft soil sites and reduced by 40 % on rock sites. The specific site classification is not known, so it is assumed that in this contex... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/fukushima_tanaka_1990.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
5730b3d0651858fa7d349af2c34395ade286145a | [
"self.s = []\n\ndef dfs_visit(root):\n if not root:\n self.s.append('null')\n return\n self.s.append(root.val)\n dfs_visit(root.left)\n dfs_visit(root.right)\ndfs_visit(root)\nprint(self.s)\nstrs = ''\nfor i in self.s:\n strs += str(i) + ','\nreturn strs[:-1]",
"s = data.split(',')\ns... | <|body_start_0|>
self.s = []
def dfs_visit(root):
if not root:
self.s.append('null')
return
self.s.append(root.val)
dfs_visit(root.left)
dfs_visit(root.right)
dfs_visit(root)
print(self.s)
strs = ''
... | 199ms | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""199ms"""
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_ske... | stack_v2_sparse_classes_10k_train_005118 | 3,990 | 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:
199ms
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: TreeNode | Implement the Python class `Codec` described below.
Class description:
199ms
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: TreeNode
<|skeleton... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Codec:
"""199ms"""
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_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
"""199ms"""
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
self.s = []
def dfs_visit(root):
if not root:
self.s.append('null')
return
self.s.append(root.val)
... | the_stack_v2_python_sparse | SerializeAndDeserializeBinaryTree_HARD_297.py | 953250587/leetcode-python | train | 2 |
7cfb27f500ba0605e13b6e9eb6396401bb21b758 | [
"parser.add_argument('--organization', required=True, metavar='ORGANIZATION_ID', completer=completers.OrganizationCompleter, help='Organization to update Logs Router CMEK settings for.')\ngroup = parser.add_mutually_exclusive_group(required=True)\nkms_resource_args.AddKmsKeyResourceArg(group, resource='logs being p... | <|body_start_0|>
parser.add_argument('--organization', required=True, metavar='ORGANIZATION_ID', completer=completers.OrganizationCompleter, help='Organization to update Logs Router CMEK settings for.')
group = parser.add_mutually_exclusive_group(required=True)
kms_resource_args.AddKmsKeyResourc... | Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK) for the Logs Router can currentl... | Update | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK... | stack_v2_sparse_classes_10k_train_005119 | 3,721 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | null | Implement the Python class `Update` described below.
Class description:
Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it.... | Implement the Python class `Update` described below.
Class description:
Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it.... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK) for the Log... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/logging/cmek_settings/update.py | bopopescu/socialliteapp | train | 0 |
01345fa2af09cc99a1f8b447883bc3b56cf14326 | [
"try:\n return eval(expr)\nexcept (ZeroDivisionError, TypeError):\n if self.muffled:\n print('Division is not allow 0')\n return 0\n else:\n raise\nfinally:\n print('hahaha')",
"try:\n eval(expr)\nexcept (ZeroDivisionError, TypeError) as e:\n print(e)\n if self.muffled:\n... | <|body_start_0|>
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.muffled:
print('Division is not allow 0')
return 0
else:
raise
finally:
print('hahaha')
<|end_body_0|>
<|body_st... | 使用参数控制是否抛出异常 | MuffledCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_0|>
def calc01(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
return eval(expr)
... | stack_v2_sparse_classes_10k_train_005120 | 1,609 | no_license | [
{
"docstring": "计算表达式值 :param expr: :return:",
"name": "calc",
"signature": "def calc(self, expr)"
},
{
"docstring": "计算表达式值 :param expr: :return:",
"name": "calc01",
"signature": "def calc01(self, expr)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002326 | Implement the Python class `MuffledCalculator` described below.
Class description:
使用参数控制是否抛出异常
Method signatures and docstrings:
- def calc(self, expr): 计算表达式值 :param expr: :return:
- def calc01(self, expr): 计算表达式值 :param expr: :return: | Implement the Python class `MuffledCalculator` described below.
Class description:
使用参数控制是否抛出异常
Method signatures and docstrings:
- def calc(self, expr): 计算表达式值 :param expr: :return:
- def calc01(self, expr): 计算表达式值 :param expr: :return:
<|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self... | e66eda07e6b1302d8ac86f93490ec5230e50fa4e | <|skeleton|>
class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_0|>
def calc01(self, expr):
"""计算表达式值 :param expr: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MuffledCalculator:
"""使用参数控制是否抛出异常"""
def calc(self, expr):
"""计算表达式值 :param expr: :return:"""
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.muffled:
print('Division is not allow 0')
return 0
... | the_stack_v2_python_sparse | day04/exceptionTst.py | zhangshichen0/python3-study | train | 0 |
c19eee4511b5b8227560c25f2f92cebe410c278b | [
"user_db = User.get_by('token', token)\nif not user_db:\n raise ValueError('Sorry, your token is either invalid or expired.')\nreturn token",
"user_db = User.get_by('email', email)\nif not user_db:\n raise ValueError('This email is not in our database.')\nreturn email",
"user_db = User.get_by('email', ema... | <|body_start_0|>
user_db = User.get_by('token', token)
if not user_db:
raise ValueError('Sorry, your token is either invalid or expired.')
return token
<|end_body_0|>
<|body_start_1|>
user_db = User.get_by('email', email)
if not user_db:
raise ValueError(... | Defines how to create validators for user properties. For detailed description see BaseValidator | UserValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
<|body_0|>
def existing_email(cls, email):
"""Validates if given email is i... | stack_v2_sparse_classes_10k_train_005121 | 5,408 | permissive | [
{
"docstring": "Validates if given token is in datastore",
"name": "token",
"signature": "def token(cls, token)"
},
{
"docstring": "Validates if given email is in datastore",
"name": "existing_email",
"signature": "def existing_email(cls, email)"
},
{
"docstring": "Validates if g... | 4 | stack_v2_sparse_classes_30k_train_000492 | Implement the Python class `UserValidator` described below.
Class description:
Defines how to create validators for user properties. For detailed description see BaseValidator
Method signatures and docstrings:
- def token(cls, token): Validates if given token is in datastore
- def existing_email(cls, email): Validate... | Implement the Python class `UserValidator` described below.
Class description:
Defines how to create validators for user properties. For detailed description see BaseValidator
Method signatures and docstrings:
- def token(cls, token): Validates if given token is in datastore
- def existing_email(cls, email): Validate... | a82de1321abab504a0be85497587fa90d75fa62d | <|skeleton|>
class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
<|body_0|>
def existing_email(cls, email):
"""Validates if given email is i... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserValidator:
"""Defines how to create validators for user properties. For detailed description see BaseValidator"""
def token(cls, token):
"""Validates if given token is in datastore"""
user_db = User.get_by('token', token)
if not user_db:
raise ValueError('Sorry, yo... | the_stack_v2_python_sparse | main/model/user.py | jajberni/pcse_web | train | 3 |
261c83a8f57d74f0d9b26a411b057c0e78bd5861 | [
"if not nums:\n return 0\ncount = 0\nfor i in range(1, len(nums)):\n if nums[count] != nums[i]:\n count += 1\n nums[count] = nums[i]\nreturn count + 1",
"if not nums:\n return 0\nfor i in range(len(nums) - 1, 0, -1):\n if nums[i] == nums[i - 1]:\n nums.pop(i)\nreturn len(nums)"
] | <|body_start_0|>
if not nums:
return 0
count = 0
for i in range(1, len(nums)):
if nums[count] != nums[i]:
count += 1
nums[count] = nums[i]
return count + 1
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums: list) -> int:
"""双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已经全部跳过,此时i指向的值是下一个不重复的值,则count自增 并且,要将nums[i]的值赋给nums[count](即将这个不重复的值往前提,因为不需要考虑超出新长度的元素)"""
... | stack_v2_sparse_classes_10k_train_005122 | 1,659 | no_license | [
{
"docstring": "双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已经全部跳过,此时i指向的值是下一个不重复的值,则count自增 并且,要将nums[i]的值赋给nums[count](即将这个不重复的值往前提,因为不需要考虑超出新长度的元素)",
"name": "removeDuplicates",
"signature": "def removeDuplicates(se... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums: list) -> int: 双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums: list) -> int: 双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums: list) -> int:
"""双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已经全部跳过,此时i指向的值是下一个不重复的值,则count自增 并且,要将nums[i]的值赋给nums[count](即将这个不重复的值往前提,因为不需要考虑超出新长度的元素)"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def removeDuplicates(self, nums: list) -> int:
"""双指针法 1. 定义count表示数组中不重复的数字的个数,同时,count表示慢指针 2. 定义快指针i,从1开始到数组末尾 3. 开始循环: 3.1 当nums[count] == nums[i]时,i向后移动,跳过重复值 3.2 当其不相等时,说明重复值已经全部跳过,此时i指向的值是下一个不重复的值,则count自增 并且,要将nums[i]的值赋给nums[count](即将这个不重复的值往前提,因为不需要考虑超出新长度的元素)"""
if not num... | the_stack_v2_python_sparse | algorithm/leetcode/list/14-删除排序数组中的重复项.py | lxconfig/UbuntuCode_bak | train | 0 | |
4986d7562765fae465ddffef852a0071fca82fc4 | [
"apply_ipaddr, apply_port = System.get_apply_ip_and_port()\ntry:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n send_data = json.dumps(send_data)\n send_data = send_data.encode()\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.setsockopt(socket... | <|body_start_0|>
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
send_data = json.dumps(send_data)
send_data = send_data.encode()
sock.setsockopt(socket.SOL_SOCKET, ... | RequestToApply | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-3.0-only",
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_10k_train_005123 | 9,642 | permissive | [
{
"docstring": "[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ",
"name": "_request",
"signature": "def _request(cls, send_data, request=None)"
},
{
"docstring": "[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue, 異常ならFalse msg : 受信メッセージ",
"name"... | 3 | stack_v2_sparse_classes_30k_train_002092 | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | Implement the Python class `RequestToApply` described below.
Class description:
Implement the RequestToApply class.
Method signatures and docstrings:
- def _request(cls, send_data, request=None): [概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ
- def operate(cls, send_data, request=None): [概要] アプライ... | c00ea4fe1bf4b4a18d545aabeaaf1d95c7664b94 | <|skeleton|>
class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
<|body_0|>
def operate(cls, send_data, request=None):
"""[概要] アプライ君にルール関連の操作を要求する [引数] send_data : リクエスト用データ [戻り値] result : 正常ならTrue,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RequestToApply:
def _request(cls, send_data, request=None):
"""[概要] 適用君へリクエスト送信 [引数] send_data : リクエスト用データ [戻り値] recv_data : 受信データ"""
apply_ipaddr, apply_port = System.get_apply_ip_and_port()
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
... | the_stack_v2_python_sparse | oase-root/libs/webcommonlibs/common.py | exastro-suite/oase | train | 10 | |
a02ff9451ce3ea4a1b9ab2c64a1cf321b18e64bc | [
"if not cost:\n return 0\nif len(cost) <= 2:\n return min(cost)\nprv = cost[0]\ncur = cost[1]\nfor i, c in enumerate(cost[2:], 2):\n prv, cur = (cur, min(cur, prv) + c)\nreturn min(prv, cur)",
"n = len(cost)\nif n == 0:\n return 0\ndp = [0, 0]\nfor i in range(2, n + 1):\n dp[i % 2] = min(dp[(i - 1)... | <|body_start_0|>
if not cost:
return 0
if len(cost) <= 2:
return min(cost)
prv = cost[0]
cur = cost[1]
for i, c in enumerate(cost[2:], 2):
prv, cur = (cur, min(cur, prv) + c)
return min(prv, cur)
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
"""06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def minCostClimbingStairs(self, cost: List[int]) -> int:
"""07/29/2022 23:43 Time complexity: O(n) Space complexity: O(1)... | stack_v2_sparse_classes_10k_train_005124 | 2,222 | no_license | [
{
"docstring": "06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)",
"name": "minCostClimbingStairs",
"signature": "def minCostClimbingStairs(self, cost: List[int]) -> int"
},
{
"docstring": "07/29/2022 23:43 Time complexity: O(n) Space complexity: O(1)",
"name": "minCostClimbingS... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostClimbingStairs(self, cost: List[int]) -> int: 06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)
- def minCostClimbingStairs(self, cost: List[int]) -> int: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minCostClimbingStairs(self, cost: List[int]) -> int: 06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)
- def minCostClimbingStairs(self, cost: List[int]) -> int: ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
"""06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)"""
<|body_0|>
def minCostClimbingStairs(self, cost: List[int]) -> int:
"""07/29/2022 23:43 Time complexity: O(n) Space complexity: O(1)... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
"""06/20/2021 07:05 Time complexity: O(n) Space complexity: O(1)"""
if not cost:
return 0
if len(cost) <= 2:
return min(cost)
prv = cost[0]
cur = cost[1]
for i, c in enume... | the_stack_v2_python_sparse | leetcode/solved/747_Min_Cost_Climbing_Stairs/solution.py | sungminoh/algorithms | train | 0 | |
76b3de3e7be38a939337bf3c0d93bc8c0dc61b70 | [
"ami = ec2AmiInstanceConfig.ami\ninstance = ec2AmiInstanceConfig.instance\nosh = ObjectStateHolder('amazon_ec2_config')\nosh.setStringAttribute('name', ami.getName())\nosh.setStringAttribute('ami_visibility', str(ami.getVisibility()))\nosh.setStringAttribute('description', ami.description)\nosh.setStringAttribute('... | <|body_start_0|>
ami = ec2AmiInstanceConfig.ami
instance = ec2AmiInstanceConfig.instance
osh = ObjectStateHolder('amazon_ec2_config')
osh.setStringAttribute('name', ami.getName())
osh.setStringAttribute('ami_visibility', str(ami.getVisibility()))
osh.setStringAttribute('d... | Builder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
<|body_0|>
def visitEc2AmiInstanceNode(self, ec2InstanceNode):
"""@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Publi... | stack_v2_sparse_classes_10k_train_005125 | 12,496 | no_license | [
{
"docstring": "@types: ec2.Ami.Instance -> ObjectStateHolder",
"name": "visitEc2AmiInstanceConfig",
"signature": "def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig)"
},
{
"docstring": "@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Public address is not speci... | 2 | stack_v2_sparse_classes_30k_train_005670 | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig): @types: ec2.Ami.Instance -> ObjectStateHolder
- def visitEc2AmiInstanceNode(self, ec2InstanceNode): @types: ec2.Builder.E... | Implement the Python class `Builder` described below.
Class description:
Implement the Builder class.
Method signatures and docstrings:
- def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig): @types: ec2.Ami.Instance -> ObjectStateHolder
- def visitEc2AmiInstanceNode(self, ec2InstanceNode): @types: ec2.Builder.E... | 49aafa7081b861c5f6d0e1753b425e78948116d0 | <|skeleton|>
class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
<|body_0|>
def visitEc2AmiInstanceNode(self, ec2InstanceNode):
"""@types: ec2.Builder.Ec2InstanceNode -> ObjectStateHolder @raise ValueError: Publi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Builder:
def visitEc2AmiInstanceConfig(self, ec2AmiInstanceConfig):
"""@types: ec2.Ami.Instance -> ObjectStateHolder"""
ami = ec2AmiInstanceConfig.ami
instance = ec2AmiInstanceConfig.instance
osh = ObjectStateHolder('amazon_ec2_config')
osh.setStringAttribute('name', am... | the_stack_v2_python_sparse | UCMDBPython/src/ec2.py | kvt11/dd-git | train | 0 | |
2a4ce08fa1df750db7bae3280b585a4edea41da7 | [
"_id = request.form.get('id', request.args.get('id', None))\nif _id is None:\n return ({'success': False, 'message': 'missing parameter: id'}, 400)\nhysds_io = mozart_es.get_by_id(index=HYSDS_IOS_INDEX, id=_id, ignore=404)\nif hysds_io['found'] is False:\n return ({'success': False, 'message': ''}, 404)\nretu... | <|body_start_0|>
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return ({'success': False, 'message': 'missing parameter: id'}, 400)
hysds_io = mozart_es.get_by_id(index=HYSDS_IOS_INDEX, id=_id, ignore=404)
if hysds_io['found'] is False:
... | HySDSio | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HySDSio:
def get(self):
"""Gets a HySDS-IO specification by ID"""
<|body_0|>
def post(self):
"""Add a HySDS IO specification"""
<|body_1|>
def delete(self):
"""Remove HySDS IO for the given ID"""
<|body_2|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_10k_train_005126 | 13,931 | permissive | [
{
"docstring": "Gets a HySDS-IO specification by ID",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Add a HySDS IO specification",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Remove HySDS IO for the given ID",
"name": "delete",
"signa... | 3 | stack_v2_sparse_classes_30k_train_005972 | Implement the Python class `HySDSio` described below.
Class description:
Implement the HySDSio class.
Method signatures and docstrings:
- def get(self): Gets a HySDS-IO specification by ID
- def post(self): Add a HySDS IO specification
- def delete(self): Remove HySDS IO for the given ID | Implement the Python class `HySDSio` described below.
Class description:
Implement the HySDSio class.
Method signatures and docstrings:
- def get(self): Gets a HySDS-IO specification by ID
- def post(self): Add a HySDS IO specification
- def delete(self): Remove HySDS IO for the given ID
<|skeleton|>
class HySDSio:
... | c238340fafd96a9b92d92e544d0892a354c1ca32 | <|skeleton|>
class HySDSio:
def get(self):
"""Gets a HySDS-IO specification by ID"""
<|body_0|>
def post(self):
"""Add a HySDS IO specification"""
<|body_1|>
def delete(self):
"""Remove HySDS IO for the given ID"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HySDSio:
def get(self):
"""Gets a HySDS-IO specification by ID"""
_id = request.form.get('id', request.args.get('id', None))
if _id is None:
return ({'success': False, 'message': 'missing parameter: id'}, 400)
hysds_io = mozart_es.get_by_id(index=HYSDS_IOS_INDEX, id... | the_stack_v2_python_sparse | mozart/services/api_v02/specs.py | hysds/mozart | train | 1 | |
44ab080409a0baddac6e71cc84accb4bf5592c7f | [
"if root == None:\n return ''\n\ndef postorder(root):\n return postorder(root.left) + postorder(root.right) + [root.val] if root else ['None']\nreturn ','.join(map(str, postorder(root)))",
"if data == '':\n return None\ndata = data.split(',')\n\ndef helper(data):\n val = data.pop()\n if val == 'Non... | <|body_start_0|>
if root == None:
return ''
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root else ['None']
return ','.join(map(str, postorder(root)))
<|end_body_0|>
<|body_start_1|>
if data == '':
return N... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_10k_train_005127 | 4,106 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_006271 | 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:... | 56047a5058c6a20b356ab20e52eacb425ad45762 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root == None:
return ''
def postorder(root):
return postorder(root.left) + postorder(root.right) + [root.val] if root else ['None']
return ','... | the_stack_v2_python_sparse | Python/BinaryTree/297. Serialize and Deserialize Binary Tree.py | Leahxuliu/Data-Structure-And-Algorithm | train | 2 | |
3cafc44d35d98bff56c5d27a71a4cf8497bb5d83 | [
"super(MajorityVote, self).__init__(raise_error=raise_error)\nself.threshold = threshold\nself.normalizer = normalizer",
"if len(values) == 0:\n if not raise_error:\n return default\n raise ValueError('cannot pick from empty set')\nvalue, freq = values.most_common(1)[0]\nif self.threshold is not None... | <|body_start_0|>
super(MajorityVote, self).__init__(raise_error=raise_error)
self.threshold = threshold
self.normalizer = normalizer
<|end_body_0|>
<|body_start_1|>
if len(values) == 0:
if not raise_error:
return default
raise ValueError('cannot p... | Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-frequent value has to satisfy. | MajorityVote | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-freq... | stack_v2_sparse_classes_10k_train_005128 | 11,064 | permissive | [
{
"docstring": "Initialize the optional min. frequency thrshold and normalizer that will be applied to frequency values. Parameters ---------- threshold: float, default=None Additional frequency threshold for the selected value. Ignored if None. normalizer: callable, default=None Normalizer that is applied to t... | 2 | stack_v2_sparse_classes_30k_train_000150 | Implement the Python class `MajorityVote` described below.
Class description:
Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional thresh... | Implement the Python class `MajorityVote` described below.
Class description:
Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional thresh... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-freq... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MajorityVote:
"""Majority picker that select the most frequent value. This picker returns the default value (or raises an error) if the given list of values is empty or there are multiple-most frequent values. THe picker allows to define an additional threshold (min. frequency) that the most-frequent value ha... | the_stack_v2_python_sparse | openclean/function/value/picker.py | Denisfench/openclean-core | train | 0 |
a711f5aa8ac6a65c2a44d1d9750d1d017c322f0d | [
"if matrix == [] or matrix == [[]]:\n return False\nvertical = [x[0] for x in matrix]\ny = self.BS_lowerBound(vertical, target)\nif matrix[y][0] == target:\n return True\nhorizontal = matrix[y]\nx = self.BS_lowerBound(horizontal, target)\nif x >= 0 and matrix[y][x] == target:\n return True\nreturn False",
... | <|body_start_0|>
if matrix == [] or matrix == [[]]:
return False
vertical = [x[0] for x in matrix]
y = self.BS_lowerBound(vertical, target)
if matrix[y][0] == target:
return True
horizontal = matrix[y]
x = self.BS_lowerBound(horizontal, target)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def BS_lowerBound(self, vertical, target):
"""lower bound binary search algorithm"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_10k_train_005129 | 1,392 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": "lower bound binary search algorithm",
"name": "BS_lowerBound",
"signature": "def BS_lowerBound(self, vertical, t... | 2 | stack_v2_sparse_classes_30k_train_001157 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def BS_lowerBound(self, vertical, target): lower bound binary search algori... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def BS_lowerBound(self, vertical, target): lower bound binary search algori... | 54d777e11b91c5debe49c1aef723234c66a5d2cc | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def BS_lowerBound(self, vertical, target):
"""lower bound binary search algorithm"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if matrix == [] or matrix == [[]]:
return False
vertical = [x[0] for x in matrix]
y = self.BS_lowerBound(vertical, target)
if matrix[y][0] ==... | the_stack_v2_python_sparse | leetcode_solution/binary search/#74.Search_a_2D_Matrix.py | HsiangHung/Code-Challenges | train | 0 | |
7ff70d0cd8252aaf45b8bc81e38a7b559ede77e1 | [
"set_seed(1)\nds.config.set_seed(1)\nrandom.seed(1)\nif device == 'CPU':\n context.set_context(mode=context.PYNATIVE_MODE, device_target=device)\nelse:\n print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device_id))\n device_num = get_device_num()\n context.set_cont... | <|body_start_0|>
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNATIVE_MODE, device_target=device)
else:
print('initialize, rank %d / %d, device_id: %d' % (get_rank_id() + 1, get_device_num(), device... | utils for initialize and prepare dataloader | MSUtils | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_10k_train_005130 | 3,836 | permissive | [
{
"docstring": ":param device: support GPU/CPU/Ascend",
"name": "initialize",
"signature": "def initialize(device='CPU', device_id=0)"
},
{
"docstring": "prepare dataloader :param dataset: dataset :param column_names: column_names :param batch_size: batch_size :param num_workers: worker numbers ... | 2 | stack_v2_sparse_classes_30k_train_005103 | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | Implement the Python class `MSUtils` described below.
Class description:
utils for initialize and prepare dataloader
Method signatures and docstrings:
- def initialize(device='CPU', device_id=0): :param device: support GPU/CPU/Ascend
- def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_s... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
<|body_0|>
def prepare_dataloader(dataset, column_names, batch_size=None, num_workers=1, is_shuffle=False):
"""prepar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MSUtils:
"""utils for initialize and prepare dataloader"""
def initialize(device='CPU', device_id=0):
""":param device: support GPU/CPU/Ascend"""
set_seed(1)
ds.config.set_seed(1)
random.seed(1)
if device == 'CPU':
context.set_context(mode=context.PYNAT... | the_stack_v2_python_sparse | research/cv/rcnn/src/common/mindspore_utils.py | mindspore-ai/models | train | 301 |
2ffdfcad09525fc2408a45fffcdceed962ef9171 | [
"for app_region in self.app.regions.values():\n app_region.instance_max = 1\n app_region.volumes['data0'] = {'count': 1, 'size': 1}\n laika_service = app_region.services['laika']\n laika_service.volumes['/mnt/data0'] = '/mnt/data'\n laika_service.environment['DISK_PATH'] = '/mnt/data/file.txt'\nself.... | <|body_start_0|>
for app_region in self.app.regions.values():
app_region.instance_max = 1
app_region.volumes['data0'] = {'count': 1, 'size': 1}
laika_service = app_region.services['laika']
laika_service.volumes['/mnt/data0'] = '/mnt/data'
laika_service... | TestDeployPersistence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDeployPersistence:
def test_01_disk(self):
"""Deploy a service with persistent EBS volume, verify."""
<|body_0|>
def test_02_cache(self):
"""Deploy a service with ElastiCache, verify."""
<|body_1|>
def test_03_rds(self):
"""Deploy a service w... | stack_v2_sparse_classes_10k_train_005131 | 2,156 | permissive | [
{
"docstring": "Deploy a service with persistent EBS volume, verify.",
"name": "test_01_disk",
"signature": "def test_01_disk(self)"
},
{
"docstring": "Deploy a service with ElastiCache, verify.",
"name": "test_02_cache",
"signature": "def test_02_cache(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_006836 | Implement the Python class `TestDeployPersistence` described below.
Class description:
Implement the TestDeployPersistence class.
Method signatures and docstrings:
- def test_01_disk(self): Deploy a service with persistent EBS volume, verify.
- def test_02_cache(self): Deploy a service with ElastiCache, verify.
- def... | Implement the Python class `TestDeployPersistence` described below.
Class description:
Implement the TestDeployPersistence class.
Method signatures and docstrings:
- def test_01_disk(self): Deploy a service with persistent EBS volume, verify.
- def test_02_cache(self): Deploy a service with ElastiCache, verify.
- def... | 900b8ada0017f727163c5c2ae464e17d747ba0e8 | <|skeleton|>
class TestDeployPersistence:
def test_01_disk(self):
"""Deploy a service with persistent EBS volume, verify."""
<|body_0|>
def test_02_cache(self):
"""Deploy a service with ElastiCache, verify."""
<|body_1|>
def test_03_rds(self):
"""Deploy a service w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestDeployPersistence:
def test_01_disk(self):
"""Deploy a service with persistent EBS volume, verify."""
for app_region in self.app.regions.values():
app_region.instance_max = 1
app_region.volumes['data0'] = {'count': 1, 'size': 1}
laika_service = app_regio... | the_stack_v2_python_sparse | src/test_integ/test_persistence.py | tom9nguyen/spacel-provision | train | 0 | |
42e81f850e23353db4bc3ee92c002e5e4e95ec4f | [
"self.points.append(point)\na = float(2) / (self.set_size + 1)\nself.average = self.average + a * (point - self.average)\nreturn self.average",
"if self.time == 0:\n self.average = point\n return point\nelse:\n return self.add_successive_points(point)"
] | <|body_start_0|>
self.points.append(point)
a = float(2) / (self.set_size + 1)
self.average = self.average + a * (point - self.average)
return self.average
<|end_body_0|>
<|body_start_1|>
if self.time == 0:
self.average = point
return point
else:
... | Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points. | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)""... | stack_v2_sparse_classes_10k_train_005132 | 943 | no_license | [
{
"docstring": "Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)",
"name": "add_successive_points",
"signature": "def add_successive_points(self, point)"
},
{
"docstring": "Because N and t are not dependent on each other in this formula, we can let EMA_1 = price_1, then... | 2 | stack_v2_sparse_classes_30k_train_004495 | Implement the Python class `Exponential` described below.
Class description:
Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points.
Method signatures and docstrings:
- def add_successive_points(self, point): Formula: EMA_t = EM... | Implement the Python class `Exponential` described below.
Class description:
Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points.
Method signatures and docstrings:
- def add_successive_points(self, point): Formula: EMA_t = EM... | ec66a140c62a330f0166d303fbbd6adbf9cc426c | <|skeleton|>
class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Similar to the LWMA, but applies exponentially decreasing weighting factors to the data points, giving more importance to the latest data points."""
def add_successive_points(self, point):
"""Formula: EMA_t = EMA_{t-1} + a * (price_t - EMA_{t-1}) where a = 2 / (N+1)"""
sel... | the_stack_v2_python_sparse | CODE/client/averages/exponential_moving_average.py | lineker/mcgill-codejam-2012 | train | 0 |
e8fddd0613d5575bde1256ad470d7904aec19f56 | [
"self.root = path\nself.appinfo = appinfo\nself.deploy = deploy\nself.custom = custom\nself.entrypoint = entrypoint\nself.server = server\nself.artifact_to_deploy = artifact_to_deploy\nif self.deploy:\n self.notify = log.info\nelse:\n self.notify = log.status.Print",
"cleaner = fingerprinting.Cleaner()\nif ... | <|body_start_0|>
self.root = path
self.appinfo = appinfo
self.deploy = deploy
self.custom = custom
self.entrypoint = entrypoint
self.server = server
self.artifact_to_deploy = artifact_to_deploy
if self.deploy:
self.notify = log.info
els... | JavaConfigurator | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. dep... | stack_v2_sparse_classes_10k_train_005133 | 7,446 | permissive | [
{
"docstring": "Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. deploy: (bool) True if run in deployment mode. entrypoint: (str) Name of the entrypoint to generate. server: (str) Name of ... | 5 | stack_v2_sparse_classes_30k_train_006526 | Implement the Python class `JavaConfigurator` described below.
Class description:
Implement the JavaConfigurator class.
Method signatures and docstrings:
- def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom): Constructor. Args: path: (str) Root path of the source tree. appinfo: (... | Implement the Python class `JavaConfigurator` described below.
Class description:
Implement the JavaConfigurator class.
Method signatures and docstrings:
- def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom): Constructor. Args: path: (str) Root path of the source tree. appinfo: (... | 1f9b424c40a87b46656fc9f5e2e9c81895c7e614 | <|skeleton|>
class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. dep... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JavaConfigurator:
def __init__(self, path, appinfo, deploy, entrypoint, server, artifact_to_deploy, custom):
"""Constructor. Args: path: (str) Root path of the source tree. appinfo: (apphosting.api.appinfo.AppInfoExternal or None) The parsed app.yaml file for the module if it exists. deploy: (bool) Tr... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/appengine/lib/runtimes/java.py | twistedpair/google-cloud-sdk | train | 58 | |
3720adc861c07007526e67b32a721799d0488ca6 | [
"script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\ndf = pd.read_pickle('%s/%s' % (script_location, data_pickle))\nH = np.array(df['H'], dtype=float)\nalpha = np.array(df['alpha'], dtype=float)\nh = np.array(df['h'], dtype=float)\nself.interpolator = LinearNDInterpolator((h, a... | <|body_start_0|>
script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
df = pd.read_pickle('%s/%s' % (script_location, data_pickle))
H = np.array(df['H'], dtype=float)
alpha = np.array(df['alpha'], dtype=float)
h = np.array(df['h'], dtype=float)... | HurstCorrection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value ... | stack_v2_sparse_classes_10k_train_005134 | 4,597 | permissive | [
{
"docstring": "When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value of H to feed to the fractional levy motion algorithm in order to achieve a specific... | 2 | stack_v2_sparse_classes_30k_train_005398 | Implement the Python class `HurstCorrection` described below.
Class description:
Implement the HurstCorrection class.
Method signatures and docstrings:
- def __init__(self, data_pickle='hurst_correction.pl'): When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to t... | Implement the Python class `HurstCorrection` described below.
Class description:
Implement the HurstCorrection class.
Method signatures and docstrings:
- def __init__(self, data_pickle='hurst_correction.pl'): When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to t... | e94694f298909352d7e9d912625314a1e46aa5b6 | <|skeleton|>
class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HurstCorrection:
def __init__(self, data_pickle='hurst_correction.pl'):
"""When simulating fractional levy motion, the value of H passed to the algorithm does not necessarily lead to the H value one would infer from the correlation structure. This class can be used to tell you the value of H to feed t... | the_stack_v2_python_sparse | LLC_Membranes/timeseries/flm_sim_params.py | NKM-ML/LLC_Membranes | train | 0 | |
8088bc5b2311607af3c9946eb29481f6881a7730 | [
"self._ctor_args = ctor_args\nself._ctor_kwargs = ctor_kwargs\nself._init_method = init_method\nif isinstance(instance_cls, str):\n instance_cls = DeferLoad(instance_cls)\nself._instance_cls = instance_cls",
"args = []\nfor arg in self._ctor_args:\n if isinstance(arg, ClassProvider.Inject):\n arg = i... | <|body_start_0|>
self._ctor_args = ctor_args
self._ctor_kwargs = ctor_kwargs
self._init_method = init_method
if isinstance(instance_cls, str):
instance_cls = DeferLoad(instance_cls)
self._instance_cls = instance_cls
<|end_body_0|>
<|body_start_1|>
args = []
... | Provider for a particular class. | ClassProvider | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClassProvider:
"""Provider for a particular class."""
def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs):
"""Initialize the class provider."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
... | stack_v2_sparse_classes_10k_train_005135 | 4,857 | permissive | [
{
"docstring": "Initialize the class provider.",
"name": "__init__",
"signature": "def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs)"
},
{
"docstring": "Provide the object instance given a config and injector.",
"name": "provide",
"signa... | 2 | null | Implement the Python class `ClassProvider` described below.
Class description:
Provider for a particular class.
Method signatures and docstrings:
- def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs): Initialize the class provider.
- def provide(self, config: BaseSetti... | Implement the Python class `ClassProvider` described below.
Class description:
Provider for a particular class.
Method signatures and docstrings:
- def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs): Initialize the class provider.
- def provide(self, config: BaseSetti... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class ClassProvider:
"""Provider for a particular class."""
def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs):
"""Initialize the class provider."""
<|body_0|>
def provide(self, config: BaseSettings, injector: BaseInjector):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClassProvider:
"""Provider for a particular class."""
def __init__(self, instance_cls: Union[str, type], *ctor_args, init_method: str=None, **ctor_kwargs):
"""Initialize the class provider."""
self._ctor_args = ctor_args
self._ctor_kwargs = ctor_kwargs
self._init_method = ... | the_stack_v2_python_sparse | aries_cloudagent/config/provider.py | hyperledger/aries-cloudagent-python | train | 370 |
fb24979088c8898572071938c343aa0db6c7df86 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn LocationConstraintItem()",
"from .location import Location\nfrom .location import Location\nfields: Dict[str, Callable[[Any], None]] = {'resolveAvailability': lambda n: setattr(self, 'resolve_availability', n.get_bool_value())}\nsuper_... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return LocationConstraintItem()
<|end_body_0|>
<|body_start_1|>
from .location import Location
from .location import Location
fields: Dict[str, Callable[[Any], None]] = {'resolveAvailab... | LocationConstraintItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocationConstraintItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraintItem:
"""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 ... | stack_v2_sparse_classes_10k_train_005136 | 2,348 | 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: LocationConstraintItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discrimina... | 3 | null | Implement the Python class `LocationConstraintItem` described below.
Class description:
Implement the LocationConstraintItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraintItem: Creates a new instance of the appropriate class b... | Implement the Python class `LocationConstraintItem` described below.
Class description:
Implement the LocationConstraintItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraintItem: Creates a new instance of the appropriate class b... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class LocationConstraintItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraintItem:
"""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 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LocationConstraintItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> LocationConstraintItem:
"""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 Ret... | the_stack_v2_python_sparse | msgraph/generated/models/location_constraint_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
fcaee598f9b2a8f09f1c45d18f52f32a666f6275 | [
"expected_children_level_0 = ['render', 'configuration']\nfor child in expected_children_level_0:\n if len(xml_object.xpath(child)) != 1:\n raise ValueError(\"Graphical Slider Tool definition must include exactly one '{0}' tag\".format(child))\nexpected_children_level_1 = ['functions']... | <|body_start_0|>
expected_children_level_0 = ['render', 'configuration']
for child in expected_children_level_0:
if len(xml_object.xpath(child)) != 1:
raise ValueError("Graphical Slider Tool definition must include exactly one '{0}' tag".format(child))
... | GraphicalSliderToolDescriptor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphicalSliderToolDescriptor:
def definition_from_xml(cls, xml_object, system):
"""Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict"""
<|body_0|>
def definition_to_xml(self, resource_fs):
"""Return an xml element representing this de... | stack_v2_sparse_classes_10k_train_005137 | 7,776 | no_license | [
{
"docstring": "Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict",
"name": "definition_from_xml",
"signature": "def definition_from_xml(cls, xml_object, system)"
},
{
"docstring": "Return an xml element representing this definition.",
"name": "definition_to_x... | 2 | stack_v2_sparse_classes_30k_val_000327 | Implement the Python class `GraphicalSliderToolDescriptor` described below.
Class description:
Implement the GraphicalSliderToolDescriptor class.
Method signatures and docstrings:
- def definition_from_xml(cls, xml_object, system): Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict
- de... | Implement the Python class `GraphicalSliderToolDescriptor` described below.
Class description:
Implement the GraphicalSliderToolDescriptor class.
Method signatures and docstrings:
- def definition_from_xml(cls, xml_object, system): Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict
- de... | 5fa3a818c3d41bd9c3eb25122e1d376c8910269c | <|skeleton|>
class GraphicalSliderToolDescriptor:
def definition_from_xml(cls, xml_object, system):
"""Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict"""
<|body_0|>
def definition_to_xml(self, resource_fs):
"""Return an xml element representing this de... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GraphicalSliderToolDescriptor:
def definition_from_xml(cls, xml_object, system):
"""Pull out the data into dictionary. Args: xml_object: xml from file. Returns: dict"""
expected_children_level_0 = ['render', 'configuration']
for child in expected_children_level_0:
if len(xm... | the_stack_v2_python_sparse | ExtractFeatures/Data/pratik98/gst_module.py | vivekaxl/LexisNexis | train | 9 | |
8c6c7b820e394fb0f2ebbd4c3eb37090ca3d68a7 | [
"if not is_string(pattern):\n raise ValueError('Pattern argument must be a string')\nself._pattern = pattern\nself._regex = re.compile(pattern) if pattern is not None else None",
"value = super(StringPatternParser, self).parse(value)\nif not self._regex.match(value):\n raise ValueParsingError(u\"String valu... | <|body_start_0|>
if not is_string(pattern):
raise ValueError('Pattern argument must be a string')
self._pattern = pattern
self._regex = re.compile(pattern) if pattern is not None else None
<|end_body_0|>
<|body_start_1|>
value = super(StringPatternParser, self).parse(value)
... | String parser using a regular expression pattern. | StringPatternParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_005138 | 23,409 | permissive | [
{
"docstring": "Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx",
"name": "__init__",
"signature": "def __init__(self, pattern)"
},
{
"docstring": "Parse a string value using the specified regula... | 2 | null | Implement the Python class `StringPatternParser` described below.
Class description:
String parser using a regular expression pattern.
Method signatures and docstrings:
- def __init__(self, pattern): Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must c... | Implement the Python class `StringPatternParser` described below.
Class description:
String parser using a regular expression pattern.
Method signatures and docstrings:
- def __init__(self, pattern): Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must c... | 662cc7e0721d0153857c8c17a37e2a6df86f8ce6 | <|skeleton|>
class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StringPatternParser:
"""String parser using a regular expression pattern."""
def __init__(self, pattern):
"""Initialize a new instance of StringPatternParser class. :param pattern: Regular expression which string's value must conform to :type pattern: RegEx"""
if not is_string(pattern):
... | the_stack_v2_python_sparse | core/util/webpub_manifest_parser/core/parsers.py | NYPL-Simplified/circulation | train | 20 |
6d1fa7f50802de1a432993bcbb5eb82ed8122d4d | [
"self.length = length\nself.partition_number = partition_number\nself.partition_type_uuid = partition_type_uuid\nself.partition_uuid = partition_uuid\nself.start_offset = start_offset",
"if dictionary is None:\n return None\nlength = dictionary.get('length')\npartition_number = dictionary.get('partitionNumber'... | <|body_start_0|>
self.length = length
self.partition_number = partition_number
self.partition_type_uuid = partition_type_uuid
self.partition_uuid = partition_uuid
self.start_offset = start_offset
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return N... | Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partition_number (long|int): Partition number. partitio... | VolumeInfo_DiskInfo_PartitionInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_10k_train_005139 | 3,327 | permissive | [
{
"docstring": "Constructor for the VolumeInfo_DiskInfo_PartitionInfo class",
"name": "__init__",
"signature": "def __init__(self, length=None, partition_number=None, partition_type_uuid=None, partition_uuid=None, start_offset=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | null | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | Implement the Python class `VolumeInfo_DiskInfo_PartitionInfo` described below.
Class description:
Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: leng... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VolumeInfo_DiskInfo_PartitionInfo:
"""Implementation of the 'VolumeInfo_DiskInfo_PartitionInfo' model. Offset/Length here is relative to the logical range starting at 0, formed by mapping the physical ranges of the disk into a linear device. Attributes: length (long|int): Length of partition in bytes. partiti... | the_stack_v2_python_sparse | cohesity_management_sdk/models/volume_info_disk_info_partition_info.py | cohesity/management-sdk-python | train | 24 |
dd8266505d6a1a0b4ec503befb0b2c23012c70ea | [
"if kernel_initializer is None:\n kernel_initializer = functools.partial(variance_scaling_init, gain=math.sqrt(1.0 / 3), mode='fan_in', distribution='uniform')\nobservation_spec, action_spec = input_tensor_spec\nobs_encoder = EncodingNetwork(observation_spec, input_preprocessors=observation_input_processors, pre... | <|body_start_0|>
if kernel_initializer is None:
kernel_initializer = functools.partial(variance_scaling_init, gain=math.sqrt(1.0 / 3), mode='fan_in', distribution='uniform')
observation_spec, action_spec = input_tensor_spec
obs_encoder = EncodingNetwork(observation_spec, input_prepro... | Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as input and outputs an action-value tensor ... | CriticNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as ... | stack_v2_sparse_classes_10k_train_005140 | 14,681 | permissive | [
{
"docstring": "Args: input_tensor_spec: A tuple of ``TensorSpec``s ``(observation_spec, action_spec)`` representing the inputs. output_tensor_spec (TensorSpec): spec for the output observation_input_preprocessors (nested Network|nn.Module|None): a nest of input preprocessors, each of which will be applied to t... | 2 | stack_v2_sparse_classes_30k_train_006617 | Implement the Python class `CriticNetwork` described below.
Class description:
Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module ta... | Implement the Python class `CriticNetwork` described below.
Class description:
Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module ta... | b00ff2fa5e660de31020338ba340263183fbeaa4 | <|skeleton|>
class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CriticNetwork:
"""Creates an instance of ``CriticNetwork`` for estimating action-value of continuous or discrete actions. The action-value is defined as the expected return starting from the given input observation and taking the given action. This module takes observation as input and action as input and out... | the_stack_v2_python_sparse | alf/networks/critic_networks.py | HorizonRobotics/alf | train | 288 |
a7a0e54a1bf8a0e5b3f369ffedbbd455d4f42209 | [
"if fmt is None:\n fmt = self.DEFAULT_FORMAT\nif datefmt is None:\n datefmt = self.DEFAULT_DATE_FORMAT\nif colors is None:\n colors = self.DEFAULT_COLORS\nlogging.Formatter.__init__(self, datefmt=datefmt)\nself._fmt = fmt\nself._colors = {}\nself._normal = ''\nif color and check_color_support():\n self.... | <|body_start_0|>
if fmt is None:
fmt = self.DEFAULT_FORMAT
if datefmt is None:
datefmt = self.DEFAULT_DATE_FORMAT
if colors is None:
colors = self.DEFAULT_COLORS
logging.Formatter.__init__(self, datefmt=datefmt)
self._fmt = fmt
self._co... | Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems. | BaseFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_10k_train_005141 | 5,254 | permissive | [
{
"docstring": "Parameters ---------- color: Enable color support. bool, default: True fmt: Log message format. It will be applied to the attributes dict of log records. The text between ``%(color)s`` and ``%(end_color)s`` will be colored depending on the level if color support is on. str, default: None datefmt... | 2 | stack_v2_sparse_classes_30k_train_000186 | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | Implement the Python class `BaseFormatter` described below.
Class description:
Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems.
Method signatures... | 6d15dd55ca5ed6fc9fbfd31d8488ee7bab453066 | <|skeleton|>
class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseFormatter:
"""Base class for all formatters used in Tornado. Key features of this formatter are: * Color support when logging to a terminal that supports it. * Timestamps on every log line. * Robust against str/bytes encoding problems."""
def __init__(self, color=True, fmt=None, datefmt=None, colors=... | the_stack_v2_python_sparse | mridc/utils/formaters/base.py | wdika/mridc | train | 40 |
74bce0dbec2c1a92c40a962f3a099097be735c96 | [
"super().__init__()\nself.encoder = TransformerEncoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)\nself.decoder = TransformerDecoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)",
"if src.size(1) != tgt.size(1):\n raise RuntimeError('the batch number ... | <|body_start_0|>
super().__init__()
self.encoder = TransformerEncoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)
self.decoder = TransformerDecoder(input_size, d_model, nhead, dim_feedforward, num_encoder_layers, dropout)
<|end_body_0|>
<|body_start_1|>
if ... | A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural In... | Transformer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is... | stack_v2_sparse_classes_10k_train_005142 | 20,460 | permissive | [
{
"docstring": "Initialize the Transformer Model. Parameters ---------- input_size : int, optional dimension of embeddings. If different from d_model, then a linear layer is added to project from input_size to d_model. d_model : int, optional the number of expected features in the encoder/decoder inputs (defaul... | 2 | stack_v2_sparse_classes_30k_train_003859 | Implement the Python class `Transformer` described below.
Class description:
A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, a... | Implement the Python class `Transformer` described below.
Class description:
A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, a... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Transformer:
"""A Transformer model User is able to modify the attributes as needed. The architechture is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need... | the_stack_v2_python_sparse | flambe/nn/transformer.py | cle-ros/flambe | train | 1 |
9faf15f211e4b8f520e45e2b4ed51621461bd23e | [
"properties = {'env_vars': {}, 'inputs': [], 'outputs': []}\nreader = self._get_reader(filepath)\nparser = self._get_parser(reader.language)\nif not parser:\n return properties\nfor chunk in reader.read_next_code_chunk():\n if chunk:\n for line in chunk:\n matches = parser.parse_environment_... | <|body_start_0|>
properties = {'env_vars': {}, 'inputs': [], 'outputs': []}
reader = self._get_reader(filepath)
parser = self._get_parser(reader.language)
if not parser:
return properties
for chunk in reader.read_next_code_chunk():
if chunk:
... | ContentParser | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-SA-4.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContentParser:
def parse(self, filepath: str) -> dict:
"""Returns a model dictionary of all the regex matches for each key in the regex dictionary"""
<|body_0|>
def _validate_file(self, filepath: str):
"""Validate file exists and is file (e.g. not a directory)"""
... | stack_v2_sparse_classes_10k_train_005143 | 7,437 | permissive | [
{
"docstring": "Returns a model dictionary of all the regex matches for each key in the regex dictionary",
"name": "parse",
"signature": "def parse(self, filepath: str) -> dict"
},
{
"docstring": "Validate file exists and is file (e.g. not a directory)",
"name": "_validate_file",
"signat... | 4 | stack_v2_sparse_classes_30k_train_003686 | Implement the Python class `ContentParser` described below.
Class description:
Implement the ContentParser class.
Method signatures and docstrings:
- def parse(self, filepath: str) -> dict: Returns a model dictionary of all the regex matches for each key in the regex dictionary
- def _validate_file(self, filepath: st... | Implement the Python class `ContentParser` described below.
Class description:
Implement the ContentParser class.
Method signatures and docstrings:
- def parse(self, filepath: str) -> dict: Returns a model dictionary of all the regex matches for each key in the regex dictionary
- def _validate_file(self, filepath: st... | 3c27ada25a27b719529e88268bed38d135e40805 | <|skeleton|>
class ContentParser:
def parse(self, filepath: str) -> dict:
"""Returns a model dictionary of all the regex matches for each key in the regex dictionary"""
<|body_0|>
def _validate_file(self, filepath: str):
"""Validate file exists and is file (e.g. not a directory)"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ContentParser:
def parse(self, filepath: str) -> dict:
"""Returns a model dictionary of all the regex matches for each key in the regex dictionary"""
properties = {'env_vars': {}, 'inputs': [], 'outputs': []}
reader = self._get_reader(filepath)
parser = self._get_parser(reader.... | the_stack_v2_python_sparse | elyra/contents/parser.py | elyra-ai/elyra | train | 1,707 | |
ac92d1a0eb628e22f9472b7215529fa745a83ebd | [
"if config.memoryProfile:\n config.memoryProfile.sample()\nif config.hotshotProfile:\n import hotshot\n config.hotshotProfile = hotshot.Profile(config.hotshotProfile)\nserver.Site.startFactory(self)",
"server.Site.stopFactory(self)\nif config.hotshotProfile:\n config.hotshotProfile.close()"
] | <|body_start_0|>
if config.memoryProfile:
config.memoryProfile.sample()
if config.hotshotProfile:
import hotshot
config.hotshotProfile = hotshot.Profile(config.hotshotProfile)
server.Site.startFactory(self)
<|end_body_0|>
<|body_start_1|>
server.Site.... | Moin site | MoinSite | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MoinSite:
"""Moin site"""
def startFactory(self):
"""Setup before starting"""
<|body_0|>
def stopFactory(self):
"""Cleaup before stoping"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if config.memoryProfile:
config.memoryProfile.sa... | stack_v2_sparse_classes_10k_train_005144 | 8,777 | no_license | [
{
"docstring": "Setup before starting",
"name": "startFactory",
"signature": "def startFactory(self)"
},
{
"docstring": "Cleaup before stoping",
"name": "stopFactory",
"signature": "def stopFactory(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002499 | Implement the Python class `MoinSite` described below.
Class description:
Moin site
Method signatures and docstrings:
- def startFactory(self): Setup before starting
- def stopFactory(self): Cleaup before stoping | Implement the Python class `MoinSite` described below.
Class description:
Moin site
Method signatures and docstrings:
- def startFactory(self): Setup before starting
- def stopFactory(self): Cleaup before stoping
<|skeleton|>
class MoinSite:
"""Moin site"""
def startFactory(self):
"""Setup before st... | a17b987c5adaa13befb0fd74ac400c8edbe62ef5 | <|skeleton|>
class MoinSite:
"""Moin site"""
def startFactory(self):
"""Setup before starting"""
<|body_0|>
def stopFactory(self):
"""Cleaup before stoping"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MoinSite:
"""Moin site"""
def startFactory(self):
"""Setup before starting"""
if config.memoryProfile:
config.memoryProfile.sample()
if config.hotshotProfile:
import hotshot
config.hotshotProfile = hotshot.Profile(config.hotshotProfile)
... | the_stack_v2_python_sparse | moin/lib/python2.4/site-packages/MoinMoin/server/twistedmoin.py | imosts/flume | train | 0 |
0f9284727d6310cc3fb65f3b52358a8b4f3d248a | [
"super().__init__(init_cfg)\nself.channel_wise_adaptation = nn.Linear(in_channels, in_channels)\nself.spatial_wise_adaptation = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1)\nself.adaptation_layers = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)\nself.student_non_local = NonLocal2dMa... | <|body_start_0|>
super().__init__(init_cfg)
self.channel_wise_adaptation = nn.Linear(in_channels, in_channels)
self.spatial_wise_adaptation = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1)
self.adaptation_layers = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=... | Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the input feature map. reduction (int): Channel reduction ratio. Defaults to 2. conv_cfg (di... | FBKDStudentConnector | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FBKDStudentConnector:
"""Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the input feature map. reduction (int): Chan... | stack_v2_sparse_classes_10k_train_005145 | 12,309 | permissive | [
{
"docstring": "Inits the FBKDStuConnector.",
"name": "__init__",
"signature": "def __init__(self, in_channels: int, reduction: int=2, conv_cfg: Dict=dict(type='Conv2d'), norm_cfg: Dict=dict(type='BN'), mode: str='dot_product', sub_sample: bool=False, maxpool_stride: int=2, zeros_init: bool=True, spatia... | 2 | null | Implement the Python class `FBKDStudentConnector` described below.
Class description:
Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the i... | Implement the Python class `FBKDStudentConnector` described below.
Class description:
Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the i... | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | <|skeleton|>
class FBKDStudentConnector:
"""Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the input feature map. reduction (int): Chan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FBKDStudentConnector:
"""Improve Object Detection with Feature-based Knowledge Distillation: Towards Accurate and Efficient Detectors, ICLR2021. https://openreview.net/pdf?id=uKhGRvM8QNH. Student connector for FBKD. Args: in_channels (int): Channels of the input feature map. reduction (int): Channel reduction... | the_stack_v2_python_sparse | cv/distiller/CWD/pytorch/mmrazor/mmrazor/models/architectures/connectors/fbkd_connector.py | Deep-Spark/DeepSparkHub | train | 7 |
05d51fd3daaca91089765c54e62bad2b07146d57 | [
"self.wordHash = {}\nfor i in range(len(words)):\n if words[i] not in self.wordHash:\n self.wordHash[words[i]] = [i]\n else:\n self.wordHash[words[i]].append(i)",
"word1Index = self.wordHash[word1]\nword2Index = self.wordHash[word2]\nres = float('inf')\ni = j = 0\nm, n = (len(word1Index), len(... | <|body_start_0|>
self.wordHash = {}
for i in range(len(words)):
if words[i] not in self.wordHash:
self.wordHash[words[i]] = [i]
else:
self.wordHash[words[i]].append(i)
<|end_body_0|>
<|body_start_1|>
word1Index = self.wordHash[word1]
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.wordHash = {}
for i in r... | stack_v2_sparse_classes_10k_train_005146 | 1,968 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002812 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 604efd2c53c369fb262f42f7f7f31997ea4d029b | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.wordHash = {}
for i in range(len(words)):
if words[i] not in self.wordHash:
self.wordHash[words[i]] = [i]
else:
self.wordHash[words[i]].append(i)
def ... | the_stack_v2_python_sparse | 244_Shortest_Word_Distance_II.py | fxy1018/Leetcode | train | 1 | |
33fd58517873b1c9b2a7c957a36f7401a18e1b93 | [
"self.hass = hass\nself.devices = devices\nself.bt_device_id = bt_device_id\n\ndef callback(bt_addr, _, packet, additional_info):\n \"\"\"Handle new packets.\"\"\"\n self.process_packet(additional_info['namespace'], additional_info['instance'], packet.temperature)\ndevice_filters = [EddystoneFilter(d.namespac... | <|body_start_0|>
self.hass = hass
self.devices = devices
self.bt_device_id = bt_device_id
def callback(bt_addr, _, packet, additional_info):
"""Handle new packets."""
self.process_packet(additional_info['namespace'], additional_info['instance'], packet.temperatur... | Continuously scan for BLE advertisements. | Monitor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monitor:
"""Continuously scan for BLE advertisements."""
def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None:
"""Construct interface object."""
<|body_0|>
def start(self) -> None:
"""Continuously scan for BLE advertise... | stack_v2_sparse_classes_10k_train_005147 | 6,045 | permissive | [
{
"docstring": "Construct interface object.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None"
},
{
"docstring": "Continuously scan for BLE advertisements.",
"name": "start",
"signature": "def start(self) ... | 4 | stack_v2_sparse_classes_30k_train_000112 | Implement the Python class `Monitor` described below.
Class description:
Continuously scan for BLE advertisements.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: Construct interface object.
- def start(self) -> None: Continuously s... | Implement the Python class `Monitor` described below.
Class description:
Continuously scan for BLE advertisements.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None: Construct interface object.
- def start(self) -> None: Continuously s... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Monitor:
"""Continuously scan for BLE advertisements."""
def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None:
"""Construct interface object."""
<|body_0|>
def start(self) -> None:
"""Continuously scan for BLE advertise... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Monitor:
"""Continuously scan for BLE advertisements."""
def __init__(self, hass: HomeAssistant, devices: list[EddystoneTemp], bt_device_id: int) -> None:
"""Construct interface object."""
self.hass = hass
self.devices = devices
self.bt_device_id = bt_device_id
de... | the_stack_v2_python_sparse | homeassistant/components/eddystone_temperature/sensor.py | home-assistant/core | train | 35,501 |
1914a53659bf5260d1c9d60f099bf00f9bea775c | [
"result = []\nfor i in range(n):\n result.append(nums[i])\n result.append(nums[n + i])\nreturn result",
"length = 2 * n\ncount = 0\npointer = 0\nprev_index, prev_val = (1, nums[1])\nnew_index, new_val = (0, 0)\nwhile count < length - 2:\n if prev_index < n:\n new_index = prev_index * 2\n else:\... | <|body_start_0|>
result = []
for i in range(n):
result.append(nums[i])
result.append(nums[n + i])
return result
<|end_body_0|>
<|body_start_1|>
length = 2 * n
count = 0
pointer = 0
prev_index, prev_val = (1, nums[1])
new_index, new... | O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array."""
def shuffle(self, nums, n):
""":type nums: List[int] :type n: int ... | stack_v2_sparse_classes_10k_train_005148 | 3,791 | no_license | [
{
"docstring": ":type nums: List[int] :type n: int :rtype: List[int]",
"name": "shuffle",
"signature": "def shuffle(self, nums, n)"
},
{
"docstring": ":type nums: List[int] :type n: int :rtype: List[int]",
"name": "shuffle",
"signature": "def shuffle(self, nums, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006712 | Implement the Python class `Solution` described below.
Class description:
O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array.
Method signatures and docstrings:
- def sh... | Implement the Python class `Solution` described below.
Class description:
O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array.
Method signatures and docstrings:
- def sh... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array."""
def shuffle(self, nums, n):
""":type nums: List[int] :type n: int ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""O(n) time, O(n) space Runtime: 48 ms, faster than 81.20% of Python online submissions for Shuffle the Array. Memory Usage: 12.8 MB, less than 100.00% of Python online submissions for Shuffle the Array."""
def shuffle(self, nums, n):
""":type nums: List[int] :type n: int :rtype: List[... | the_stack_v2_python_sparse | 1470-shuffle_the_array.py | stevestar888/leetcode-problems | train | 2 |
6a1c82f57b7816e95e6eb168d95d180981a42487 | [
"dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, 'Error')\ndialog.format_secondary_text(self.messages(list_error))\ndialog.run()\ndialog.destroy()",
"text = 'Ingrese:'\nif list_error[0] == 1:\n text += '\\n - Function.'\nif list_error[1] == 1:\n text += '\\n - GFunction.'\nif l... | <|body_start_0|>
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, 'Error')
dialog.format_secondary_text(self.messages(list_error))
dialog.run()
dialog.destroy()
<|end_body_0|>
<|body_start_1|>
text = 'Ingrese:'
if list_error[0] == 1:
... | Errors | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Errors:
def non_lineal_errors(self, list_error):
"""list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Superior list_error[6]: Tolerance"""
<|body_0|>
def messages(self, list_error):
... | stack_v2_sparse_classes_10k_train_005149 | 1,520 | permissive | [
{
"docstring": "list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Superior list_error[6]: Tolerance",
"name": "non_lineal_errors",
"signature": "def non_lineal_errors(self, list_error)"
},
{
"docstring": "li... | 2 | stack_v2_sparse_classes_30k_train_001209 | Implement the Python class `Errors` described below.
Class description:
Implement the Errors class.
Method signatures and docstrings:
- def non_lineal_errors(self, list_error): list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Su... | Implement the Python class `Errors` described below.
Class description:
Implement the Errors class.
Method signatures and docstrings:
- def non_lineal_errors(self, list_error): list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Su... | d6c4eb3de51c627c2489c2289738ec567cfa5cc9 | <|skeleton|>
class Errors:
def non_lineal_errors(self, list_error):
"""list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Superior list_error[6]: Tolerance"""
<|body_0|>
def messages(self, list_error):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Errors:
def non_lineal_errors(self, list_error):
"""list_error[0]: Function list_error[1]: GFunction list_error[2]: Iterations list_error[3]: Increments list_error[4]: Initial list_error[5]: Superior list_error[6]: Tolerance"""
dialog = Gtk.MessageDialog(None, 0, Gtk.MessageType.INFO, Gtk.Butt... | the_stack_v2_python_sparse | UI/NonLineal/Messages/errors.py | tdnavarrom/Numerical-Analytics-App | train | 0 | |
e71cfa4eb58e07d16d27a714b41879b1c0d02cf6 | [
"fast = self.helper(self.helper(n))\nslow = self.helper(n)\nwhile slow != fast:\n fast = self.helper(self.helper(fast))\n slow = self.helper(slow)\nreturn slow == 1",
"res = 0\nwhile n:\n res += (n % 10) ** 2\n n //= 10\nreturn res"
] | <|body_start_0|>
fast = self.helper(self.helper(n))
slow = self.helper(n)
while slow != fast:
fast = self.helper(self.helper(fast))
slow = self.helper(slow)
return slow == 1
<|end_body_0|>
<|body_start_1|>
res = 0
while n:
res += (n % ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
<|body_0|>
def helper(self, n):
"""Args: n: int Return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
fast = self.helper(self.helper(n))
slow = self.helper(n)
whil... | stack_v2_sparse_classes_10k_train_005150 | 1,351 | no_license | [
{
"docstring": "Args: n: int Return: bool",
"name": "isHappy",
"signature": "def isHappy(self, n)"
},
{
"docstring": "Args: n: int Return: int",
"name": "helper",
"signature": "def helper(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005087 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): Args: n: int Return: bool
- def helper(self, n): Args: n: int Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): Args: n: int Return: bool
- def helper(self, n): Args: n: int Return: int
<|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int R... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
<|body_0|>
def helper(self, n):
"""Args: n: int Return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
fast = self.helper(self.helper(n))
slow = self.helper(n)
while slow != fast:
fast = self.helper(self.helper(fast))
slow = self.helper(slow)
return slow == 1
def helper(self, n):... | the_stack_v2_python_sparse | code/202. 快乐数.py | AiZhanghan/Leetcode | train | 0 | |
d5df93cc370d1ad9635344abb49ef97ef334ac73 | [
"form = SponsorForm(self.request.form, config=self.config)\nif form.validate():\n f = form.data\n f['logo'] = f['image']\n del f['image']\n self.barcamp.sponsors.append(f)\n self.barcamp.put()\n self.flash('Neuen Sponsor angelegt', category='info')\nelse:\n self.flash('Leider enthielt das Formu... | <|body_start_0|>
form = SponsorForm(self.request.form, config=self.config)
if form.validate():
f = form.data
f['logo'] = f['image']
del f['image']
self.barcamp.sponsors.append(f)
self.barcamp.put()
self.flash('Neuen Sponsor angelegt... | view for adding and deleting sponsors | BarcampSponsors | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BarcampSponsors:
"""view for adding and deleting sponsors"""
def post(self, slug=None):
"""just add the sponsor and reload the page"""
<|body_0|>
def delete(self, slug=None):
"""delete a sponsor again and give the index via idx param"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k_train_005151 | 2,903 | permissive | [
{
"docstring": "just add the sponsor and reload the page",
"name": "post",
"signature": "def post(self, slug=None)"
},
{
"docstring": "delete a sponsor again and give the index via idx param",
"name": "delete",
"signature": "def delete(self, slug=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006750 | Implement the Python class `BarcampSponsors` described below.
Class description:
view for adding and deleting sponsors
Method signatures and docstrings:
- def post(self, slug=None): just add the sponsor and reload the page
- def delete(self, slug=None): delete a sponsor again and give the index via idx param | Implement the Python class `BarcampSponsors` described below.
Class description:
view for adding and deleting sponsors
Method signatures and docstrings:
- def post(self, slug=None): just add the sponsor and reload the page
- def delete(self, slug=None): delete a sponsor again and give the index via idx param
<|skele... | 9b45664e46c451b2cbe00bb55583b043e769083d | <|skeleton|>
class BarcampSponsors:
"""view for adding and deleting sponsors"""
def post(self, slug=None):
"""just add the sponsor and reload the page"""
<|body_0|>
def delete(self, slug=None):
"""delete a sponsor again and give the index via idx param"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BarcampSponsors:
"""view for adding and deleting sponsors"""
def post(self, slug=None):
"""just add the sponsor and reload the page"""
form = SponsorForm(self.request.form, config=self.config)
if form.validate():
f = form.data
f['logo'] = f['image']
... | the_stack_v2_python_sparse | camper/barcamps/index.py | comlounge/camper | train | 14 |
5e6985314d55561cfb1a6055d8f223f3fd1e149a | [
"super(DataQ_DI145, self).__init__()\nself.comm_port = comm_port\nself.baud_rate = baud_rate\nself.stop_thread = True\ntry:\n self.scan()\n self.sts()\nexcept:\n self.serDataq = serial.Serial(comm_port, baud_rate)\n self.serDataq.write(b'S0\\r')\n self.serDataq.write(b'C3')",
"self.stop_thread = Fa... | <|body_start_0|>
super(DataQ_DI145, self).__init__()
self.comm_port = comm_port
self.baud_rate = baud_rate
self.stop_thread = True
try:
self.scan()
self.sts()
except:
self.serDataq = serial.Serial(comm_port, baud_rate)
self.... | DataQ_DI145 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataQ_DI145:
def __init__(self, comm_port='COM4', baud_rate=4800):
"""Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication port of ADC device (default: COM4 on 17021058 Machine) baud_rate - baud rate of the device (default: ... | stack_v2_sparse_classes_10k_train_005152 | 3,869 | no_license | [
{
"docstring": "Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication port of ADC device (default: COM4 on 17021058 Machine) baud_rate - baud rate of the device (default: 4800 for DI145) C1 - Slope coefficient of counts vs Volts (default: 0.0003 for... | 4 | stack_v2_sparse_classes_30k_test_000019 | Implement the Python class `DataQ_DI145` described below.
Class description:
Implement the DataQ_DI145 class.
Method signatures and docstrings:
- def __init__(self, comm_port='COM4', baud_rate=4800): Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication p... | Implement the Python class `DataQ_DI145` described below.
Class description:
Implement the DataQ_DI145 class.
Method signatures and docstrings:
- def __init__(self, comm_port='COM4', baud_rate=4800): Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication p... | eccd3b5a68173ee4f78a0182f9f0317fede84e81 | <|skeleton|>
class DataQ_DI145:
def __init__(self, comm_port='COM4', baud_rate=4800):
"""Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication port of ADC device (default: COM4 on 17021058 Machine) baud_rate - baud rate of the device (default: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataQ_DI145:
def __init__(self, comm_port='COM4', baud_rate=4800):
"""Initialize instance variable defaults for the DataQ_DI145 class Variable Descriptions: comm_port - USB communication port of ADC device (default: COM4 on 17021058 Machine) baud_rate - baud rate of the device (default: 4800 for DI145... | the_stack_v2_python_sparse | ADC.py | jbaviation/humidity_cart | train | 0 | |
378c845527ed1579e91c7197270a543a223c26a0 | [
"data = np.ones((1, 16, 16), dtype=np.float32)\ndata[:, 7, 7] = 0.0\nself.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', 'equalarea', attributes=ATTRIBUTES)\nself.spot_cube = create_spot_cube()",
"plugin = DayNightMask()\nresult = plugin._create_daynight_mask(self.cube)\nself.assertIsInstanc... | <|body_start_0|>
data = np.ones((1, 16, 16), dtype=np.float32)
data[:, 7, 7] = 0.0
self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', 'equalarea', attributes=ATTRIBUTES)
self.spot_cube = create_spot_cube()
<|end_body_0|>
<|body_start_1|>
plugin = DayNightM... | Test string representation | Test__create_daynight_mask | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__create_daynight_mask:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
<|body_0|>
def test_basic_daynight_mask(self):
"""Test this creates a blank mask cube for gridded data"""
<|body_1|>
def test_basic_dayni... | stack_v2_sparse_classes_10k_train_005153 | 18,065 | permissive | [
{
"docstring": "Set up the cube for testing.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test this creates a blank mask cube for gridded data",
"name": "test_basic_daynight_mask",
"signature": "def test_basic_daynight_mask(self)"
},
{
"docstring": "Test t... | 3 | null | Implement the Python class `Test__create_daynight_mask` described below.
Class description:
Test string representation
Method signatures and docstrings:
- def setUp(self): Set up the cube for testing.
- def test_basic_daynight_mask(self): Test this creates a blank mask cube for gridded data
- def test_basic_daynight_... | Implement the Python class `Test__create_daynight_mask` described below.
Class description:
Test string representation
Method signatures and docstrings:
- def setUp(self): Set up the cube for testing.
- def test_basic_daynight_mask(self): Test this creates a blank mask cube for gridded data
- def test_basic_daynight_... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__create_daynight_mask:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
<|body_0|>
def test_basic_daynight_mask(self):
"""Test this creates a blank mask cube for gridded data"""
<|body_1|>
def test_basic_dayni... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test__create_daynight_mask:
"""Test string representation"""
def setUp(self):
"""Set up the cube for testing."""
data = np.ones((1, 16, 16), dtype=np.float32)
data[:, 7, 7] = 0.0
self.cube = set_up_variable_cube(data, 'precipitation_amount', 'kg m^-2', 'equalarea', attribu... | the_stack_v2_python_sparse | improver_tests/utilities/solar/test_DayNightMask.py | metoppv/improver | train | 101 |
de8e0ba92c1c3349519a69f6900044727f35e11c | [
"command = command.split(' ')\nprocess = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ntry:\n output, errors = process.communicate(timeout=8)\n output = output.split('\\n')\n process.terminate()\nexcept subprocess.TimeoutExpired:\n process.kill()\n ... | <|body_start_0|>
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
output, errors = process.communicate(timeout=8)
output = output.split('\n')
process.terminate()
... | Commands that evaluate commands.. | Evaluation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_10k_train_005154 | 2,006 | permissive | [
{
"docstring": "Execute a system command. Bot owner only.",
"name": "sh",
"signature": "async def sh(self, ctx, *, command)"
},
{
"docstring": "Evaluate a Python expression. Bot owner only.",
"name": "_eval",
"signature": "async def _eval(self, ctx, *, expression)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006193 | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only. | Implement the Python class `Evaluation` described below.
Class description:
Commands that evaluate commands..
Method signatures and docstrings:
- async def sh(self, ctx, *, command): Execute a system command. Bot owner only.
- async def _eval(self, ctx, *, expression): Evaluate a Python expression. Bot owner only.
<... | 3a456ad06814181d13d4aabefc151756c55444f4 | <|skeleton|>
class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
<|body_0|>
async def _eval(self, ctx, *, expression):
"""Evaluate a Python expression. Bot owner only."""
<|body_1|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Evaluation:
"""Commands that evaluate commands.."""
async def sh(self, ctx, *, command):
"""Execute a system command. Bot owner only."""
command = command.split(' ')
process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | the_stack_v2_python_sparse | cogs/eval.py | sokcheng/Kitsuchan-NG | train | 1 |
d4d7d6219289c858ddda8c518c329c01eb9a2a22 | [
"BaseWorkerThread.__init__(self)\nself.forbiddenStatus = ['aborted', 'aborted-completed', 'force-complete', 'completed']\nself.queue = queue\nself.config = config\nself.reqmgr2Svc = ReqMgr(self.config.General.ReqMgr2ServiceURL)\nmyThread = threading.currentThread()\ndaoFactory = DAOFactory(package='WMCore.WMBS', lo... | <|body_start_0|>
BaseWorkerThread.__init__(self)
self.forbiddenStatus = ['aborted', 'aborted-completed', 'force-complete', 'completed']
self.queue = queue
self.config = config
self.reqmgr2Svc = ReqMgr(self.config.General.ReqMgr2ServiceURL)
myThread = threading.currentThre... | Cleans expired items, updates element status. | WorkQueueManagerCleaner | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at o... | stack_v2_sparse_classes_10k_train_005155 | 2,649 | permissive | [
{
"docstring": "Initialise class members",
"name": "__init__",
"signature": "def __init__(self, queue, config)"
},
{
"docstring": "Called at startup - introduce random delay to avoid workers all starting at once",
"name": "setup",
"signature": "def setup(self, parameters)"
},
{
"... | 3 | null | Implement the Python class `WorkQueueManagerCleaner` described below.
Class description:
Cleans expired items, updates element status.
Method signatures and docstrings:
- def __init__(self, queue, config): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid work... | Implement the Python class `WorkQueueManagerCleaner` described below.
Class description:
Cleans expired items, updates element status.
Method signatures and docstrings:
- def __init__(self, queue, config): Initialise class members
- def setup(self, parameters): Called at startup - introduce random delay to avoid work... | de110ccf6fc63ef5589b4e871ef4d51d5bce7a25 | <|skeleton|>
class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
<|body_0|>
def setup(self, parameters):
"""Called at startup - introduce random delay to avoid workers all starting at o... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkQueueManagerCleaner:
"""Cleans expired items, updates element status."""
def __init__(self, queue, config):
"""Initialise class members"""
BaseWorkerThread.__init__(self)
self.forbiddenStatus = ['aborted', 'aborted-completed', 'force-complete', 'completed']
self.queue ... | the_stack_v2_python_sparse | src/python/WMComponent/WorkQueueManager/WorkQueueManagerCleaner.py | vkuznet/WMCore | train | 0 |
cedc972b0656600a70e7c021cb81bbd44f991220 | [
"hang = len(M)\nlie = len(M[0])\nfor i in range(hang):\n for j in range(lie):\n pass",
"dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]\nheight = len(M)\nwidth = len(M[0])\nres = []\nfor i in range(height):\n cache = []\n for j in range(width):\n sum = M[i][j]\... | <|body_start_0|>
hang = len(M)
lie = len(M[0])
for i in range(hang):
for j in range(lie):
pass
<|end_body_0|>
<|body_start_1|>
dirs = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
height = len(M)
width = len(M[0])
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
<|body_0|>
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
hang = len(M)
lie = len(M[0])
... | stack_v2_sparse_classes_10k_train_005156 | 2,234 | permissive | [
{
"docstring": "暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:",
"name": "imageSmoother",
"signature": "def imageSmoother(self, M)"
},
{
"docstring": "卷积神经网络里的平均池 :param M: :return:",
"name": "imageSmoother2",
"signature": "def imageSmoother2(self, M)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006885 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def imageSmoother(self, M): 暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:
- def imageSmoother2(self, M): 卷积神经网络里的平均池 :param M: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def imageSmoother(self, M): 暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:
- def imageSmoother2(self, M): 卷积神经网络里的平均池 :param M: :return:
<|skeleton|>
class Solution:
def imageSmo... | 41f4b8b557cf15cbd602f187f6550184b3a108ec | <|skeleton|>
class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
<|body_0|>
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def imageSmoother(self, M):
"""暴力法看起来可以求解的样子 但比较麻烦。。 :param M: :return:"""
hang = len(M)
lie = len(M[0])
for i in range(hang):
for j in range(lie):
pass
def imageSmoother2(self, M):
"""卷积神经网络里的平均池 :param M: :return:"""
... | the_stack_v2_python_sparse | leetcode/661. 图片平滑器.py | zhongmb/suanfa | train | 0 | |
f6276073b6b60a7e1cbd0a64163932be07232dc2 | [
"def mps(root):\n if not root:\n return (-float('inf'), -float('inf'))\n ll, l = mps(root.left)\n rr, r = mps(root.right)\n connected = root.val + max(0, l, r)\n unconnected = max(ll, rr, l, r, l + r + root.val)\n return (unconnected, connected)\nreturn max(mps(root))",
"m = -float('inf')... | <|body_start_0|>
def mps(root):
if not root:
return (-float('inf'), -float('inf'))
ll, l = mps(root.left)
rr, r = mps(root.right)
connected = root.val + max(0, l, r)
unconnected = max(ll, rr, l, r, l + r + root.val)
return (... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
<|body_0|>
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""Feb 19, 2023 15:03"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def mps(root):
if not root:
... | stack_v2_sparse_classes_10k_train_005157 | 2,524 | no_license | [
{
"docstring": "Aug 16, 2018 06:35",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root)"
},
{
"docstring": "Feb 19, 2023 15:03",
"name": "maxPathSum",
"signature": "def maxPathSum(self, root: Optional[TreeNode]) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Aug 16, 2018 06:35
- def maxPathSum(self, root: Optional[TreeNode]) -> int: Feb 19, 2023 15:03 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxPathSum(self, root): Aug 16, 2018 06:35
- def maxPathSum(self, root: Optional[TreeNode]) -> int: Feb 19, 2023 15:03
<|skeleton|>
class Solution:
def maxPathSum(self,... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
<|body_0|>
def maxPathSum(self, root: Optional[TreeNode]) -> int:
"""Feb 19, 2023 15:03"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxPathSum(self, root):
"""Aug 16, 2018 06:35"""
def mps(root):
if not root:
return (-float('inf'), -float('inf'))
ll, l = mps(root.left)
rr, r = mps(root.right)
connected = root.val + max(0, l, r)
unconn... | the_stack_v2_python_sparse | leetcode/solved/124_Binary_Tree_Maximum_Path_Sum/solution.py | sungminoh/algorithms | train | 0 | |
33ec09ba13f6846d5027bb4199082f3bab99bd67 | [
"if not l or not r or r < l:\n return list()\nreturn [i for i in range(l, r + 1, 1) if self.is_self_dividing(i)]",
"if not i:\n return False\np = i\nwhile p > 0:\n p, d = divmod(p, 10)\n if d == 0 or i % d != 0:\n return False\nreturn True"
] | <|body_start_0|>
if not l or not r or r < l:
return list()
return [i for i in range(l, r + 1, 1) if self.is_self_dividing(i)]
<|end_body_0|>
<|body_start_1|>
if not i:
return False
p = i
while p > 0:
p, d = divmod(p, 10)
if d == 0 ... | Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range | Solution | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range"""
def find_self_dividing_nums(self, l, r):
"""Determines all self-d... | stack_v2_sparse_classes_10k_train_005158 | 3,918 | permissive | [
{
"docstring": "Determines all self-dividing numbers within target limits (inclusive). :param int l: lower limit of target range :param int r: upper limit of target range :return: array of all self-dividing numbers in range :rtype: list[int]",
"name": "find_self_dividing_nums",
"signature": "def find_se... | 2 | stack_v2_sparse_classes_30k_train_001912 | Implement the Python class `Solution` described below.
Class description:
Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range
Method signatures and docstrings:
- def f... | Implement the Python class `Solution` described below.
Class description:
Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range
Method signatures and docstrings:
- def f... | 69f90877c5466927e8b081c4268cbcda074813ec | <|skeleton|>
class Solution:
"""Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range"""
def find_self_dividing_nums(self, l, r):
"""Determines all self-d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""Pythonic iteration over all integers in target range. Time complexity: O(n ** m) - Amortized iterate over all integers and contained digits Space complexity: O(n) - Amortized store all integers in range"""
def find_self_dividing_nums(self, l, r):
"""Determines all self-dividing numbe... | the_stack_v2_python_sparse | 0728_self_dividing_numbers/python_source.py | arthurdysart/LeetCode | train | 0 |
b261e33a15f7278b65224b276db641b5b3647a31 | [
"self._name = name\nself._aws_profile = aws_profile\nself._client = boto3.Session(profile_name=aws_profile, region_name=aws_region).client('autoscaling')",
"config_name = config.get('LaunchConfigurationName', self._name)\nassert config_name == self._name, 'Config name mismatch {} {}'.format(config_name, self._nam... | <|body_start_0|>
self._name = name
self._aws_profile = aws_profile
self._client = boto3.Session(profile_name=aws_profile, region_name=aws_region).client('autoscaling')
<|end_body_0|>
<|body_start_1|>
config_name = config.get('LaunchConfigurationName', self._name)
assert config_n... | LaunchConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaunchConfig:
def __init__(self, name, aws_profile=None, aws_region=None):
"""Init method. Will create AWS clients."""
<|body_0|>
def create(self, config):
"""Create a new launch config using config dict passed in. Config name in __init__ and create must match."""
... | stack_v2_sparse_classes_10k_train_005159 | 3,497 | permissive | [
{
"docstring": "Init method. Will create AWS clients.",
"name": "__init__",
"signature": "def __init__(self, name, aws_profile=None, aws_region=None)"
},
{
"docstring": "Create a new launch config using config dict passed in. Config name in __init__ and create must match.",
"name": "create",... | 5 | stack_v2_sparse_classes_30k_train_000367 | Implement the Python class `LaunchConfig` described below.
Class description:
Implement the LaunchConfig class.
Method signatures and docstrings:
- def __init__(self, name, aws_profile=None, aws_region=None): Init method. Will create AWS clients.
- def create(self, config): Create a new launch config using config dic... | Implement the Python class `LaunchConfig` described below.
Class description:
Implement the LaunchConfig class.
Method signatures and docstrings:
- def __init__(self, name, aws_profile=None, aws_region=None): Init method. Will create AWS clients.
- def create(self, config): Create a new launch config using config dic... | 8601d652476cd30457961aaf9feac143fd437606 | <|skeleton|>
class LaunchConfig:
def __init__(self, name, aws_profile=None, aws_region=None):
"""Init method. Will create AWS clients."""
<|body_0|>
def create(self, config):
"""Create a new launch config using config dict passed in. Config name in __init__ and create must match."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LaunchConfig:
def __init__(self, name, aws_profile=None, aws_region=None):
"""Init method. Will create AWS clients."""
self._name = name
self._aws_profile = aws_profile
self._client = boto3.Session(profile_name=aws_profile, region_name=aws_region).client('autoscaling')
def... | the_stack_v2_python_sparse | common/python/ax/cloud/aws/launch_config.py | durgeshsanagaram/argo | train | 1 | |
2c1efdee1105c559f158e5bbcd006763beb94e7d | [
"super().__init__()\nself.normalize_feats = normalize_feats\nlayers = []\nlast_dim = dims[0]\nfor i, dim in enumerate(dims[1:]):\n layers.append(nn.Linear(last_dim, dim, bias=use_bias))\n if i == len(dims) - 2 and skip_last_bn:\n break\n if use_bn:\n layers.append(nn.BatchNorm1d(dim, eps=mode... | <|body_start_0|>
super().__init__()
self.normalize_feats = normalize_feats
layers = []
last_dim = dims[0]
for i, dim in enumerate(dims[1:]):
layers.append(nn.Linear(last_dim, dim, bias=use_bias))
if i == len(dims) - 2 and skip_last_bn:
brea... | SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering step. Input: 2D torch.tensor of shape (N x C) Ou... | SwAVPrototypesHead | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering st... | stack_v2_sparse_classes_10k_train_005160 | 6,370 | permissive | [
{
"docstring": "Args: model_config (AttrDict): dictionary config.MODEL in the config file dims (int): dimensions of the linear layer. Must have length at least 2. Example: [2048, 2048, 128] attaches linear layer Linear(2048, 2048) -> BN -> Relu -> Linear(2048, 128) use_bn (bool): whether to attach BatchNorm aft... | 2 | null | Implement the Python class `SwAVPrototypesHead` described below.
Class description:
SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features... | Implement the Python class `SwAVPrototypesHead` described below.
Class description:
SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features... | b647c256447af7ea66655811849be1f642377db8 | <|skeleton|>
class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SwAVPrototypesHead:
"""SwAV head used in https://arxiv.org/pdf/2006.09882.pdf paper. The head is composed of 2 parts 1) projection of features to lower dimension like 128 2) feature classification into clusters (also called prototypes) The projected features are L2 normalized before clustering step. Input: 2D... | the_stack_v2_python_sparse | vissl/models/heads/swav_prototypes_head.py | pzharrington/vissl | train | 1 |
7d48359e5b9532ada9a0bf6ce0859bfacef18e85 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AppliedConditionalAccessPolicy()",
"from .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult\nfrom .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult\nfields: Dict[st... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AppliedConditionalAccessPolicy()
<|end_body_0|>
<|body_start_1|>
from .applied_conditional_access_policy_result import AppliedConditionalAccessPolicyResult
from .applied_conditional_acce... | AppliedConditionalAccessPolicy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k_train_005161 | 4,450 | 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: AppliedConditionalAccessPolicy",
"name": "create_from_discriminator_value",
"signature": "def create_from_di... | 3 | null | Implement the Python class `AppliedConditionalAccessPolicy` described below.
Class description:
Implement the AppliedConditionalAccessPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy: Creates a new instance of... | Implement the Python class `AppliedConditionalAccessPolicy` described below.
Class description:
Implement the AppliedConditionalAccessPolicy class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy: Creates a new instance of... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AppliedConditionalAccessPolicy:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppliedConditionalAccessPolicy:
"""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 creat... | the_stack_v2_python_sparse | msgraph/generated/models/applied_conditional_access_policy.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
942714f4b8023e452e056b7ea12d72b2d5563c29 | [
"super(PlacementShiftNet, self).__init__()\nself.num_out_dims = num_out_dims\nself.drop_prob = drop_prob\nself.layer1 = nn.Sequential(nn.Conv2d(in_channels, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2, dil... | <|body_start_0|>
super(PlacementShiftNet, self).__init__()
self.num_out_dims = num_out_dims
self.drop_prob = drop_prob
self.layer1 = nn.Sequential(nn.Conv2d(in_channels, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=5, stride=1, padding=1), nn.ReLU(), ... | PlacementShiftNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlacementShiftNet:
def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5):
"""Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations... | stack_v2_sparse_classes_10k_train_005162 | 13,489 | no_license | [
{
"docstring": "Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations can be applied outside of this class's forward",
"name": "__init__",
"signature": "def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1... | 2 | null | Implement the Python class `PlacementShiftNet` described below.
Class description:
Implement the PlacementShiftNet class.
Method signatures and docstrings:
- def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): Same as PlacementShiftDistNet,... | Implement the Python class `PlacementShiftNet` described below.
Class description:
Implement the PlacementShiftNet class.
Method signatures and docstrings:
- def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5): Same as PlacementShiftDistNet,... | ad713e4eb15a2d9573622bace528fc86e19a6545 | <|skeleton|>
class PlacementShiftNet:
def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5):
"""Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PlacementShiftNet:
def __init__(self, in_channels=2, num_out_dims=2, fc1_size=1024, fc1_input2_size=64, fc2_size=512, input2_size=1, drop_prob=0.5):
"""Same as PlacementShiftDistNet, but the vanilla version (i.e. outputs scalars). Acitvation of final layer is linear. So other activations can be applie... | the_stack_v2_python_sparse | manipulation/plating/RNNs/rnns/networks.py | HARPLab/gastronomy | train | 6 | |
5b666f7761603ae3ea1a7d98e74174a1c3af2b3c | [
"self._text = text\nself._word = word\nself._occurrences = []\nidx = 0\nwhile idx < len(text):\n parse_end = min(idx + len(word), len(text))\n word_in_text = text[idx:parse_end]\n if word_in_text.lower() == word.lower():\n self._occurrences.append(idx)\n idx = parse_end\n else:\n id... | <|body_start_0|>
self._text = text
self._word = word
self._occurrences = []
idx = 0
while idx < len(text):
parse_end = min(idx + len(word), len(text))
word_in_text = text[idx:parse_end]
if word_in_text.lower() == word.lower():
s... | Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), when it us prohibitively expensive for a given application. This is exactly the case.... | WordOccurrences | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordOccurrences:
"""Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), when it us prohibitively expensive for a g... | stack_v2_sparse_classes_10k_train_005163 | 1,872 | permissive | [
{
"docstring": "Constructor with parameter. :param text: str :param word: str",
"name": "__init__",
"signature": "def __init__(self, text: str, word: str)"
},
{
"docstring": "Returns the position of word's n-th occurrence in text (zero-based). :param n: int :return: int",
"name": "get_nth_oc... | 2 | stack_v2_sparse_classes_30k_train_003622 | Implement the Python class `WordOccurrences` described below.
Class description:
Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), whe... | Implement the Python class `WordOccurrences` described below.
Class description:
Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), whe... | 7a8167a85456b481aba15d5eee5a64b116b00adc | <|skeleton|>
class WordOccurrences:
"""Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), when it us prohibitively expensive for a g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WordOccurrences:
"""Class to buffer the positions of occurrences for a word within some text. Recall that one of the applicabilities of Prototype Pattern is: Avoid the inherent cost of creating a new object in the standard way (using the 'new' operator), when it us prohibitively expensive for a given applicat... | the_stack_v2_python_sparse | 2-Creational Patterns/6-Prototype Pattern/WordOccurrences Example/Python/prototype.py | Ziang-Lu/Design-Patterns | train | 2 |
1ff5cf19221fcaf3017c0cc3f48325da8afe2ce5 | [
"args = entity_parser.parse_args()\npage = args['page']\nper_page = args['per_page']\nsort_order = args['order']\nif per_page > 100:\n per_page = 100\ndescending = sort_order == 'desc'\nstart = per_page * (page - 1)\nstop = start + per_page\nkwargs = {'start': start, 'stop': stop, 'descending': descending, 'sess... | <|body_start_0|>
args = entity_parser.parse_args()
page = args['page']
per_page = args['per_page']
sort_order = args['order']
if per_page > 100:
per_page = 100
descending = sort_order == 'desc'
start = per_page * (page - 1)
stop = start + per_p... | SeriesSeasonsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeriesSeasonsAPI:
def get(self, show_id, session):
"""Get seasons by show ID"""
<|body_0|>
def delete(self, show_id, session):
"""Deletes all seasons of a show"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
args = entity_parser.parse_args()
... | stack_v2_sparse_classes_10k_train_005164 | 47,001 | permissive | [
{
"docstring": "Get seasons by show ID",
"name": "get",
"signature": "def get(self, show_id, session)"
},
{
"docstring": "Deletes all seasons of a show",
"name": "delete",
"signature": "def delete(self, show_id, session)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005048 | Implement the Python class `SeriesSeasonsAPI` described below.
Class description:
Implement the SeriesSeasonsAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get seasons by show ID
- def delete(self, show_id, session): Deletes all seasons of a show | Implement the Python class `SeriesSeasonsAPI` described below.
Class description:
Implement the SeriesSeasonsAPI class.
Method signatures and docstrings:
- def get(self, show_id, session): Get seasons by show ID
- def delete(self, show_id, session): Deletes all seasons of a show
<|skeleton|>
class SeriesSeasonsAPI:
... | ea95ff60041beaea9aacbc2d93549e3a6b981dc5 | <|skeleton|>
class SeriesSeasonsAPI:
def get(self, show_id, session):
"""Get seasons by show ID"""
<|body_0|>
def delete(self, show_id, session):
"""Deletes all seasons of a show"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SeriesSeasonsAPI:
def get(self, show_id, session):
"""Get seasons by show ID"""
args = entity_parser.parse_args()
page = args['page']
per_page = args['per_page']
sort_order = args['order']
if per_page > 100:
per_page = 100
descending = sort_o... | the_stack_v2_python_sparse | flexget/components/series/api.py | BrutuZ/Flexget | train | 1 | |
fff7b890da23348a6c8b6afa9e22bb9afec32872 | [
"article = ArticleInst.fetch(slug)\ncomment = request.data.get('comment', {})\nserializer = self.serializer_class(data=comment)\nserializer.is_valid(raise_exception=True)\nstatus_ = status.HTTP_201_CREATED\ntry:\n Comment.objects.get(article=article, body=comment.get('body'))\nexcept Comment.DoesNotExist:\n s... | <|body_start_0|>
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
serializer = self.serializer_class(data=comment)
serializer.is_valid(raise_exception=True)
status_ = status.HTTP_201_CREATED
try:
Comment.objects.get(article=article, ... | Handles listing of all comments and creation of new comments to an article | ListCommentsView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
<|body_0|>
def get(self, request, slug):
"""Retrieves all comments associated with an article"""
... | stack_v2_sparse_classes_10k_train_005165 | 10,918 | permissive | [
{
"docstring": "Posts a comment to an article",
"name": "post",
"signature": "def post(self, request, slug)"
},
{
"docstring": "Retrieves all comments associated with an article",
"name": "get",
"signature": "def get(self, request, slug)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002864 | Implement the Python class `ListCommentsView` described below.
Class description:
Handles listing of all comments and creation of new comments to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a comment to an article
- def get(self, request, slug): Retrieves all comments associate... | Implement the Python class `ListCommentsView` described below.
Class description:
Handles listing of all comments and creation of new comments to an article
Method signatures and docstrings:
- def post(self, request, slug): Posts a comment to an article
- def get(self, request, slug): Retrieves all comments associate... | b80ad485339dbb02b74d9b2093543bf8173d51de | <|skeleton|>
class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
<|body_0|>
def get(self, request, slug):
"""Retrieves all comments associated with an article"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ListCommentsView:
"""Handles listing of all comments and creation of new comments to an article"""
def post(self, request, slug):
"""Posts a comment to an article"""
article = ArticleInst.fetch(slug)
comment = request.data.get('comment', {})
serializer = self.serializer_cl... | the_stack_v2_python_sparse | authors/apps/comments/views.py | deferral/ah-django | train | 1 |
fc26cb07de0a6458130cedb2be9e5491fe0cc862 | [
"self.sensor_dimensions_in_cm = (Sensor_dim_in_px[0] * (pixel_size_in_um / 10000), Sensor_dim_in_px[1] * (pixel_size_in_um / 10000))\nself.focal_in_cm = focal_in_mm / 10\nself.element_height_in_cm = element_heigth_in_cm\nself.sensor_aperture_in_degrees = 2 * atan(self.sensor_dimensions_in_cm[0] / (2 * self.focal_in... | <|body_start_0|>
self.sensor_dimensions_in_cm = (Sensor_dim_in_px[0] * (pixel_size_in_um / 10000), Sensor_dim_in_px[1] * (pixel_size_in_um / 10000))
self.focal_in_cm = focal_in_mm / 10
self.element_height_in_cm = element_heigth_in_cm
self.sensor_aperture_in_degrees = 2 * atan(self.sensor... | CameraCalculator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraCalculator:
def __init__(self, pixel_size_in_um=SENSOR_PIXEL_SIZE_IN_UM, Sensor_dim_in_px=SENSOR_DIM_IN_PIXELS, focal_in_mm=FOCAL_IN_MM, element_heigth_in_cm=ELEMENT_HEIGHT_IN_CM):
"""Uses the Gauss Formula for Lens for calculating the distance to the baby in function of the parame... | stack_v2_sparse_classes_10k_train_005166 | 5,412 | no_license | [
{
"docstring": "Uses the Gauss Formula for Lens for calculating the distance to the baby in function of the parameters of the camera (focal length, sensor dimensions and pixel size), the height of the target and the height of its detected reflexion in the camera sensor. :param pixel_size_in_um: Float. Pixel siz... | 4 | stack_v2_sparse_classes_30k_train_001386 | Implement the Python class `CameraCalculator` described below.
Class description:
Implement the CameraCalculator class.
Method signatures and docstrings:
- def __init__(self, pixel_size_in_um=SENSOR_PIXEL_SIZE_IN_UM, Sensor_dim_in_px=SENSOR_DIM_IN_PIXELS, focal_in_mm=FOCAL_IN_MM, element_heigth_in_cm=ELEMENT_HEIGHT_I... | Implement the Python class `CameraCalculator` described below.
Class description:
Implement the CameraCalculator class.
Method signatures and docstrings:
- def __init__(self, pixel_size_in_um=SENSOR_PIXEL_SIZE_IN_UM, Sensor_dim_in_px=SENSOR_DIM_IN_PIXELS, focal_in_mm=FOCAL_IN_MM, element_heigth_in_cm=ELEMENT_HEIGHT_I... | 5103b2bd78ffbbb42afb892bdca67859324726e9 | <|skeleton|>
class CameraCalculator:
def __init__(self, pixel_size_in_um=SENSOR_PIXEL_SIZE_IN_UM, Sensor_dim_in_px=SENSOR_DIM_IN_PIXELS, focal_in_mm=FOCAL_IN_MM, element_heigth_in_cm=ELEMENT_HEIGHT_IN_CM):
"""Uses the Gauss Formula for Lens for calculating the distance to the baby in function of the parame... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CameraCalculator:
def __init__(self, pixel_size_in_um=SENSOR_PIXEL_SIZE_IN_UM, Sensor_dim_in_px=SENSOR_DIM_IN_PIXELS, focal_in_mm=FOCAL_IN_MM, element_heigth_in_cm=ELEMENT_HEIGHT_IN_CM):
"""Uses the Gauss Formula for Lens for calculating the distance to the baby in function of the parameters of the ca... | the_stack_v2_python_sparse | RobotController/PiCamera/CameraCalculator/CameraCalculator.py | Eric-Canas/BabyRobot | train | 1 | |
087b92c724b3807537bb10452a42f2bceac59b17 | [
"identifier = f'{ROTKI_EVENT_PREFIX}_{uuid4().hex}'\ntry:\n event_type, event_subtype = GENERIC_TYPE_TO_HISTORY_EVENT_TYPE_MAPPINGS[csv_row['Type']]\nexcept KeyError as e:\n raise UnsupportedCSVEntry(f\"Unsupported entry {csv_row['Type']}. Data: {csv_row}\") from e\nevents: list[HistoryBaseEntry] = []\nasset,... | <|body_start_0|>
identifier = f'{ROTKI_EVENT_PREFIX}_{uuid4().hex}'
try:
event_type, event_subtype = GENERIC_TYPE_TO_HISTORY_EVENT_TYPE_MAPPINGS[csv_row['Type']]
except KeyError as e:
raise UnsupportedCSVEntry(f"Unsupported entry {csv_row['Type']}. Data: {csv_row}") from ... | RotkiGenericEventsImporter | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownA... | stack_v2_sparse_classes_10k_train_005167 | 4,809 | permissive | [
{
"docstring": "Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownAsset - KeyError",
"name": "_consume_rotki_event",
"signature": "def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any... | 2 | null | Implement the Python class `RotkiGenericEventsImporter` described below.
Class description:
Implement the RotkiGenericEventsImporter class.
Method signatures and docstrings:
- def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None: Consume rotki generic events imp... | Implement the Python class `RotkiGenericEventsImporter` described below.
Class description:
Implement the RotkiGenericEventsImporter class.
Method signatures and docstrings:
- def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None: Consume rotki generic events imp... | 496948458b89afc41458f19d1cba0e971ab67c8b | <|skeleton|>
class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownA... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RotkiGenericEventsImporter:
def _consume_rotki_event(self, write_cursor: DBCursor, csv_row: dict[str, Any], sequence_index: int) -> None:
"""Consume rotki generic events import CSV file. May raise: - UnsupportedCSVEntry if an unknown type is encountered. - DeserializationError - UnknownAsset - KeyErro... | the_stack_v2_python_sparse | rotkehlchen/data_import/importers/rotki_events.py | LefterisJP/rotkehlchen | train | 0 | |
38b9452142eaa8cc7c802c034f8e65fdd5efcd10 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SynchronizationRule()",
"from .container_filter import ContainerFilter\nfrom .group_filter import GroupFilter\nfrom .object_mapping import ObjectMapping\nfrom .string_key_string_value_pair import StringKeyStringValuePair\nfrom .contain... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SynchronizationRule()
<|end_body_0|>
<|body_start_1|>
from .container_filter import ContainerFilter
from .group_filter import GroupFilter
from .object_mapping import ObjectMappin... | SynchronizationRule | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynchronizationRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationRule:
"""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 ob... | stack_v2_sparse_classes_10k_train_005168 | 6,106 | 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: SynchronizationRule",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | stack_v2_sparse_classes_30k_train_000198 | Implement the Python class `SynchronizationRule` described below.
Class description:
Implement the SynchronizationRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationRule: Creates a new instance of the appropriate class based on d... | Implement the Python class `SynchronizationRule` described below.
Class description:
Implement the SynchronizationRule class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationRule: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SynchronizationRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationRule:
"""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 ob... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SynchronizationRule:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationRule:
"""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: ... | the_stack_v2_python_sparse | msgraph/generated/models/synchronization_rule.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6bbafd267f6b7c7465c6aef4ae5df9ab2384b9ea | [
"n = len(s)\nresult = []\n\ndef dfs(i, path):\n if i == n:\n result.append(path)\n return\n for j in range(i + 1, n + 1):\n if s[i:j] == s[i:j][::-1]:\n dfs(j, path + [s[i:j]])\ndfs(0, [])\nreturn result",
"n = len(s)\nresult = []\n\n@lru_cache(None)\ndef is_palindrone(i, j):... | <|body_start_0|>
n = len(s)
result = []
def dfs(i, path):
if i == n:
result.append(path)
return
for j in range(i + 1, n + 1):
if s[i:j] == s[i:j][::-1]:
dfs(j, path + [s[i:j]])
dfs(0, [])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def partition(self, s: str) -> List[List[str]]:
"""Backtracking, Time: O(n*2^n), Space: O(n)"""
<|body_0|>
def partition(self, s: str) -> List[List[str]]:
"""Backtracking + Top-Down DP on is_palindrone, Time: O(n*2^n), Space: O(n)"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k_train_005169 | 1,269 | no_license | [
{
"docstring": "Backtracking, Time: O(n*2^n), Space: O(n)",
"name": "partition",
"signature": "def partition(self, s: str) -> List[List[str]]"
},
{
"docstring": "Backtracking + Top-Down DP on is_palindrone, Time: O(n*2^n), Space: O(n)",
"name": "partition",
"signature": "def partition(se... | 2 | stack_v2_sparse_classes_30k_train_007188 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s: str) -> List[List[str]]: Backtracking, Time: O(n*2^n), Space: O(n)
- def partition(self, s: str) -> List[List[str]]: Backtracking + Top-Down DP on is_palin... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def partition(self, s: str) -> List[List[str]]: Backtracking, Time: O(n*2^n), Space: O(n)
- def partition(self, s: str) -> List[List[str]]: Backtracking + Top-Down DP on is_palin... | 72136e3487d239f5b37e2d6393e034262a6bf599 | <|skeleton|>
class Solution:
def partition(self, s: str) -> List[List[str]]:
"""Backtracking, Time: O(n*2^n), Space: O(n)"""
<|body_0|>
def partition(self, s: str) -> List[List[str]]:
"""Backtracking + Top-Down DP on is_palindrone, Time: O(n*2^n), Space: O(n)"""
<|body_1|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def partition(self, s: str) -> List[List[str]]:
"""Backtracking, Time: O(n*2^n), Space: O(n)"""
n = len(s)
result = []
def dfs(i, path):
if i == n:
result.append(path)
return
for j in range(i + 1, n + 1):
... | the_stack_v2_python_sparse | python/131-Palindrome Partitioning.py | cwza/leetcode | train | 0 | |
4d8703ab469b53407c3e2000c50416251ace5eed | [
"dummy_head = ListNode(0)\ndummy_head.next = head\nif n == m:\n return dummy_head.next\ni = 1\npre = dummy_head\nwhile i < m:\n pre = pre.next\n i += 1\ntemp_head = None\ntail = pre.next\nwhile i < n:\n cur = pre.next\n pre.next = cur.next\n cur.next = temp_head\n temp_head = cur\n i += 1\nn... | <|body_start_0|>
dummy_head = ListNode(0)
dummy_head.next = head
if n == m:
return dummy_head.next
i = 1
pre = dummy_head
while i < m:
pre = pre.next
i += 1
temp_head = None
tail = pre.next
while i < n:
... | ReverseLinkedList2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverse_between_dj(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_... | stack_v2_sparse_classes_10k_train_005170 | 2,382 | no_license | [
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverse_between",
"signature": "def reverse_between(self, head, m, n)"
},
{
"docstring": ":type head: ListNode :type m: int :type n: int :rtype: ListNode",
"name": "reverse_between_dj",
"signature"... | 2 | stack_v2_sparse_classes_30k_train_002822 | Implement the Python class `ReverseLinkedList2` described below.
Class description:
Implement the ReverseLinkedList2 class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverse_between_dj(self, head, m, n): :type head:... | Implement the Python class `ReverseLinkedList2` described below.
Class description:
Implement the ReverseLinkedList2 class.
Method signatures and docstrings:
- def reverse_between(self, head, m, n): :type head: ListNode :type m: int :type n: int :rtype: ListNode
- def reverse_between_dj(self, head, m, n): :type head:... | e41f4ac9e99b9272ed4718680f4d12fd7443db03 | <|skeleton|>
class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_0|>
def reverse_between_dj(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReverseLinkedList2:
def reverse_between(self, head, m, n):
""":type head: ListNode :type m: int :type n: int :rtype: ListNode"""
dummy_head = ListNode(0)
dummy_head.next = head
if n == m:
return dummy_head.next
i = 1
pre = dummy_head
while i ... | the_stack_v2_python_sparse | tags/linked_list/reverse_linked_list2.py | jied314/IQs | train | 0 | |
b6c35a8577519638942f88bd0970dd66be54aa7a | [
"result = self.first_name\nif self.last_name is not None:\n result += ' ' + self.last_name\nreturn result",
"if not hasattr(self, '_avatar'):\n avatars = self._api.call('getUserProfilePhotos', {'user_id': self.id, 'limit': 1}, expect=UserProfilePhotos)\n self._avatar = None\n if len(avatars.photos):\n... | <|body_start_0|>
result = self.first_name
if self.last_name is not None:
result += ' ' + self.last_name
return result
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_avatar'):
avatars = self._api.call('getUserProfilePhotos', {'user_id': self.id, 'limit': 1... | Telegram API representation of an user https://core.telegram.org/bots/api#user | User | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
<|body_0|>
def avatar(self):
"""Get the avatar of the user"""
<|body_1|>
def avatar_history(self):
... | stack_v2_sparse_classes_10k_train_005171 | 17,248 | permissive | [
{
"docstring": "Get the full name of the user",
"name": "name",
"signature": "def name(self)"
},
{
"docstring": "Get the avatar of the user",
"name": "avatar",
"signature": "def avatar(self)"
},
{
"docstring": "Get all the avatars of the user",
"name": "avatar_history",
"... | 3 | stack_v2_sparse_classes_30k_train_005416 | Implement the Python class `User` described below.
Class description:
Telegram API representation of an user https://core.telegram.org/bots/api#user
Method signatures and docstrings:
- def name(self): Get the full name of the user
- def avatar(self): Get the avatar of the user
- def avatar_history(self): Get all the ... | Implement the Python class `User` described below.
Class description:
Telegram API representation of an user https://core.telegram.org/bots/api#user
Method signatures and docstrings:
- def name(self): Get the full name of the user
- def avatar(self): Get the avatar of the user
- def avatar_history(self): Get all the ... | 7daafc09cb8bbc27517e1febc5a6ca5a01cbc655 | <|skeleton|>
class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
<|body_0|>
def avatar(self):
"""Get the avatar of the user"""
<|body_1|>
def avatar_history(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class User:
"""Telegram API representation of an user https://core.telegram.org/bots/api#user"""
def name(self):
"""Get the full name of the user"""
result = self.first_name
if self.last_name is not None:
result += ' ' + self.last_name
return result
def avatar(s... | the_stack_v2_python_sparse | botogram/objects/chats.py | Ensenasty/botogram | train | 0 |
52c8bbd470a30b42bb1da00520ae10a00ae7a648 | [
"super(SoftwareSpriteRenderSystem, self).__init__()\nif isinstance(window, Window):\n self.window = window.window\nelif isinstance(window, video.SDL_Window):\n self.window = window\nelse:\n raise TypeError('unsupported window type')\nself.target = window\nsfc = video.SDL_GetWindowSurface(self.window)\nif n... | <|body_start_0|>
super(SoftwareSpriteRenderSystem, self).__init__()
if isinstance(window, Window):
self.window = window.window
elif isinstance(window, video.SDL_Window):
self.window = window
else:
raise TypeError('unsupported window type')
self... | A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operations, such as texture handling or using SDL renderers is not possible. | SoftwareSpriteRenderSystem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftwareSpriteRenderSystem:
"""A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operations, such as texture handling or using ... | stack_v2_sparse_classes_10k_train_005172 | 14,308 | permissive | [
{
"docstring": "Creates a new SoftwareSpriteRenderSystem for a specific Window.",
"name": "__init__",
"signature": "def __init__(self, window)"
},
{
"docstring": "Draws the passed sprites (or sprite) on the Window's surface. x and y are optional arguments that can be used as relative drawing loc... | 2 | null | Implement the Python class `SoftwareSpriteRenderSystem` described below.
Class description:
A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operati... | Implement the Python class `SoftwareSpriteRenderSystem` described below.
Class description:
A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operati... | 29f79c41cfb49ea5b1dd1bec559795727e868558 | <|skeleton|>
class SoftwareSpriteRenderSystem:
"""A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operations, such as texture handling or using ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SoftwareSpriteRenderSystem:
"""A rendering system for SoftwareSprite components. The SoftwareSpriteRenderSystem class uses a Window as drawing device to display Sprite surfaces. It uses the Window's internal SDL surface as drawing context, so that GL operations, such as texture handling or using SDL renderers... | the_stack_v2_python_sparse | blimgui/dist/sdl2/ext/spritesystem.py | juso40/bl2sdk_Mods | train | 42 |
55635ed1a1d82ecec7a592001e19eda422acfeee | [
"latest = 1\ncurr = 0\nwhile True:\n curr = latest\n latest = (latest + x / latest) / 2\n if abs(latest - curr) < 1e-07:\n break\nreturn int(curr)",
"if x == 0:\n return 0\nleft, right = (1, x >> 1)\nwhile left < right:\n mid = left + right + 1 >> 1\n v = mid * mid\n if v > x:\n ... | <|body_start_0|>
latest = 1
curr = 0
while True:
curr = latest
latest = (latest + x / latest) / 2
if abs(latest - curr) < 1e-07:
break
return int(curr)
<|end_body_0|>
<|body_start_1|>
if x == 0:
return 0
lef... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
<|body_0|>
def sqrt1(self, x):
"""二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 m... | stack_v2_sparse_classes_10k_train_005173 | 1,782 | no_license | [
{
"docstring": "数学分析法,牛顿迭代法:",
"name": "sqrt",
"signature": "def sqrt(self, x)"
},
{
"docstring": "二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 mid * mid = 9... | 2 | stack_v2_sparse_classes_30k_train_002853 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sqrt(self, x): 数学分析法,牛顿迭代法:
- def sqrt1(self, x): 二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sqrt(self, x): 数学分析法,牛顿迭代法:
- def sqrt1(self, x): 二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3... | 0cc970aaa03aa9300319a1e39e052e4beeec6698 | <|skeleton|>
class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
<|body_0|>
def sqrt1(self, x):
"""二分法很好理解,要知道任何一个正整数的算术平方根是不可能大于这个数的一般的,所以基于这个特性,我们可以利用二分查找找[1, x / 2]那个数与x最接近。 注意的是,我们找中位数的时候,要找右中位数, 因为当遇到x = 9的时候,我们计算到区间[3, 4],如果此时去中位数按照以前mid = (left + right) // 2的话, 此时mid = 3, 那么 m... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def sqrt(self, x):
"""数学分析法,牛顿迭代法:"""
latest = 1
curr = 0
while True:
curr = latest
latest = (latest + x / latest) / 2
if abs(latest - curr) < 1e-07:
break
return int(curr)
def sqrt1(self, x):
""... | the_stack_v2_python_sparse | leetcode.69x的平方根.py | NonCover/- | train | 2 | |
6020acf1143a12164983ea1e03fd1c2d2c0b8430 | [
"try:\n verify_token(request.headers)\nexcept Exception as err:\n ns.abort(401, message=err)\noffset = request.args.get('offset', '0')\nlimit = request.args.get('limit', '10')\norder_by = request.args.get('order_by', 'id')\norder = request.args.get('order', 'ASC')\nper_page = request.args.get('per_page', '10'... | <|body_start_0|>
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request.args.get('offset', '0')
limit = request.args.get('limit', '10')
order_by = request.args.get('order_by', 'id')
order = request.a... | ProgramaSocialList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramaSocialList:
def get(self):
"""Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear un programa social"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005174 | 6,332 | no_license | [
{
"docstring": "Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Crear un programa social",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006268 | Implement the Python class `ProgramaSocialList` described below.
Class description:
Implement the ProgramaSocialList class.
Method signatures and docstrings:
- def get(self): Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear un progra... | Implement the Python class `ProgramaSocialList` described below.
Class description:
Implement the ProgramaSocialList class.
Method signatures and docstrings:
- def get(self): Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages
- def post(self): Crear un progra... | e00610fac26ef3ca078fd037c0649b70fa0e9a09 | <|skeleton|>
class ProgramaSocialList:
def get(self):
"""Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
<|body_0|>
def post(self):
"""Crear un programa social"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProgramaSocialList:
def get(self):
"""Listado de programas sociales. On Success it returns two custom headers: X-SOA-Total-Items, X-SOA-Total-Pages"""
try:
verify_token(request.headers)
except Exception as err:
ns.abort(401, message=err)
offset = request... | the_stack_v2_python_sparse | DOS/soa/service/genl/endpoints/programas_sociales.py | Telematica/knight-rider | train | 1 | |
09664f8a4cce173651142202ebfab6d36a157a55 | [
"encrypted_data = [ord(i) for i in data]\nencrypted_data = [str(i) + ' ' for i in encrypted_data]\nencrypted_data = ''.join(encrypted_data)\nprint(f'Writing encrypted {data} as {encrypted_data}')\nsuper().write(encrypted_data)\nprint(f'Finished writing encrypted data {encrypted_data}')",
"print('reading encrypte... | <|body_start_0|>
encrypted_data = [ord(i) for i in data]
encrypted_data = [str(i) + ' ' for i in encrypted_data]
encrypted_data = ''.join(encrypted_data)
print(f'Writing encrypted {data} as {encrypted_data}')
super().write(encrypted_data)
print(f'Finished writing encrypt... | This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The encryption converts each letter to its ASCII code, while the decryption algorithm does the same. | EncryptedDataSourceDecorator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncryptedDataSourceDecorator:
"""This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The encryption converts each letter to its AS... | stack_v2_sparse_classes_10k_train_005175 | 6,195 | no_license | [
{
"docstring": "Encrypts the given data and calls the write function of the DataSource that is being wrapped around. :param data: a string :return: None",
"name": "write",
"signature": "def write(self, data)"
},
{
"docstring": "Reads data from a data source and decrypts it to a string value. :pr... | 2 | stack_v2_sparse_classes_30k_train_006084 | Implement the Python class `EncryptedDataSourceDecorator` described below.
Class description:
This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The en... | Implement the Python class `EncryptedDataSourceDecorator` described below.
Class description:
This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The en... | 68ad3a22646c5433e395fbee2c1fbb972b805c09 | <|skeleton|>
class EncryptedDataSourceDecorator:
"""This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The encryption converts each letter to its AS... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncryptedDataSourceDecorator:
"""This is a decorator (read: wrapper) that adds an encryption/decryption behaviour to a datasource. This decorator can wrap around a concrete DataSource (like FileDataSource) or it can also wrap around another Decorator. The encryption converts each letter to its ASCII code, whi... | the_stack_v2_python_sparse | Lectures/1028/decorator_example.py | usop7/Python_OOP_Projects | train | 0 |
1f469c4a7678bd681ee263ed81c12bfcf5d203d3 | [
"if not A:\n return -1\nn = len(A)\nsortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))\nindex_max = [index[-1]] * n\nfor i in range(n - 2, -1, -1):\n index_max[i] = max(index[i], index_max[i + 1])\nres = 0\nfor i, j in zip(index, index_max):\n res = max(res, j - i)\nreturn res",
"if not A:\... | <|body_start_0|>
if not A:
return -1
n = len(A)
sortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))
index_max = [index[-1]] * n
for i in range(n - 2, -1, -1):
index_max[i] = max(index[i], index_max[i + 1])
res = 0
for i, j in z... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
<|body_0|>
def naiveMaximumGap(self, A):
"""Time Complexity: O(n*n)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not A:
return -1
n = len(A)
sortedA... | stack_v2_sparse_classes_10k_train_005176 | 2,223 | permissive | [
{
"docstring": "Time Complexity: O(nlogn)",
"name": "maximumGap",
"signature": "def maximumGap(self, A)"
},
{
"docstring": "Time Complexity: O(n*n)",
"name": "naiveMaximumGap",
"signature": "def naiveMaximumGap(self, A)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumGap(self, A): Time Complexity: O(nlogn)
- def naiveMaximumGap(self, A): Time Complexity: O(n*n) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumGap(self, A): Time Complexity: O(nlogn)
- def naiveMaximumGap(self, A): Time Complexity: O(n*n)
<|skeleton|>
class Solution:
def maximumGap(self, A):
"""... | 77bc551a03a2a3e3808e50016ece14adb5cfbd96 | <|skeleton|>
class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
<|body_0|>
def naiveMaximumGap(self, A):
"""Time Complexity: O(n*n)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maximumGap(self, A):
"""Time Complexity: O(nlogn)"""
if not A:
return -1
n = len(A)
sortedA, index = zip(*sorted(((a, i) for i, a in enumerate(A))))
index_max = [index[-1]] * n
for i in range(n - 2, -1, -1):
index_max[i] = m... | the_stack_v2_python_sparse | quizzes/interviewbit/programming/arrays/max_distance.py | JiniousChoi/encyclopedia-in-code | train | 2 | |
ccd76485925a4b693b312575c44683f60bcafc01 | [
"future_seq = self.image_group_future_seq(image_seq, **kwargs)\nindex_group_seq = self.future_result_seq(future_seq)\nfor _, group in sorted(index_group_seq):\n for image in group:\n yield image",
"future_list = list(future_seq)\nfuture_seq = as_completed(future_list)\nfor future in future_seq:\n yie... | <|body_start_0|>
future_seq = self.image_group_future_seq(image_seq, **kwargs)
index_group_seq = self.future_result_seq(future_seq)
for _, group in sorted(index_group_seq):
for image in group:
yield image
<|end_body_0|>
<|body_start_1|>
future_list = list(fut... | It helps only with long videos WARNING: remember that sending data from process to another has its own costs! | ParallelExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelExtractor:
"""It helps only with long videos WARNING: remember that sending data from process to another has its own costs!"""
def transform_frame_images(self, image_seq, **kwargs):
""":param image_seq: :param kwargs: :return:"""
<|body_0|>
def future_result_seq(... | stack_v2_sparse_classes_10k_train_005177 | 3,728 | permissive | [
{
"docstring": ":param image_seq: :param kwargs: :return:",
"name": "transform_frame_images",
"signature": "def transform_frame_images(self, image_seq, **kwargs)"
},
{
"docstring": ":param future_seq: :return:",
"name": "future_result_seq",
"signature": "def future_result_seq(future_seq)... | 5 | stack_v2_sparse_classes_30k_val_000285 | Implement the Python class `ParallelExtractor` described below.
Class description:
It helps only with long videos WARNING: remember that sending data from process to another has its own costs!
Method signatures and docstrings:
- def transform_frame_images(self, image_seq, **kwargs): :param image_seq: :param kwargs: :... | Implement the Python class `ParallelExtractor` described below.
Class description:
It helps only with long videos WARNING: remember that sending data from process to another has its own costs!
Method signatures and docstrings:
- def transform_frame_images(self, image_seq, **kwargs): :param image_seq: :param kwargs: :... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class ParallelExtractor:
"""It helps only with long videos WARNING: remember that sending data from process to another has its own costs!"""
def transform_frame_images(self, image_seq, **kwargs):
""":param image_seq: :param kwargs: :return:"""
<|body_0|>
def future_result_seq(... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ParallelExtractor:
"""It helps only with long videos WARNING: remember that sending data from process to another has its own costs!"""
def transform_frame_images(self, image_seq, **kwargs):
""":param image_seq: :param kwargs: :return:"""
future_seq = self.image_group_future_seq(image_seq,... | the_stack_v2_python_sparse | shot_detector/features/extractors/parallel_extractor.py | w495/python-video-shot-detector | train | 20 |
c1bce218f52678372c242fa2bdade9fdd4d33d68 | [
"n = len(s)\ndp = [[0] * n for _ in range(n)]\nans = ''\nfor i in range(n):\n for j in range(i, -1, -1):\n if s[i] == s[j] and (i - j <= 2 or dp[i - 1][j + 1] == 1):\n dp[i][j] = 1\n ans = max(ans, s[j:i + 1], key=len)\nreturn ans",
"n = len(s)\nres = ''\n\ndef _helper(s, l, r):\n ... | <|body_start_0|>
n = len(s)
dp = [[0] * n for _ in range(n)]
ans = ''
for i in range(n):
for j in range(i, -1, -1):
if s[i] == s[j] and (i - j <= 2 or dp[i - 1][j + 1] == 1):
dp[i][j] = 1
ans = max(ans, s[j:i + 1], key=l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
<|body_0|>
def longestPalindrome(self, s:... | stack_v2_sparse_classes_10k_train_005178 | 2,295 | no_license | [
{
"docstring": "动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1",
"name": "longestPalindrome_1",
"signature": "def longestPalindrome_1(self, s: str) -> str"
},
{
"docstring... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s: str) -> str: 动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome_1(self, s: str) -> str: 动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i... | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | <|skeleton|>
class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
<|body_0|>
def longestPalindrome(self, s:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome_1(self, s: str) -> str:
"""动态规划: 1. dp[i][j] 表示 s[j:i+1] 是否为回文子串 2. 状态转移方程: - i==j: dp[i][j]=1 - i-j==1 且 s[i]==s[j]: dp[i][j]=1 - i-j>1 且 s[i]==s[j] 且 s[j+1:i] 为回文子串,即 dp[i-1][j+1]==1 时: dp[i][j]=1"""
n = len(s)
dp = [[0] * n for _ in range(n)]
... | the_stack_v2_python_sparse | Week_08/G20190343020242/LeetCode_5_0242.py | algorithm005-class01/algorithm005-class01 | train | 27 | |
002c469bd1ed9c15918a9194cb968ec187203d0b | [
"try:\n self.sig_maker = _librsync.new_sigmaker(blocksize)\nexcept _librsync.librsyncError as e:\n raise librsyncError(str(e))\nself.gotsig = None\nself.buffer = ''\nself.sigstring_list = []",
"if self.gotsig:\n raise librsyncError('SigGenerator already provided signature')\nself.buffer += buf\nwhile len... | <|body_start_0|>
try:
self.sig_maker = _librsync.new_sigmaker(blocksize)
except _librsync.librsyncError as e:
raise librsyncError(str(e))
self.gotsig = None
self.buffer = ''
self.sigstring_list = []
<|end_body_0|>
<|body_start_1|>
if self.gotsig:
... | Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object | SigGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SigGenerator:
"""Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object"""
def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN):
"""Return new signature instance"""
<|body_0|>
def update(self, buf):
... | stack_v2_sparse_classes_10k_train_005179 | 8,383 | no_license | [
{
"docstring": "Return new signature instance",
"name": "__init__",
"signature": "def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN)"
},
{
"docstring": "Add buf to data that signature will be calculated over",
"name": "update",
"signature": "def update(self, buf)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_004718 | Implement the Python class `SigGenerator` described below.
Class description:
Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object
Method signatures and docstrings:
- def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN): Return new signature insta... | Implement the Python class `SigGenerator` described below.
Class description:
Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object
Method signatures and docstrings:
- def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN): Return new signature insta... | ef6d0f4bdff52be379784325e504de22cfe149de | <|skeleton|>
class SigGenerator:
"""Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object"""
def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN):
"""Return new signature instance"""
<|body_0|>
def update(self, buf):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SigGenerator:
"""Calculate signature. Input and output is same as SigFile, but the interface is like md5 module, not filelike object"""
def __init__(self, blocksize=_librsync.RS_DEFAULT_BLOCK_LEN):
"""Return new signature instance"""
try:
self.sig_maker = _librsync.new_sigmake... | the_stack_v2_python_sparse | duplicity/librsync.py | henrysher/duplicity | train | 90 |
94e1b171130a75e8d09c4fea7088f43c1a23a2f3 | [
"self.colored = colored\nself.formatter_chain = formatter_chain or []\nself.formatter_chain.append(LogsFormatter._pretty_print_event)",
"for operation in self.formatter_chain:\n partial_op = functools.partial(operation, colored=self.colored)\n event_iterable = imap(partial_op, event_iterable)\nreturn event_... | <|body_start_0|>
self.colored = colored
self.formatter_chain = formatter_chain or []
self.formatter_chain.append(LogsFormatter._pretty_print_event)
<|end_body_0|>
<|body_start_1|>
for operation in self.formatter_chain:
partial_op = functools.partial(operation, colored=self.c... | Formats log messages returned by CloudWatch Logs service. | LogsFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and retu... | stack_v2_sparse_classes_10k_train_005180 | 6,494 | permissive | [
{
"docstring": "``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and return the same object back. This allows us to easily chain formatter methods one after another. This class will apply all the formatters from this l... | 3 | stack_v2_sparse_classes_30k_train_005311 | Implement the Python class `LogsFormatter` described below.
Class description:
Formats log messages returned by CloudWatch Logs service.
Method signatures and docstrings:
- def __init__(self, colored, formatter_chain=None): ``formatter_chain`` is a list of methods that can format an event. Each method must take an ``... | Implement the Python class `LogsFormatter` described below.
Class description:
Formats log messages returned by CloudWatch Logs service.
Method signatures and docstrings:
- def __init__(self, colored, formatter_chain=None): ``formatter_chain`` is a list of methods that can format an event. Each method must take an ``... | 9b13e9390d0ae10bf0d3cdfaf3f449cde9b460b7 | <|skeleton|>
class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and retu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and return the same o... | the_stack_v2_python_sparse | samcli/lib/logs/formatter.py | keetonian/aws-sam-cli | train | 1 |
7dd1822b730aa7c21e28c2e2f5266bb296329369 | [
"self.max_len = min(trace_len, max_evaluations)\nself.iteration = []\nself.fitness = []\nself.next_iteration = 0\nif self.max_len > 0:\n self.interval = max_evaluations // self.max_len",
"if self.max_len > 0:\n if iteration >= self.next_iteration:\n self.fitness.append(fitness)\n self.iteratio... | <|body_start_0|>
self.max_len = min(trace_len, max_evaluations)
self.iteration = []
self.fitness = []
self.next_iteration = 0
if self.max_len > 0:
self.interval = max_evaluations // self.max_len
<|end_body_0|>
<|body_start_1|>
if self.max_len > 0:
... | 记录不同iteration对应的fitness | FitnessTrace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_10k_train_005181 | 3,090 | no_license | [
{
"docstring": "Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: Object instance.",
"name": "__init__",
"signature": "def __init__(self, trace_len, max... | 2 | stack_v2_sparse_classes_30k_train_003523 | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | Implement the Python class `FitnessTrace` described below.
Class description:
记录不同iteration对应的fitness
Method signatures and docstrings:
- def __init__(self, trace_len, max_evaluations): Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluation... | 1157e5abc004af624f182879105f9284f97ef08c | <|skeleton|>
class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be perform... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FitnessTrace:
"""记录不同iteration对应的fitness"""
def __init__(self, trace_len, max_evaluations):
"""Create the object instance. :param trace_len: Max length of fitness-trace. Zero if no fitness-trace is wanted. :param max_evaluations: Number of optimization iterations that will be performed. :return: ... | the_stack_v2_python_sparse | Programme/python/two qubit gate/CZgate/IBM/Qubits module/swarmops/FitnessTrace.py | ChenZha/Quantum-Computation | train | 6 |
82bcf6f3e4e0aa2c11e809dc982b412cccaa331f | [
"def helper(i):\n if i == 1:\n return '0'\n s = helper(i - 1)\n t = ''\n for c in s:\n if c == '0':\n t += '01'\n else:\n t += '10'\n print(t)\n return t\ns = helper(n)\nreturn int(s[k - 1])",
"if n == 1:\n return 0\nif n == 2:\n if k == 1:\n ... | <|body_start_0|>
def helper(i):
if i == 1:
return '0'
s = helper(i - 1)
t = ''
for c in s:
if c == '0':
t += '01'
else:
t += '10'
print(t)
return t
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kthGrammar(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def helper(i):
if i == 1... | stack_v2_sparse_classes_10k_train_005182 | 1,902 | no_license | [
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kthGrammarTLE",
"signature": "def kthGrammarTLE(self, n, k)"
},
{
"docstring": ":type n: int :type k: int :rtype: int",
"name": "kthGrammar",
"signature": "def kthGrammar(self, n, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammarTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kthGrammar(self, n, k): :type n: int :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthGrammarTLE(self, n, k): :type n: int :type k: int :rtype: int
- def kthGrammar(self, n, k): :type n: int :type k: int :rtype: int
<|skeleton|>
class Solution:
def kt... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_0|>
def kthGrammar(self, n, k):
""":type n: int :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def kthGrammarTLE(self, n, k):
""":type n: int :type k: int :rtype: int"""
def helper(i):
if i == 1:
return '0'
s = helper(i - 1)
t = ''
for c in s:
if c == '0':
t += '01'
... | the_stack_v2_python_sparse | K/K-thSymbolinGrammar.py | bssrdf/pyleet | train | 2 | |
2e4425708b5b83bcb5a806ae0f01bfee33d19fe6 | [
"super(ClusterDeploymentConfigs, self).__init__()\nself.log = logger.setup_logging(self.__class__.__name__)\nself.schema_class = 'cluster_deployment_configs_schema.ClusterDeploymentConfigsSchema'\nself.set_connection(service.get_connection())\nself.create_endpoint = 'si/deploy'\nself.delete_endpoint = 'si/deploy/' ... | <|body_start_0|>
super(ClusterDeploymentConfigs, self).__init__()
self.log = logger.setup_logging(self.__class__.__name__)
self.schema_class = 'cluster_deployment_configs_schema.ClusterDeploymentConfigsSchema'
self.set_connection(service.get_connection())
self.create_endpoint = '... | ClusterDeploymentConfigs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
<|body_0|>
def delete(self, schema_object=None):
"""Over riding delete met... | stack_v2_sparse_classes_10k_train_005183 | 1,442 | no_license | [
{
"docstring": "Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured",
"name": "__init__",
"signature": "def __init__(self, service=None)"
},
{
"docstring": "Over riding delete method to perform DELETE operation",
"nam... | 2 | stack_v2_sparse_classes_30k_train_000586 | Implement the Python class `ClusterDeploymentConfigs` described below.
Class description:
Implement the ClusterDeploymentConfigs class.
Method signatures and docstrings:
- def __init__(self, service=None): Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to... | Implement the Python class `ClusterDeploymentConfigs` described below.
Class description:
Implement the ClusterDeploymentConfigs class.
Method signatures and docstrings:
- def __init__(self, service=None): Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
<|body_0|>
def delete(self, schema_object=None):
"""Over riding delete met... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClusterDeploymentConfigs:
def __init__(self, service=None):
"""Constructor to create ClusterDeploymentConfigs object @param vsm object on which ClusterDeploymentConfigs has to be configured"""
super(ClusterDeploymentConfigs, self).__init__()
self.log = logger.setup_logging(self.__class... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/service_insertion/cluster_deployment_configs.py | Cloudxtreme/MyProject | train | 0 | |
ebc4265b7bec08003fc3b39970afb794a2f91c94 | [
"size = len(nums)\nif size == 0 or k <= 0:\n return\nk = k % len(nums)\nself.__reverse(nums, 0, size - 1)\nself.__reverse(nums, 0, k - 1)\nself.__reverse(nums, k, size - 1)",
"while index1 < index2:\n nums[index1], nums[index2] = (nums[index2], nums[index1])\n index1 += 1\n index2 -= 1"
] | <|body_start_0|>
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1)
self.__reverse(nums, k, size - 1)
<|end_body_0|>
<|body_start_1|>
while index1 < index2:
nu... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_10k_train_005184 | 1,050 | permissive | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "rotate",
"signature": "def rotate(self, nums: List[int], k: int) -> None"
},
{
"docstring": "将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:",
"name": "__reverse",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_001985 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, nums: List[int], k: int) -> None: Do not return anything, modify nums in-place instead.
- def __reverse(self, nums, index1, index2): 将数组 [index1,index2] 区间内的元素进行... | baabdb1990fd49ab82a712e121f49c4f68b29459 | <|skeleton|>
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def __reverse(self, nums, index1, index2):
"""将数组 [index1,index2] 区间内的元素进行逆转 :param nums: :param index1: :param index2: :return:"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""Do not return anything, modify nums in-place instead."""
size = len(nums)
if size == 0 or k <= 0:
return
k = k % len(nums)
self.__reverse(nums, 0, size - 1)
self.__reverse(nums, 0, k - 1... | the_stack_v2_python_sparse | array/Python/0189-rotate-array.py | lemonnader/LeetCode-Solution-Well-Formed | train | 1 | |
023c4e27374b241b364035cf7e75fa64c29dd7de | [
"parser.display_info.AddFormat(bare_metal_constants.BARE_METAL_STANDALONE_CLUSTERS_FORMAT)\nstandalone_cluster_flags.AddStandaloneClusterResourceArg(parser, verb='to update', positional=True)\nbase.ASYNC_FLAG.AddToParser(parser)\nstandalone_cluster_flags.AddValidationOnly(parser)\nstandalone_cluster_flags.AddAllowM... | <|body_start_0|>
parser.display_info.AddFormat(bare_metal_constants.BARE_METAL_STANDALONE_CLUSTERS_FORMAT)
standalone_cluster_flags.AddStandaloneClusterResourceArg(parser, verb='to update', positional=True)
base.ASYNC_FLAG.AddToParser(parser)
standalone_cluster_flags.AddValidationOnly(pa... | Update an Anthos on bare metal standalone cluster. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update an Anthos on bare metal standalone cluster."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
<|body_0|>
def Run(self, args):
... | stack_v2_sparse_classes_10k_train_005185 | 4,069 | permissive | [
{
"docstring": "Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to.",
"name": "Args",
"signature": "def Args(parser: parser_arguments.ArgumentInterceptor)"
},
{
"docstring": "Runs the update command. Args: args: The arguments received from... | 2 | null | Implement the Python class `Update` described below.
Class description:
Update an Anthos on bare metal standalone cluster.
Method signatures and docstrings:
- def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the fla... | Implement the Python class `Update` described below.
Class description:
Update an Anthos on bare metal standalone cluster.
Method signatures and docstrings:
- def Args(parser: parser_arguments.ArgumentInterceptor): Gathers command line arguments for the update command. Args: parser: The argparse parser to add the fla... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update an Anthos on bare metal standalone cluster."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
<|body_0|>
def Run(self, args):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Update:
"""Update an Anthos on bare metal standalone cluster."""
def Args(parser: parser_arguments.ArgumentInterceptor):
"""Gathers command line arguments for the update command. Args: parser: The argparse parser to add the flag to."""
parser.display_info.AddFormat(bare_metal_constants.BA... | the_stack_v2_python_sparse | lib/surface/container/bare_metal/standalone_clusters/update.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
1ded29b013b3c8fc349828d6d63c7b41d569efb8 | [
"super(RandAugmentation, self).__init__(n_level)\nself.n_select = n_select\nself.level = level if type(level) is int and 0 <= level < n_level else None\nself.transforms = transforms",
"chosen_transforms = random.sample(self.transforms, k=self.n_select)\nfor transf in chosen_transforms:\n level = self.level if ... | <|body_start_0|>
super(RandAugmentation, self).__init__(n_level)
self.n_select = n_select
self.level = level if type(level) is int and 0 <= level < n_level else None
self.transforms = transforms
<|end_body_0|>
<|body_start_1|>
chosen_transforms = random.sample(self.transforms, k... | Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719) | RandAugmentation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandAugmentation:
"""Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719)"""
def __init__(self, transforms: List[str], n_select: int=2, level: int=14, n_level: int=31) -> None:
"""Init... | stack_v2_sparse_classes_10k_train_005186 | 5,467 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, transforms: List[str], n_select: int=2, level: int=14, n_level: int=31) -> None"
},
{
"docstring": "Run augmentations.",
"name": "__call__",
"signature": "def __call__(self, img: Image) -> Image"
}
] | 2 | stack_v2_sparse_classes_30k_val_000179 | Implement the Python class `RandAugmentation` described below.
Class description:
Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719)
Method signatures and docstrings:
- def __init__(self, transforms: List[str], n_sel... | Implement the Python class `RandAugmentation` described below.
Class description:
Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719)
Method signatures and docstrings:
- def __init__(self, transforms: List[str], n_sel... | 88bcff70e93dd68058a5cf0dfeac119a57abc6de | <|skeleton|>
class RandAugmentation:
"""Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719)"""
def __init__(self, transforms: List[str], n_select: int=2, level: int=14, n_level: int=31) -> None:
"""Init... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RandAugmentation:
"""Random augmentation class. References: RandAugment: Practical automated data augmentation with a reduced search space (https://arxiv.org/abs/1909.13719)"""
def __init__(self, transforms: List[str], n_select: int=2, level: int=14, n_level: int=31) -> None:
"""Initialize."""
... | the_stack_v2_python_sparse | src/augmentation/methods.py | scott-mao/DenseDepth_Pruning | train | 1 |
cece3091c1a56091f60fd4fcacc1f6469411addc | [
"try:\n dst_state = Status.objects.get(id=self.context.get('dst_state'))\nexcept Status.DoesNotExist:\n self.data.set_outputs('message', '对应的节点不存在')\n return False\nprocessors = self.data.get_one_of_inputs('processors')\nif not processors:\n self.data.set_outputs('message', '设置处理人为空')\n return False\... | <|body_start_0|>
try:
dst_state = Status.objects.get(id=self.context.get('dst_state'))
except Status.DoesNotExist:
self.data.set_outputs('message', '对应的节点不存在')
return False
processors = self.data.get_one_of_inputs('processors')
if not processors:
... | ModifyProcessorComponent | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModifyProcessorComponent:
def _execute(self):
"""修改节点对应的处理人"""
<|body_0|>
def update_context(self):
"""手动操作的时候更新context"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
dst_state = Status.objects.get(id=self.context.get('dst_state'))... | stack_v2_sparse_classes_10k_train_005187 | 3,288 | permissive | [
{
"docstring": "修改节点对应的处理人",
"name": "_execute",
"signature": "def _execute(self)"
},
{
"docstring": "手动操作的时候更新context",
"name": "update_context",
"signature": "def update_context(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005046 | Implement the Python class `ModifyProcessorComponent` described below.
Class description:
Implement the ModifyProcessorComponent class.
Method signatures and docstrings:
- def _execute(self): 修改节点对应的处理人
- def update_context(self): 手动操作的时候更新context | Implement the Python class `ModifyProcessorComponent` described below.
Class description:
Implement the ModifyProcessorComponent class.
Method signatures and docstrings:
- def _execute(self): 修改节点对应的处理人
- def update_context(self): 手动操作的时候更新context
<|skeleton|>
class ModifyProcessorComponent:
def _execute(self):... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class ModifyProcessorComponent:
def _execute(self):
"""修改节点对应的处理人"""
<|body_0|>
def update_context(self):
"""手动操作的时候更新context"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModifyProcessorComponent:
def _execute(self):
"""修改节点对应的处理人"""
try:
dst_state = Status.objects.get(id=self.context.get('dst_state'))
except Status.DoesNotExist:
self.data.set_outputs('message', '对应的节点不存在')
return False
processors = self.data.... | the_stack_v2_python_sparse | itsm/trigger/action/components/modify_processor.py | TencentBlueKing/bk-itsm | train | 100 | |
a314e9d42e749bc9a4413b8e445c96c4ab1a3ace | [
"super(InTriggerDistanceToNextIntersection, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._distance = distance\nself._map = CarlaDataProvider.get_map()\nwaypoint = self._map.get_waypoint(self._actor.get_location())\nwhile waypoint and (not waypoint.is_... | <|body_start_0|>
super(InTriggerDistanceToNextIntersection, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._distance = distance
self._map = CarlaDataProvider.get_map()
waypoint = self._map.get_waypoint(self._acto... | This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger distance between the actor and the next intersection in meters The condition terminates with SUCCESS, whe... | InTriggerDistanceToNextIntersection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger distance between the actor and the next in... | stack_v2_sparse_classes_10k_train_005188 | 18,494 | permissive | [
{
"docstring": "Setup trigger distance",
"name": "__init__",
"signature": "def __init__(self, actor, distance, name='InTriggerDistanceToNextIntersection')"
},
{
"docstring": "Check if the actor is within trigger distance to the intersection",
"name": "update",
"signature": "def update(se... | 2 | stack_v2_sparse_classes_30k_train_006720 | Implement the Python class `InTriggerDistanceToNextIntersection` described below.
Class description:
This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger dis... | Implement the Python class `InTriggerDistanceToNextIntersection` described below.
Class description:
This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger dis... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger distance between the actor and the next in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InTriggerDistanceToNextIntersection:
"""This class contains the trigger (condition) for a distance to the next intersection of a scenario Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - distance: Trigger distance between the actor and the next intersection in... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_trigger_conditions.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
8f2a0d2c2b781211f13f6f848aab6fd0e9ae5529 | [
"super(Inverter, self).__init__()\nself.add_param('inverter_efficiency', 1.0, desc='power out / power in')\nself.add_param('output_voltage', 120.0, desc='amplitude of AC output voltage', units='V')\nself.add_param('output_current', 2.0, desc='amplitude of AC output current', units='A')\nself.add_param('output_frequ... | <|body_start_0|>
super(Inverter, self).__init__()
self.add_param('inverter_efficiency', 1.0, desc='power out / power in')
self.add_param('output_voltage', 120.0, desc='amplitude of AC output voltage', units='V')
self.add_param('output_current', 2.0, desc='amplitude of AC output current',... | The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (W) output_voltage : float amplitude of AC output voltage (A) output_current... | Inverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Inverter:
"""The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (W) output_voltage : float amplitude of ... | stack_v2_sparse_classes_10k_train_005189 | 3,116 | permissive | [
{
"docstring": "Initializes a `Inverter` object Sets up the given Params/Outputs of the OpenMDAO `Inverter` component, initializes their shape, and sets them to their default values.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Runs the `Battery` component and sets ... | 2 | stack_v2_sparse_classes_30k_train_005799 | Implement the Python class `Inverter` described below.
Class description:
The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (... | Implement the Python class `Inverter` described below.
Class description:
The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (... | ac6261ffc2926cc4041185563044de3dac0101e6 | <|skeleton|>
class Inverter:
"""The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (W) output_voltage : float amplitude of ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Inverter:
"""The `Inverter` class represents a BLDC inverter in an OpenMDAO model The `Inverter` class models the efficiency loss across a typical BLDC inverter following the example from [1]_. Params ------ inverter_efficiency : float power out / power in (W) output_voltage : float amplitude of AC output vol... | the_stack_v2_python_sparse | src/hyperloop/Python/pod/drivetrain/inverter.py | HamzaRabi/MagnePlane | train | 0 |
cb9c469d1df50f59a1b1673c45f39db7aaf992f0 | [
"self.branch = 'master'\nself.fix = False\nsuper(lint, self).initialize_options()",
"cmd = 'black .'\ncmd = cmd.format(branch=self.branch)\nself.call_and_exit(self.apply_options(cmd, ('fix',)))"
] | <|body_start_0|>
self.branch = 'master'
self.fix = False
super(lint, self).initialize_options()
<|end_body_0|>
<|body_start_1|>
cmd = 'black .'
cmd = cmd.format(branch=self.branch)
self.call_and_exit(self.apply_options(cmd, ('fix',)))
<|end_body_1|>
| A PEP 8 lint command that optionally fixes violations. | lint | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lint:
"""A PEP 8 lint command that optionally fixes violations."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the linter."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.branch = 'master'
... | stack_v2_sparse_classes_10k_train_005190 | 3,851 | permissive | [
{
"docstring": "Set the default options.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Run the linter.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005810 | Implement the Python class `lint` described below.
Class description:
A PEP 8 lint command that optionally fixes violations.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the linter. | Implement the Python class `lint` described below.
Class description:
A PEP 8 lint command that optionally fixes violations.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the linter.
<|skeleton|>
class lint:
"""A PEP 8 lint command that optionally... | 4e2c417f68bc07c72b508e107431569b0783c4ef | <|skeleton|>
class lint:
"""A PEP 8 lint command that optionally fixes violations."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the linter."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class lint:
"""A PEP 8 lint command that optionally fixes violations."""
def initialize_options(self):
"""Set the default options."""
self.branch = 'master'
self.fix = False
super(lint, self).initialize_options()
def run(self):
"""Run the linter."""
cmd = 'b... | the_stack_v2_python_sparse | tasks.py | dbcli/cli_helpers | train | 102 |
5e64c07affa1968ea878f4be27f9d4baa44c9ec0 | [
"if model == FilterRecordingTracking:\n return 'db_rest_api'\nreturn None",
"if model == FilterRecordingTracking:\n return 'db_rest_api'\nreturn None"
] | <|body_start_0|>
if model == FilterRecordingTracking:
return 'db_rest_api'
return None
<|end_body_0|>
<|body_start_1|>
if model == FilterRecordingTracking:
return 'db_rest_api'
return None
<|end_body_1|>
| CloudDBRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudDBRouter:
def db_for_read(self, model, **hints):
"""reading FilterRecordingTracking from barc-prod"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing FilterRecordingTracking to barc-prod"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_005191 | 649 | no_license | [
{
"docstring": "reading FilterRecordingTracking from barc-prod",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "writing FilterRecordingTracking to barc-prod",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
}... | 2 | stack_v2_sparse_classes_30k_train_003238 | Implement the Python class `CloudDBRouter` described below.
Class description:
Implement the CloudDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading FilterRecordingTracking from barc-prod
- def db_for_write(self, model, **hints): writing FilterRecordingTracking to barc-... | Implement the Python class `CloudDBRouter` described below.
Class description:
Implement the CloudDBRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): reading FilterRecordingTracking from barc-prod
- def db_for_write(self, model, **hints): writing FilterRecordingTracking to barc-... | d084c6146de114823f68046fd4a57fe04544a403 | <|skeleton|>
class CloudDBRouter:
def db_for_read(self, model, **hints):
"""reading FilterRecordingTracking from barc-prod"""
<|body_0|>
def db_for_write(self, model, **hints):
"""writing FilterRecordingTracking to barc-prod"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CloudDBRouter:
def db_for_read(self, model, **hints):
"""reading FilterRecordingTracking from barc-prod"""
if model == FilterRecordingTracking:
return 'db_rest_api'
return None
def db_for_write(self, model, **hints):
"""writing FilterRecordingTracking to barc-p... | the_stack_v2_python_sparse | dashboard/rest_api/dbrouters.py | teraflik/ao-tv-recording-dashboard | train | 1 | |
7a9b1a72eb2a54ce2149918a02825b03d76a9b17 | [
"if len(nums1) < len(nums2):\n self.intersect(nums2, nums1)\nd_nums, res = ({}, [])\nfor num in nums2:\n if num not in d_nums:\n d_nums[num] = 1\n else:\n d_nums[num] += 1\nfor num in nums1:\n if num in d_nums and d_nums[num] > 0:\n res.append(num)\n d_nums[num] -= 1\nreturn ... | <|body_start_0|>
if len(nums1) < len(nums2):
self.intersect(nums2, nums1)
d_nums, res = ({}, [])
for num in nums2:
if num not in d_nums:
d_nums[num] = 1
else:
d_nums[num] += 1
for num in nums1:
if num in d_nu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersectSorted(self, nums1, nums2):
"""Follow up - sorted arrays"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if le... | stack_v2_sparse_classes_10k_train_005192 | 1,833 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(self, nums1, nums2)"
},
{
"docstring": "Follow up - sorted arrays",
"name": "intersectSorted",
"signature": "def intersectSorted(self, nums1, nums2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005466 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersectSorted(self, nums1, nums2): Follow up - sorted arrays | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersectSorted(self, nums1, nums2): Follow up - sorted arrays
<|skeleto... | abd7e0f1869f94bd1c663f1eb3268c1603a73c62 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersectSorted(self, nums1, nums2):
"""Follow up - sorted arrays"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
if len(nums1) < len(nums2):
self.intersect(nums2, nums1)
d_nums, res = ({}, [])
for num in nums2:
if num not in d_nums:
d_n... | the_stack_v2_python_sparse | Sorting/350.IntersectionOfTwoArraysII.py | shreyasabharwal/Data-Structures-and-Algorithms | train | 0 | |
fe7db0c87f6dc5a5471c1f07560a9fb0da7b0ea6 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('xcao19', 'xcao19')\nurl = 'https://data.boston.gov/dataset/52b0fdad-4037-460c-9c92-290f5774ab2b/resource/c2fcc1e3-c38f-44ad-a0cf-e5ea2a6585b5/download/streetlight-locations.csv'\ndf = pd.read_csv(url, en... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'https://data.boston.gov/dataset/52b0fdad-4037-460c-9c92-290f5774ab2b/resource/c2fcc1e3-c38f-44ad-a0cf-e5ea2a6585b5/download/stre... | streetlights | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class streetlights:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_10k_train_005193 | 3,325 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `streetlights` described below.
Class description:
Implement the streetlights class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `streetlights` described below.
Class description:
Implement the streetlights class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class streetlights:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class streetlights:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('xcao19', 'xcao19')
url = 'http... | the_stack_v2_python_sparse | xcao19/streetlights.py | maximega/course-2019-spr-proj | train | 2 | |
486119251afaf2bf1b149bb814c9c35059dac0a7 | [
"def help(nums, idx, step):\n if len(nums) - 1 - idx <= step:\n return True\n for i in range(step, 0, -1):\n if nums[idx + i] and help(nums, idx + i, nums[idx + i]):\n return True\n return False\nreturn help(nums, 0, nums[0])",
"if len(nums) == 1:\n return True\nstack = [[0, s... | <|body_start_0|>
def help(nums, idx, step):
if len(nums) - 1 - idx <= step:
return True
for i in range(step, 0, -1):
if nums[idx + i] and help(nums, idx + i, nums[idx + i]):
return True
return False
return help(nums,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body... | stack_v2_sparse_classes_10k_train_005194 | 1,254 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump1",
"signature": "def canJump1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "canJump2",
"signature": "def canJump2(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bo... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtyp... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump1(self, nums): :type nums: List[int] :rtype: bool
- def canJump2(self, nums): :type nums: List[int] :rtype: bool
- def canJump(self, nums): :type nums: List[int] :rtyp... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def canJump2(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
def canJump(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump1(self, nums):
""":type nums: List[int] :rtype: bool"""
def help(nums, idx, step):
if len(nums) - 1 - idx <= step:
return True
for i in range(step, 0, -1):
if nums[idx + i] and help(nums, idx + i, nums[idx + i]):
... | the_stack_v2_python_sparse | py/leetcode/55.py | wfeng1991/learnpy | train | 0 | |
59cb629ba2c0377424c24dad821472ceb67d22e2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn NetworkConnection()",
"from .connection_direction import ConnectionDirection\nfrom .connection_status import ConnectionStatus\nfrom .security_network_protocol import SecurityNetworkProtocol\nfrom .connection_direction import Connection... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return NetworkConnection()
<|end_body_0|>
<|body_start_1|>
from .connection_direction import ConnectionDirection
from .connection_status import ConnectionStatus
from .security_network_p... | NetworkConnection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""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... | stack_v2_sparse_classes_10k_train_005195 | 9,109 | 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: NetworkConnection",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_v... | 3 | null | Implement the Python class `NetworkConnection` described below.
Class description:
Implement the NetworkConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim... | Implement the Python class `NetworkConnection` described below.
Class description:
Implement the NetworkConnection class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection: Creates a new instance of the appropriate class based on discrim... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""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... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NetworkConnection:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> NetworkConnection:
"""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: Netw... | the_stack_v2_python_sparse | msgraph/generated/models/network_connection.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ce5ff41227402d99412c197b2dcfd4a113492449 | [
"super(FLAMELayer, self).__init__(*args, **kwargs)\nself.keypoint_src = keypoint_src\nself.keypoint_dst = keypoint_dst\nself.keypoint_approximate = keypoint_approximate\nself.num_verts = self.get_num_verts()\nself.num_faces = self.get_num_faces()\nself.num_joints = get_keypoint_num(convention=self.keypoint_dst)",
... | <|body_start_0|>
super(FLAMELayer, self).__init__(*args, **kwargs)
self.keypoint_src = keypoint_src
self.keypoint_dst = keypoint_dst
self.keypoint_approximate = keypoint_approximate
self.num_verts = self.get_num_verts()
self.num_faces = self.get_num_faces()
self.n... | Extension of the official FLAME implementation. | FLAMELayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FLAMELayer:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source conventio... | stack_v2_sparse_classes_10k_train_005196 | 6,673 | permissive | [
{
"docstring": "Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoints. This convention is used for keypoints obtained from joint regressors. Keypoints then undergo conversion into keypoint_dst convention. keypoint_dst: destination convention of keypoints. This conve... | 2 | null | Implement the Python class `FLAMELayer` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments... | Implement the Python class `FLAMELayer` described below.
Class description:
Extension of the official FLAME implementation.
Method signatures and docstrings:
- def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs): Args: *args: extra arguments... | 9431addec32f7fbeffa1786927a854c0ab79d9ea | <|skeleton|>
class FLAMELayer:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source conventio... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FLAMELayer:
"""Extension of the official FLAME implementation."""
def __init__(self, *args, keypoint_src: str='flame', keypoint_dst: str='human_data', keypoint_approximate: bool=False, **kwargs):
"""Args: *args: extra arguments for FLAME initialization. keypoint_src: source convention of keypoint... | the_stack_v2_python_sparse | mmhuman3d/models/body_models/flame.py | open-mmlab/mmhuman3d | train | 966 |
3123aad781f1a9807f44a457bcb363888ba070e3 | [
"if not head or not head.next:\n return head\ndummy = cur = ListNode(0, head)\nwhile head and head.next:\n if head.val == head.next.val:\n while head and head.next and (head.val == head.next.val):\n head = head.next\n head = head.next\n cur.next = head\n else:\n cur =... | <|body_start_0|>
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while head and head.next:
if head.val == head.next.val:
while head and head.next and (head.val == head.next.val):
head = head.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head or not head.ne... | stack_v2_sparse_classes_10k_train_005197 | 1,636 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates1",
"signature": "def deleteDuplicates1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000231 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates1(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteDuplicates1(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while head and head.next:
if head.val == head.next.val:
while head and head... | the_stack_v2_python_sparse | out/production/leetcode/82.删除排序链表中的重复元素-ii.py | yangyuxiang1996/leetcode | train | 0 | |
86874b155c89d6239930c16fd87d8d38991d0438 | [
"guild_id = get_guild_id(guild)\nuser_id = get_user_id(user)\nassert _assert__guild_ban_add__delete_message_duration(delete_message_duration)\ndata = {}\nif delete_message_duration > 0:\n if delete_message_duration > 604800:\n delete_message_duration = 604800\n data['delete_message_seconds'] = delete_m... | <|body_start_0|>
guild_id = get_guild_id(guild)
user_id = get_user_id(user)
assert _assert__guild_ban_add__delete_message_duration(delete_message_duration)
data = {}
if delete_message_duration > 0:
if delete_message_duration > 604800:
delete_message_du... | ClientCompoundGuildBanEndpoints | [
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientCompoundGuildBanEndpoints:
async def guild_ban_add(self, guild, user, *, delete_message_duration=0, reason=None):
"""Bans the given user from the guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild from where the user will be banned. user : `... | stack_v2_sparse_classes_10k_train_005198 | 9,134 | permissive | [
{
"docstring": "Bans the given user from the guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild from where the user will be banned. user : ``ClientUserBase``, `int` The user to ban from the guild. delete_message_duration : `int` = `0`, Optional (Keyword only) How much se... | 5 | null | Implement the Python class `ClientCompoundGuildBanEndpoints` described below.
Class description:
Implement the ClientCompoundGuildBanEndpoints class.
Method signatures and docstrings:
- async def guild_ban_add(self, guild, user, *, delete_message_duration=0, reason=None): Bans the given user from the guild. This meth... | Implement the Python class `ClientCompoundGuildBanEndpoints` described below.
Class description:
Implement the ClientCompoundGuildBanEndpoints class.
Method signatures and docstrings:
- async def guild_ban_add(self, guild, user, *, delete_message_duration=0, reason=None): Bans the given user from the guild. This meth... | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | <|skeleton|>
class ClientCompoundGuildBanEndpoints:
async def guild_ban_add(self, guild, user, *, delete_message_duration=0, reason=None):
"""Bans the given user from the guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild from where the user will be banned. user : `... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClientCompoundGuildBanEndpoints:
async def guild_ban_add(self, guild, user, *, delete_message_duration=0, reason=None):
"""Bans the given user from the guild. This method is a coroutine. Parameters ---------- guild : ``Guild``, `int` The guild from where the user will be banned. user : ``ClientUserBas... | the_stack_v2_python_sparse | hata/discord/client/compounds/guild_ban.py | HuyaneMatsu/hata | train | 3 | |
f1d587037d67f00fc090604e9bd7d81ab1dc1bc3 | [
"if data is None:\n if n < 1:\n raise ValueError('n must be a positive value')\n if p <= 0 or p >= 1:\n raise ValueError('p must be greater than 0 and less than 1')\n self.n = n\n self.p = p\nelse:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if ... | <|body_start_0|>
if data is None:
if n < 1:
raise ValueError('n must be a positive value')
if p <= 0 or p >= 1:
raise ValueError('p must be greater than 0 and less than 1')
self.n = n
self.p = p
else:
if not isin... | The Binomial Class | Binomial | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Binomial:
"""The Binomial Class"""
def __init__(self, data=None, n=1, p=0.5):
"""Init of n, for number of trials, and p, probability of success"""
<|body_0|>
def factorial(self, n):
"""n factorial"""
<|body_1|>
def pmf(self, k):
"""The PMF of... | stack_v2_sparse_classes_10k_train_005199 | 1,863 | no_license | [
{
"docstring": "Init of n, for number of trials, and p, probability of success",
"name": "__init__",
"signature": "def __init__(self, data=None, n=1, p=0.5)"
},
{
"docstring": "n factorial",
"name": "factorial",
"signature": "def factorial(self, n)"
},
{
"docstring": "The PMF of ... | 4 | stack_v2_sparse_classes_30k_train_004110 | Implement the Python class `Binomial` described below.
Class description:
The Binomial Class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Init of n, for number of trials, and p, probability of success
- def factorial(self, n): n factorial
- def pmf(self, k): The PMF of a binomial dis... | Implement the Python class `Binomial` described below.
Class description:
The Binomial Class
Method signatures and docstrings:
- def __init__(self, data=None, n=1, p=0.5): Init of n, for number of trials, and p, probability of success
- def factorial(self, n): n factorial
- def pmf(self, k): The PMF of a binomial dis... | 4200798bdbbe828db94e5585b62a595e3a96c3e6 | <|skeleton|>
class Binomial:
"""The Binomial Class"""
def __init__(self, data=None, n=1, p=0.5):
"""Init of n, for number of trials, and p, probability of success"""
<|body_0|>
def factorial(self, n):
"""n factorial"""
<|body_1|>
def pmf(self, k):
"""The PMF of... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Binomial:
"""The Binomial Class"""
def __init__(self, data=None, n=1, p=0.5):
"""Init of n, for number of trials, and p, probability of success"""
if data is None:
if n < 1:
raise ValueError('n must be a positive value')
if p <= 0 or p >= 1:
... | the_stack_v2_python_sparse | math/0x03-probability/binomial.py | JohnCook17/holbertonschool-machine_learning | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.