blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c57ff9c6ae888e8c5f8df102f0f835ad4df175da | [
"self.line_style = line_style\nself.has_fill = has_fill\nself.fill_colour = fill_colour",
"plt.title(title)\nplt.xlabel(labels[0])\nplt.ylabel(labels[1])\nif self.has_fill:\n plt.plot(data[0], data[1], self.line_style)\n plt.fill_between(data[0], data[1], color=f'{self.fill_colour}')\nelse:\n plt.plot(da... | <|body_start_0|>
self.line_style = line_style
self.has_fill = has_fill
self.fill_colour = fill_colour
<|end_body_0|>
<|body_start_1|>
plt.title(title)
plt.xlabel(labels[0])
plt.ylabel(labels[1])
if self.has_fill:
plt.plot(data[0], data[1], self.line_s... | Represents an object that generates a line graph when it is called and executed as a function | LineGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineGraph:
"""Represents an object that generates a line graph when it is called and executed as a function"""
def __init__(self, line_style, has_fill=False, fill_colour=None):
"""Initializes a LineGraph object :param line_style: style of a line in a line graph as a String :param has... | stack_v2_sparse_classes_36k_train_028800 | 5,075 | no_license | [
{
"docstring": "Initializes a LineGraph object :param line_style: style of a line in a line graph as a String :param has_fill: tells if a line graph has a fill as a Bool :param fill_colour: colour of the fill as a String",
"name": "__init__",
"signature": "def __init__(self, line_style, has_fill=False, ... | 2 | stack_v2_sparse_classes_30k_train_001110 | Implement the Python class `LineGraph` described below.
Class description:
Represents an object that generates a line graph when it is called and executed as a function
Method signatures and docstrings:
- def __init__(self, line_style, has_fill=False, fill_colour=None): Initializes a LineGraph object :param line_styl... | Implement the Python class `LineGraph` described below.
Class description:
Represents an object that generates a line graph when it is called and executed as a function
Method signatures and docstrings:
- def __init__(self, line_style, has_fill=False, fill_colour=None): Initializes a LineGraph object :param line_styl... | e4953c9a4f574a6d92cbd0815e5150dd1523c31d | <|skeleton|>
class LineGraph:
"""Represents an object that generates a line graph when it is called and executed as a function"""
def __init__(self, line_style, has_fill=False, fill_colour=None):
"""Initializes a LineGraph object :param line_style: style of a line in a line graph as a String :param has... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineGraph:
"""Represents an object that generates a line graph when it is called and executed as a function"""
def __init__(self, line_style, has_fill=False, fill_colour=None):
"""Initializes a LineGraph object :param line_style: style of a line in a line graph as a String :param has_fill: tells ... | the_stack_v2_python_sparse | Labs/Lab9/observers.py | kchung90/Python-Labs-Assignments | train | 0 |
15c03825c09659da332b38f23e0a9cce5a41a374 | [
"if nvars is None:\n nvars = [(2, 300)]\nsuper().__init__((nvars, None, np.dtype('float64')))\nself._makeAttributeAndRegister('nvars', 'cs', 'cadv', 'order_adv', 'waveno', localVars=locals(), readOnly=True)\nself.mesh = np.linspace(0.0, 1.0, self.nvars[1], endpoint=False)\nself.dx = self.mesh[1] - self.mesh[0]\n... | <|body_start_0|>
if nvars is None:
nvars = [(2, 300)]
super().__init__((nvars, None, np.dtype('float64')))
self._makeAttributeAndRegister('nvars', 'cs', 'cadv', 'order_adv', 'waveno', localVars=locals(), readOnly=True)
self.mesh = np.linspace(0.0, 1.0, self.nvars[1], endpoint... | This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\partial x} + U \\frac{\\partial u}{\\partial x} = 0, .. math:: \\frac{\\partial p}{\\pa... | acoustic_1d_imex | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class acoustic_1d_imex:
"""This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\partial x} + U \\frac{\\partial u}{\\partia... | stack_v2_sparse_classes_36k_train_028801 | 6,436 | permissive | [
{
"docstring": "Initialization routine",
"name": "__init__",
"signature": "def __init__(self, nvars=None, cs=0.5, cadv=0.1, order_adv=5, waveno=5)"
},
{
"docstring": "Simple linear solver for :math:`(I-factor\\\\cdot A)\\\\vec{u}=\\\\vec{rhs}`. Parameters ---------- rhs : dtype_f Right-hand side... | 6 | null | Implement the Python class `acoustic_1d_imex` described below.
Class description:
This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\part... | Implement the Python class `acoustic_1d_imex` described below.
Class description:
This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\part... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class acoustic_1d_imex:
"""This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\partial x} + U \\frac{\\partial u}{\\partia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class acoustic_1d_imex:
"""This class implements the one-dimensional acoustics advection equation on a periodic domain :math:`[0, 1]` fully investigated in [1]_. The equations are given by .. math:: \\frac{\\partial u}{\\partial t} + c_s \\frac{\\partial p}{\\partial x} + U \\frac{\\partial u}{\\partial x} = 0, .. ... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AcousticAdvection_1D_FD_imex.py | Parallel-in-Time/pySDC | train | 30 |
b706eeaa36af3986e9e2e68ec06176b593cb293a | [
"GC.read()\nif os.path.exists(CONFIG_OVERWRITE):\n cls.overwrite(CONFIG_OVERWRITE)",
"conf_overwrite: dict = GC.read_conf(config_file_overwrite)\nfor sec, attr in conf_overwrite.items():\n for key, val in attr.items():\n try:\n _ = GC.conf[sec][key]\n GC.conf[sec][key] = val\n ... | <|body_start_0|>
GC.read()
if os.path.exists(CONFIG_OVERWRITE):
cls.overwrite(CONFIG_OVERWRITE)
<|end_body_0|>
<|body_start_1|>
conf_overwrite: dict = GC.read_conf(config_file_overwrite)
for sec, attr in conf_overwrite.items():
for key, val in attr.items():
... | Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design reason. GlobalConfig should not depend on LOG_TYPE, but we have to depen... | GCO | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCO:
"""Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design reason. GlobalConfig should not depend on... | stack_v2_sparse_classes_36k_train_028802 | 6,236 | permissive | [
{
"docstring": "Overwrite version of read config file",
"name": "read",
"signature": "def read(cls)"
},
{
"docstring": "Update im-momory conf with the overwrite config file.",
"name": "overwrite",
"signature": "def overwrite(cls, config_file_overwrite: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013313 | Implement the Python class `GCO` described below.
Class description:
Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design re... | Implement the Python class `GCO` described below.
Class description:
Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design re... | 4dcb8a0044683372abb4bfad69fc4ba71162ecd5 | <|skeleton|>
class GCO:
"""Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design reason. GlobalConfig should not depend on... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GCO:
"""Handle overwrite config file. Take the module as helper instead of the derived class of GlobalConfig to be back compatible and avoid confusing. It only updates the global in-memory conf dict. It either cannot be merged with GlobalConfig for design reason. GlobalConfig should not depend on LOG_TYPE, bu... | the_stack_v2_python_sparse | analyzer/utils/data_helper.py | hayhan/loganalyzer | train | 2 |
363626baab2fe3537a41c2abff87689c56909432 | [
"li = [i for i in range(1, 10)]\nres = []\n\ndef helper(i, cnt, tmp):\n if sum(tmp) == n and cnt == k:\n res.append(tmp)\n return\n if sum(tmp) == n:\n return\n for j in range(i, 9):\n if cnt == k and li[j] + sum(tmp) < n or li[j] + sum(tmp) > n:\n break\n help... | <|body_start_0|>
li = [i for i in range(1, 10)]
res = []
def helper(i, cnt, tmp):
if sum(tmp) == n and cnt == k:
res.append(tmp)
return
if sum(tmp) == n:
return
for j in range(i, 9):
if cnt == k ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
li = ... | stack_v2_sparse_classes_36k_train_028803 | 1,436 | no_license | [
{
"docstring": ":type k: int :type n: int :rtype: List[List[int]]",
"name": "combinationSum3",
"signature": "def combinationSum3(self, k, n)"
},
{
"docstring": ":type k: int :type n: int :rtype: List[List[int]]",
"name": "combinationSum3",
"signature": "def combinationSum3(self, k, n)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]]
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]]
- def combinationSum3(self, k, n): :type k: int :type n: int :rtype: List[List[int]]
<|skeleto... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum3(self, k, n):
""":type k: int :type n: int :rtype: List[List[int]]"""
li = [i for i in range(1, 10)]
res = []
def helper(i, cnt, tmp):
if sum(tmp) == n and cnt == k:
res.append(tmp)
return
if ... | the_stack_v2_python_sparse | 0216_Combination_Sum_III.py | bingli8802/leetcode | train | 0 | |
28e43c66502a5eaf8c76f16e4afa94be7ad17a2c | [
"super(Test_relax_disp, self).__init__(methodName)\nself.interpreter = Interpreter(show_script=False, raise_relax_error=True)\nself.interpreter.populate_self()\nself.interpreter.on(verbose=False)\nself.relax_disp_fns = self.interpreter.relax_disp",
"for data in DATA_TYPES:\n if data[0] == 'float' or data[0] ==... | <|body_start_0|>
super(Test_relax_disp, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, raise_relax_error=True)
self.interpreter.populate_self()
self.interpreter.on(verbose=False)
self.relax_disp_fns = self.interpreter.relax_disp
<|end_body_0|>
<|bod... | Unit tests for the functions of the 'prompt.relax_disp' module. | Test_relax_disp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_relax_disp:
"""Unit tests for the functions of the 'prompt.relax_disp' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_cpmg_setup_argfail_cpmg_frq(self):
"""The cpmg_frq arg tes... | stack_v2_sparse_classes_36k_train_028804 | 4,406 | no_license | [
{
"docstring": "Set up the test case class for the system tests.",
"name": "__init__",
"signature": "def __init__(self, methodName=None)"
},
{
"docstring": "The cpmg_frq arg test of the relax_disp.cpmg_setup() user function.",
"name": "test_relax_cpmg_setup_argfail_cpmg_frq",
"signature"... | 5 | null | Implement the Python class `Test_relax_disp` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_disp' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_cpmg_setup_argfail_cpmg_frq(self):... | Implement the Python class `Test_relax_disp` described below.
Class description:
Unit tests for the functions of the 'prompt.relax_disp' module.
Method signatures and docstrings:
- def __init__(self, methodName=None): Set up the test case class for the system tests.
- def test_relax_cpmg_setup_argfail_cpmg_frq(self):... | c317326ddeacd1a1c608128769676899daeae531 | <|skeleton|>
class Test_relax_disp:
"""Unit tests for the functions of the 'prompt.relax_disp' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
<|body_0|>
def test_relax_cpmg_setup_argfail_cpmg_frq(self):
"""The cpmg_frq arg tes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_relax_disp:
"""Unit tests for the functions of the 'prompt.relax_disp' module."""
def __init__(self, methodName=None):
"""Set up the test case class for the system tests."""
super(Test_relax_disp, self).__init__(methodName)
self.interpreter = Interpreter(show_script=False, ra... | the_stack_v2_python_sparse | test_suite/unit_tests/_prompt/test_relax_disp.py | jlec/relax | train | 4 |
b8b94476b2c501435a07f857ba656bed407b769b | [
"location = coupon.offer.business.locations.all()[0]\ncoupon.location = [location]\nreturn location",
"current_create_count = 1\nwhile current_create_count < business_location_count:\n BUSINESS_LOCATION_FACTORY.create_business_location(coupon.offer.business)\n current_create_count += 1\nall_business_locatio... | <|body_start_0|>
location = coupon.offer.business.locations.all()[0]
coupon.location = [location]
return location
<|end_body_0|>
<|body_start_1|>
current_create_count = 1
while current_create_count < business_location_count:
BUSINESS_LOCATION_FACTORY.create_business_... | Coupon Location Factory Class | CouponLocationFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CouponLocationFactory:
"""Coupon Location Factory Class"""
def create_coupon_location(coupon):
"""Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This is already taken care of when create_business gets call i... | stack_v2_sparse_classes_36k_train_028805 | 4,502 | no_license | [
{
"docstring": "Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This is already taken care of when create_business gets call in the BUSINESS_FACTORY.",
"name": "create_coupon_location",
"signature": "def create_coupon_location(c... | 2 | null | Implement the Python class `CouponLocationFactory` described below.
Class description:
Coupon Location Factory Class
Method signatures and docstrings:
- def create_coupon_location(coupon): Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This ... | Implement the Python class `CouponLocationFactory` described below.
Class description:
Coupon Location Factory Class
Method signatures and docstrings:
- def create_coupon_location(coupon): Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This ... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class CouponLocationFactory:
"""Coupon Location Factory Class"""
def create_coupon_location(coupon):
"""Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This is already taken care of when create_business gets call i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CouponLocationFactory:
"""Coupon Location Factory Class"""
def create_coupon_location(coupon):
"""Associate one business_locations with this coupon. Requirement: A business must already have a location associated with it. This is already taken care of when create_business gets call in the BUSINES... | the_stack_v2_python_sparse | advertiser/factories/location_factory.py | wcirillo/ten | train | 0 |
b2a89a8459357d33b649e703c68ef30928f39a69 | [
"profile: Profile = get_profile_by_token(request)\nif not profile.has_valid_token:\n return INVALID_CREDENTIALS\nid_: str = request.query_params.get('id')\ntry:\n product: Product = Product.get_by_id(id_)\nexcept (ValueError, TypeError, Product.DoesNotExist):\n return PRODUCT_NOT_FOUND\nserializer = Produc... | <|body_start_0|>
profile: Profile = get_profile_by_token(request)
if not profile.has_valid_token:
return INVALID_CREDENTIALS
id_: str = request.query_params.get('id')
try:
product: Product = Product.get_by_id(id_)
except (ValueError, TypeError, Product.Doe... | ProductView provides handlers for different methods on single product. | ProductView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product... | stack_v2_sparse_classes_36k_train_028806 | 6,415 | no_license | [
{
"docstring": "Get info about product by its id. :param request: request with \"id\" field. :return: response whether request is successful with info about product.",
"name": "get",
"signature": "def get(self, request: Request) -> Response"
},
{
"docstring": "Edit product info. :param request: ... | 4 | stack_v2_sparse_classes_30k_train_010393 | Implement the Python class `ProductView` described below.
Class description:
ProductView provides handlers for different methods on single product.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Get info about product by its id. :param request: request with "id" field. :return: respo... | Implement the Python class `ProductView` described below.
Class description:
ProductView provides handlers for different methods on single product.
Method signatures and docstrings:
- def get(self, request: Request) -> Response: Get info about product by its id. :param request: request with "id" field. :return: respo... | ef31cba8656b66d8fdbdd6a947bcf00a3ad3f92a | <|skeleton|>
class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductView:
"""ProductView provides handlers for different methods on single product."""
def get(self, request: Request) -> Response:
"""Get info about product by its id. :param request: request with "id" field. :return: response whether request is successful with info about product."""
... | the_stack_v2_python_sparse | online-store/backend/views.py | TmLev/microservices | train | 1 |
9798a79d3bdd014c7dd5665e586c3322086d3eac | [
"self.SIZE = 300\nself.counts = [0] * self.SIZE\nself.times = [0] * self.SIZE",
"index = timestamp % self.SIZE - 1\nif self.times[index] != timestamp:\n self.counts[index] = 1\n self.times[index] = timestamp\nelse:\n self.counts[index] += 1",
"result = 0\nfor i in range(self.SIZE):\n if timestamp - ... | <|body_start_0|>
self.SIZE = 300
self.counts = [0] * self.SIZE
self.times = [0] * self.SIZE
<|end_body_0|>
<|body_start_1|>
index = timestamp % self.SIZE - 1
if self.times[index] != timestamp:
self.counts[index] = 1
self.times[index] = timestamp
e... | HitCounter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k_train_028807 | 23,575 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Record a hit. @param timestamp - The current timestamp (in seconds granularity).",
"name": "hit",
"signature": "def hit(self, timestamp: int) -> None"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_020688 | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | Implement the Python class `HitCounter` described below.
Class description:
Implement the HitCounter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def hit(self, timestamp: int) -> None: Record a hit. @param timestamp - The current timestamp (in seconds granulari... | 8c6cfdd951dc7d1363f1917404488fca0e7051f5 | <|skeleton|>
class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granularity)."""
<|body_1|>
def getHits(self, timestamp: in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HitCounter:
def __init__(self):
"""Initialize your data structure here."""
self.SIZE = 300
self.counts = [0] * self.SIZE
self.times = [0] * self.SIZE
def hit(self, timestamp: int) -> None:
"""Record a hit. @param timestamp - The current timestamp (in seconds granul... | the_stack_v2_python_sparse | Lc_FrequencyRanked/FrequencyRanked_2.py | yurenwang/Algorithm-Data-Structure | train | 0 | |
47c71ca91a7dd0bd27a51e4b155dab3c1279b638 | [
"diagnosis = DiagnosisPerm.objects.filter(diag_id=self, username=healthcare, perm_value__in=[2, 3])\nif diagnosis.count() == 0:\n return False\nelse:\n return True",
"if self.patient_id == patient:\n return True\nelse:\n return False"
] | <|body_start_0|>
diagnosis = DiagnosisPerm.objects.filter(diag_id=self, username=healthcare, perm_value__in=[2, 3])
if diagnosis.count() == 0:
return False
else:
return True
<|end_body_0|>
<|body_start_1|>
if self.patient_id == patient:
return True
... | Diagnosis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Diagnosis:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the diagnosis."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_028808 | 12,031 | no_license | [
{
"docstring": "Checks if a user has permissions to view the diagnosis.",
"name": "has_permission",
"signature": "def has_permission(self, healthcare)"
},
{
"docstring": "Checks if the record belongs to the patient.",
"name": "is_patient",
"signature": "def is_patient(self, patient)"
}... | 2 | null | Implement the Python class `Diagnosis` described below.
Class description:
Implement the Diagnosis class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the diagnosis.
- def is_patient(self, patient): Checks if the record belongs to the patient. | Implement the Python class `Diagnosis` described below.
Class description:
Implement the Diagnosis class.
Method signatures and docstrings:
- def has_permission(self, healthcare): Checks if a user has permissions to view the diagnosis.
- def is_patient(self, patient): Checks if the record belongs to the patient.
<|s... | 685c2b9d40fb24ca1735352846a39fdf5d3728eb | <|skeleton|>
class Diagnosis:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the diagnosis."""
<|body_0|>
def is_patient(self, patient):
"""Checks if the record belongs to the patient."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Diagnosis:
def has_permission(self, healthcare):
"""Checks if a user has permissions to view the diagnosis."""
diagnosis = DiagnosisPerm.objects.filter(diag_id=self, username=healthcare, perm_value__in=[2, 3])
if diagnosis.count() == 0:
return False
else:
... | the_stack_v2_python_sparse | patientrecords/models.py | guekling/ifs4205team1 | train | 0 | |
caa1a732ffd449f5d248732e2735d78b5537b34f | [
"self.val = value\nself.left = left\nself.right = right",
"preOrder = ''\nif self:\n preOrder += str(self.val)\nif self.left:\n preOrder += ' ' + str(self.left)\nif self.right:\n preOrder += ' ' + str(self.right)\nreturn preOrder"
] | <|body_start_0|>
self.val = value
self.left = left
self.right = right
<|end_body_0|>
<|body_start_1|>
preOrder = ''
if self:
preOrder += str(self.val)
if self.left:
preOrder += ' ' + str(self.left)
if self.right:
preOrder += ' ... | TreeNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
<|body_0|>
def __str__(self):
""":rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.val = value
self.lef... | stack_v2_sparse_classes_36k_train_028809 | 1,997 | no_license | [
{
"docstring": ":type value: int or str, left: TreeNode, right: TreeNode",
"name": "__init__",
"signature": "def __init__(self, value, left=None, right=None)"
},
{
"docstring": ":rtype: str",
"name": "__str__",
"signature": "def __str__(self)"
}
] | 2 | null | Implement the Python class `TreeNode` described below.
Class description:
Implement the TreeNode class.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): :type value: int or str, left: TreeNode, right: TreeNode
- def __str__(self): :rtype: str | Implement the Python class `TreeNode` described below.
Class description:
Implement the TreeNode class.
Method signatures and docstrings:
- def __init__(self, value, left=None, right=None): :type value: int or str, left: TreeNode, right: TreeNode
- def __str__(self): :rtype: str
<|skeleton|>
class TreeNode:
def... | fa624b702129fa3efd6997791e4cd37c420e114e | <|skeleton|>
class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
<|body_0|>
def __str__(self):
""":rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeNode:
def __init__(self, value, left=None, right=None):
""":type value: int or str, left: TreeNode, right: TreeNode"""
self.val = value
self.left = left
self.right = right
def __str__(self):
""":rtype: str"""
preOrder = ''
if self:
p... | the_stack_v2_python_sparse | p65/p65.py | zois-tasoulas/DailyInterviewPro | train | 0 | |
025c11864e7566f7be0a3e60b7118d44c35fbf09 | [
"self._sub_output_topic = None\nself._publisher = None\nself.node = node",
"try:\n self._publisher = self.node.create_publisher(Int64, publish_topic, qos_profile=QoSProfile(depth=1))\n output_topic_type = get_msg_class(self.node, output_topic, blocking=True)\n self._sub_output_topic = self.node.create_su... | <|body_start_0|>
self._sub_output_topic = None
self._publisher = None
self.node = node
<|end_body_0|>
<|body_start_1|>
try:
self._publisher = self.node.create_publisher(Int64, publish_topic, qos_profile=QoSProfile(depth=1))
output_topic_type = get_msg_class(self.... | The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses millisecond resolution. This class should be used when the node that produces the message, is c... | TimeEstimatorHeader | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeEstimatorHeader:
"""The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses millisecond resolution. This class should be use... | stack_v2_sparse_classes_36k_train_028810 | 4,464 | permissive | [
{
"docstring": "Create a TimeEstimator object. @param node: ROS2 node @type node: rclpy.node.Node",
"name": "__init__",
"signature": "def __init__(self, node)"
},
{
"docstring": "Start the time measurement. @param output_topic: Topic to be listened to measure the time @type output_topic: str @pa... | 3 | null | Implement the Python class `TimeEstimatorHeader` described below.
Class description:
The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses milliseco... | Implement the Python class `TimeEstimatorHeader` described below.
Class description:
The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses milliseco... | ff8950abbb72366ed3072de790c405de8875ecc3 | <|skeleton|>
class TimeEstimatorHeader:
"""The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses millisecond resolution. This class should be use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeEstimatorHeader:
"""The TimeEstimatorHeader class. It measures the time elapsed from the reception of a message using the header stamp information. It measures the difference between the received time and the time in the message header, it uses millisecond resolution. This class should be used when the no... | the_stack_v2_python_sparse | src/tools/benchmark_tool/benchmark_tool/time_estimator/time_estimator_header.py | bytetok/vde | train | 0 |
25abd94c6ce0692be34de91ac6f66da5e3e35a1a | [
"review = cls(**review_data)\nreview.clean_fields()\nreview.clean()\nreview.save()\nreturn review",
"response = {'Reviews': []}\nfor review in list(Review.objects.filter(restaurant_id=rest_id)):\n review._id = str(review._id)\n response['Reviews'].append({'_id': str(review._id), 'restaurant_id': review.rest... | <|body_start_0|>
review = cls(**review_data)
review.clean_fields()
review.clean()
review.save()
return review
<|end_body_0|>
<|body_start_1|>
response = {'Reviews': []}
for review in list(Review.objects.filter(restaurant_id=rest_id)):
review._id = str... | Review | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Review:
def new_review(cls, review_data):
"""Create new review and save to database :param review_data: data of new review :return: newly created review instance"""
<|body_0|>
def get_by_restaurant(cls, rest_id):
"""gets all reviews for a restaurant :param rest_id: t... | stack_v2_sparse_classes_36k_train_028811 | 2,002 | no_license | [
{
"docstring": "Create new review and save to database :param review_data: data of new review :return: newly created review instance",
"name": "new_review",
"signature": "def new_review(cls, review_data)"
},
{
"docstring": "gets all reviews for a restaurant :param rest_id: the id of restaurant :... | 3 | stack_v2_sparse_classes_30k_train_006893 | Implement the Python class `Review` described below.
Class description:
Implement the Review class.
Method signatures and docstrings:
- def new_review(cls, review_data): Create new review and save to database :param review_data: data of new review :return: newly created review instance
- def get_by_restaurant(cls, re... | Implement the Python class `Review` described below.
Class description:
Implement the Review class.
Method signatures and docstrings:
- def new_review(cls, review_data): Create new review and save to database :param review_data: data of new review :return: newly created review instance
- def get_by_restaurant(cls, re... | 97242c072ab64704fd250a3ac2b62da05b0d3ca5 | <|skeleton|>
class Review:
def new_review(cls, review_data):
"""Create new review and save to database :param review_data: data of new review :return: newly created review instance"""
<|body_0|>
def get_by_restaurant(cls, rest_id):
"""gets all reviews for a restaurant :param rest_id: t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Review:
def new_review(cls, review_data):
"""Create new review and save to database :param review_data: data of new review :return: newly created review instance"""
review = cls(**review_data)
review.clean_fields()
review.clean()
review.save()
return review
... | the_stack_v2_python_sparse | server/review/models.py | CSCC01/team_08-project | train | 0 | |
9f1bb281cb38c76b57422884c25bc7f6a3eff6c3 | [
"self.payload = None\nself.response_b = None\nself.response = None\nHmcHeaders_obj = HmcHeaders.HmcHeaders(service, ip, root, session_id)\nglobal global_HmcHeaders\nglobal_HmcHeaders = HmcHeaders_obj\nself.head = global_HmcHeaders.getHeader(service, session_id, content_type)",
"if response.status_code == 200:\n ... | <|body_start_0|>
self.payload = None
self.response_b = None
self.response = None
HmcHeaders_obj = HmcHeaders.HmcHeaders(service, ip, root, session_id)
global global_HmcHeaders
global_HmcHeaders = HmcHeaders_obj
self.head = global_HmcHeaders.getHeader(service, sess... | HTTPClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HTTPClient:
def __init__(self, service, ip, root, content_type, session_id=None):
"""Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/pcm) ip : ip address of the hmc root : root element in the url content_type : specifies the content ... | stack_v2_sparse_classes_36k_train_028812 | 5,033 | permissive | [
{
"docstring": "Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/pcm) ip : ip address of the hmc root : root element in the url content_type : specifies the content type of the request session_id : id for the current X_API_Session",
"name": "__init__",
... | 6 | stack_v2_sparse_classes_30k_train_009745 | Implement the Python class `HTTPClient` described below.
Class description:
Implement the HTTPClient class.
Method signatures and docstrings:
- def __init__(self, service, ip, root, content_type, session_id=None): Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/p... | Implement the Python class `HTTPClient` described below.
Class description:
Implement the HTTPClient class.
Method signatures and docstrings:
- def __init__(self, service, ip, root, content_type, session_id=None): Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/p... | 8e46a5a25a57d07f0612404f4b978234d6d2cd4b | <|skeleton|>
class HTTPClient:
def __init__(self, service, ip, root, content_type, session_id=None):
"""Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/pcm) ip : ip address of the hmc root : root element in the url content_type : specifies the content ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HTTPClient:
def __init__(self, service, ip, root, content_type, session_id=None):
"""Initializes the default values to the arguments Args: service : To specify the type of service(web/uom/pcm) ip : ip address of the hmc root : root element in the url content_type : specifies the content type of the re... | the_stack_v2_python_sparse | src/utility/HTTPClient.py | Python3pkg/HmcRestClient | train | 0 | |
f875997e46b97d8657a0dc76d3f9cfda6612767a | [
"if None is gpb_msg_class:\n raise AttributeError('No any GPB message class passed')\nif gpb_msg_class not in (t_ItApiRpdMessage, t_ItApiServiceSuiteMessage):\n raise AttributeError('Invalid GPB message class passed')\nself.gpb_msg_class = gpb_msg_class\nself.it_api_socket = None\nsetup_logging('ItManager', f... | <|body_start_0|>
if None is gpb_msg_class:
raise AttributeError('No any GPB message class passed')
if gpb_msg_class not in (t_ItApiRpdMessage, t_ItApiServiceSuiteMessage):
raise AttributeError('Invalid GPB message class passed')
self.gpb_msg_class = gpb_msg_class
... | Implements client side of IT (Integration Testing) API. | ItApiClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ItApiClient:
"""Implements client side of IT (Integration Testing) API."""
def __init__(self, gpb_msg_class):
"""Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of GPB messages which will be exchanged. :param rx_cb: User... | stack_v2_sparse_classes_36k_train_028813 | 10,996 | permissive | [
{
"docstring": "Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of GPB messages which will be exchanged. :param rx_cb: User's RX callback which is called when some GPB message was received. The callback expects the GPB message as argument. :param d... | 5 | null | Implement the Python class `ItApiClient` described below.
Class description:
Implements client side of IT (Integration Testing) API.
Method signatures and docstrings:
- def __init__(self, gpb_msg_class): Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of... | Implement the Python class `ItApiClient` described below.
Class description:
Implements client side of IT (Integration Testing) API.
Method signatures and docstrings:
- def __init__(self, gpb_msg_class): Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of... | 70cf84df92347aba0493f506c0d059c0c041cba8 | <|skeleton|>
class ItApiClient:
"""Implements client side of IT (Integration Testing) API."""
def __init__(self, gpb_msg_class):
"""Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of GPB messages which will be exchanged. :param rx_cb: User... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ItApiClient:
"""Implements client side of IT (Integration Testing) API."""
def __init__(self, gpb_msg_class):
"""Creates dispatcher if not passed and initializes instance. TODO params dont match :param gpb_msg_class: A class of GPB messages which will be exchanged. :param rx_cb: User's RX callbac... | the_stack_v2_python_sparse | openrpd/rpd/it_api/it_api.py | hujiangyi/or | train | 0 |
0387cdebd5ba397f79d4aebcb137ff94fd873fe2 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CallEndedEventMessageDetail()",
"from .call_participant_info import CallParticipantInfo\nfrom .event_message_detail import EventMessageDetail\nfrom .identity_set import IdentitySet\nfrom .teamwork_call_event_type import TeamworkCallEve... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CallEndedEventMessageDetail()
<|end_body_0|>
<|body_start_1|>
from .call_participant_info import CallParticipantInfo
from .event_message_detail import EventMessageDetail
from .id... | CallEndedEventMessageDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallEndedEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallEndedEventMessageDetail:
"""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 a... | stack_v2_sparse_classes_36k_train_028814 | 3,856 | 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: CallEndedEventMessageDetail",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | null | Implement the Python class `CallEndedEventMessageDetail` described below.
Class description:
Implement the CallEndedEventMessageDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallEndedEventMessageDetail: Creates a new instance of the appr... | Implement the Python class `CallEndedEventMessageDetail` described below.
Class description:
Implement the CallEndedEventMessageDetail class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallEndedEventMessageDetail: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CallEndedEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallEndedEventMessageDetail:
"""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 a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallEndedEventMessageDetail:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CallEndedEventMessageDetail:
"""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 ... | the_stack_v2_python_sparse | msgraph/generated/models/call_ended_event_message_detail.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
ef10982b6e273e7456dff909c70456075cd34d19 | [
"logs.log_info('You are using the vgK channel: K_Fast ')\nself.time_unit = 1000.0\nself.vrev = -65\nself.m = 1 / (1 + np.exp(-(V + 47) / 29))\nself.h = 1 / (1 + np.exp(-(V + 56) / -10))\nself._mpower = 1\nself._hpower = 1",
"self._mInf = 1 / (1 + np.exp(-(V + 47) / 29))\nself._mTau = 0.34 + 0.92 * np.exp(-((V + 7... | <|body_start_0|>
logs.log_info('You are using the vgK channel: K_Fast ')
self.time_unit = 1000.0
self.vrev = -65
self.m = 1 / (1 + np.exp(-(V + 47) / 29))
self.h = 1 / (1 + np.exp(-(V + 56) / -10))
self._mpower = 1
self._hpower = 1
<|end_body_0|>
<|body_start_1|>... | "K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39). | K_Fast | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class K_Fast:
""""K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39)."""
def _init_state(self, V):
"""Run initia... | stack_v2_sparse_classes_36k_train_028815 | 24,227 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `K_Fast` described below.
Class description:
"K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39).
Method signatur... | Implement the Python class `K_Fast` described below.
Class description:
"K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39).
Method signatur... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class K_Fast:
""""K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39)."""
def _init_state(self, V):
"""Run initia... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class K_Fast:
""""K Fast" model from Korngreen et al. Reference: Korngreen A. et al. Voltage-gated K+ channels in layer 5 neocortical pyramidal neurones from young rats: subtypes and gradients. J. Physiol. (Lond.), 2000 Jun 15 , 525 Pt 3 (621-39)."""
def _init_state(self, V):
"""Run initialization calc... | the_stack_v2_python_sparse | betse/science/channels/vg_k.py | R-Stefano/betse-ml | train | 0 |
15e94a422cd8b5a4337799c053e7bbcb118e0bd8 | [
"self.use_gumbel = use_gumbel\nif train_inputs is None and hasattr(model, 'train_inputs'):\n train_inputs = model.train_inputs[0]\nif train_inputs is not None:\n if train_inputs.ndim > 2:\n raise NotImplementedError('Batch GP models (e.g. fantasized models) are not yet supported by `MaxValueBase`')\n ... | <|body_start_0|>
self.use_gumbel = use_gumbel
if train_inputs is None and hasattr(model, 'train_inputs'):
train_inputs = model.train_inputs[0]
if train_inputs is not None:
if train_inputs.ndim > 2:
raise NotImplementedError('Batch GP models (e.g. fantasize... | Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates. It supports either exact (w.r.t. the candidate set) sampling, or using a Gumbel approx... | DiscreteMaxValueBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscreteMaxValueBase:
"""Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates. It supports either exact (w.r.t. the c... | stack_v2_sparse_classes_36k_train_028816 | 42,596 | permissive | [
{
"docstring": "Single-outcome MES-like acquisition functions based on discrete MV sampling. Args: model: A fitted single-outcome model. candidate_set: A `n x d` Tensor including `n` candidate points to discretize the design space. Max values are sampled from the (joint) model posterior over these points. num_m... | 2 | null | Implement the Python class `DiscreteMaxValueBase` described below.
Class description:
Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates.... | Implement the Python class `DiscreteMaxValueBase` described below.
Class description:
Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates.... | 4cc5ed59b2e8a9c780f786830c548e05cc74d53c | <|skeleton|>
class DiscreteMaxValueBase:
"""Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates. It supports either exact (w.r.t. the c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscreteMaxValueBase:
"""Abstract base class for MES-like methods using discrete max posterior sampling. This class provides basic functionality for sampling posterior maximum values from a surrogate Gaussian process model using a discrete set of candidates. It supports either exact (w.r.t. the candidate set)... | the_stack_v2_python_sparse | botorch/acquisition/max_value_entropy_search.py | pytorch/botorch | train | 2,891 |
d97991577af3fa405d7995ae49df4886b0476482 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file | ProfileServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileServicer:
"""Missing associated documentation comment in .proto file"""
def getUserInfo(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def createUser(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_36k_train_028817 | 7,766 | no_license | [
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "getUserInfo",
"signature": "def getUserInfo(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "createUser",
"signature": "def createUser(self, re... | 2 | stack_v2_sparse_classes_30k_train_009859 | Implement the Python class `ProfileServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def getUserInfo(self, request, context): Missing associated documentation comment in .proto file
- def createUser(self, request, context): Missin... | Implement the Python class `ProfileServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def getUserInfo(self, request, context): Missing associated documentation comment in .proto file
- def createUser(self, request, context): Missin... | 626dae0efa20a66d1f69f49be15ab90c623ec33b | <|skeleton|>
class ProfileServicer:
"""Missing associated documentation comment in .proto file"""
def getUserInfo(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def createUser(self, request, context):
"""Missing associated document... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileServicer:
"""Missing associated documentation comment in .proto file"""
def getUserInfo(self, request, context):
"""Missing associated documentation comment in .proto file"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | svms-job-module-service/backup/connectors/vms_profile_manager/protoc/profile_manager_pb2_grpc.py | shankarmahato/Job_module | train | 0 |
60767b79c8df2acd6845f1ed9a4ee6f1f3c497db | [
"QActiveViewsListWidgetItem.opened_views += 1\nview_name = f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.name}'\nsuper(QActiveViewsListWidgetItem, self).__init__(view_name, parent, type)\nview_window.setWindowTitle(f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.windowTitle()} - {view_wi... | <|body_start_0|>
QActiveViewsListWidgetItem.opened_views += 1
view_name = f'({QActiveViewsListWidgetItem.opened_views:d}) {view_window.name}'
super(QActiveViewsListWidgetItem, self).__init__(view_name, parent, type)
view_window.setWindowTitle(f'({QActiveViewsListWidgetItem.opened_views:d... | Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views. | QActiveViewsListWidgetItem | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, type=QtWidgets.Q... | stack_v2_sparse_classes_36k_train_028818 | 39,926 | permissive | [
{
"docstring": "Add ID number to the title of the corresponding view window.",
"name": "__init__",
"signature": "def __init__(self, view_window, parent=None, viewsChanged=None, type=QtWidgets.QListWidgetItem.UserType)"
},
{
"docstring": "Slot that removes this QListWidgetItem from the parent (th... | 2 | stack_v2_sparse_classes_30k_train_008373 | Implement the Python class `QActiveViewsListWidgetItem` described below.
Class description:
Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views.
Method signatures and docstrings:
- def __init__... | Implement the Python class `QActiveViewsListWidgetItem` described below.
Class description:
Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views.
Method signatures and docstrings:
- def __init__... | 36f4467bb7fa7c4b4d2e2a5d91cd05b7a46d9765 | <|skeleton|>
class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, type=QtWidgets.Q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QActiveViewsListWidgetItem:
"""Subclass of QListWidgetItem, represents an open view in the list of open views. Keeps a reference to the view instance (i.e. the window) it represents in the list of open views."""
def __init__(self, view_window, parent=None, viewsChanged=None, type=QtWidgets.QListWidgetIte... | the_stack_v2_python_sparse | mslib/msui/mss_pyui.py | risehr/MSS | train | 0 |
36b68c257b4d38157969f6d03d86c77f2e4a3548 | [
"self.arpoja = arpoja\nself.tilasiirtymat = [[30, 20, 20, 15, 15], [10, 40, 25, 15, 10], [0, 0, 20, 80, 0], [0, 0, 10, 80, 10], [0, 0, 0, 80, 20]]\nself.selitteet = {0: 'kokonuotti', 1: 'puolinuotti', 2: 'neljäsosanuotti', 3: 'kahdeksasosanuotti', 4: 'kuudestoistaosanuotti'}",
"arvottu = self.arpoja.randint(1, 10... | <|body_start_0|>
self.arpoja = arpoja
self.tilasiirtymat = [[30, 20, 20, 15, 15], [10, 40, 25, 15, 10], [0, 0, 20, 80, 0], [0, 0, 10, 80, 10], [0, 0, 0, 80, 20]]
self.selitteet = {0: 'kokonuotti', 1: 'puolinuotti', 2: 'neljäsosanuotti', 3: 'kahdeksasosanuotti', 4: 'kuudestoistaosanuotti'}
<|end_... | Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen todennäköisyyksiä selitteet: tilasiirtymien indeksien selitteet | Pituusarpoja | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pituusarpoja:
"""Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen todennäköisyyksiä selitteet: tilasiirtymi... | stack_v2_sparse_classes_36k_train_028819 | 1,947 | no_license | [
{
"docstring": "Args: arpoja: Arpoja-olio (Random-kirjastosta)",
"name": "__init__",
"signature": "def __init__(self, arpoja)"
},
{
"docstring": "Etsii seuraavan tilan. Tyhjälle tilalle etsitään arvo neljäsosanuotin arvojen perusteella Varmistaa, ettei arvota tahdin ylittäviä pituuksia Args: ede... | 2 | stack_v2_sparse_classes_30k_train_012877 | Implement the Python class `Pituusarpoja` described below.
Class description:
Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen to... | Implement the Python class `Pituusarpoja` described below.
Class description:
Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen to... | 09f09e60c89bdfb29fb63d9749a8b9c1b31cd6dd | <|skeleton|>
class Pituusarpoja:
"""Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen todennäköisyyksiä selitteet: tilasiirtymi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pituusarpoja:
"""Olio, joka (ensimmäisen asteen) Markovin ketjua käyttäen arpoo sävelen pituuden arpoja: Arpoja-olio (Random-kirjastosta) tilasiirtymat: taulukko, jonka perusteella siirrytään eri tilojen välillä x-akseli kuvaa tietystä tilasta siirtymisen todennäköisyyksiä selitteet: tilasiirtymien indeksien ... | the_stack_v2_python_sparse | src/markovin_ketjut/pituusarpoja.py | Aikamoine/markovin-ketju-saveltaja | train | 0 |
b60a6a5ee1df3d8df5d337fc02020953eb5bed6a | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.kernel_size = kernel_size\nself.dilation = dilation\nself.up_or_down_sample = up_or_down_sample\nself.layer = layer\npadding_length = (self.kernel_size - 1) * self.dilation\n'\\n determining the input and output chann... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.dilation = dilation
self.up_or_down_sample = up_or_down_sample
self.layer = layer
padding_length = (self.kernel_size - 1... | CausalCNNLayer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CausalCNNLayer:
def __init__(self, in_channels, out_channels, kernel_size, dilation, layer, up_or_down_sample=False):
"""Each of the causal convolution layers as depicted in Fig. 2 (b) of the paper. :param in_channels: channel size of the input to the causal layer :param out_channels: ch... | stack_v2_sparse_classes_36k_train_028820 | 8,666 | no_license | [
{
"docstring": "Each of the causal convolution layers as depicted in Fig. 2 (b) of the paper. :param in_channels: channel size of the input to the causal layer :param out_channels: channel size of the output of the causal layer :param kernel_size: - :param dilation: - :param layer: the position of the layer ('f... | 2 | stack_v2_sparse_classes_30k_train_000257 | Implement the Python class `CausalCNNLayer` described below.
Class description:
Implement the CausalCNNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, dilation, layer, up_or_down_sample=False): Each of the causal convolution layers as depicted in Fig. 2 (b) ... | Implement the Python class `CausalCNNLayer` described below.
Class description:
Implement the CausalCNNLayer class.
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, dilation, layer, up_or_down_sample=False): Each of the causal convolution layers as depicted in Fig. 2 (b) ... | 84b9ac79439657c04033cadb51c6145ad7e2f4b3 | <|skeleton|>
class CausalCNNLayer:
def __init__(self, in_channels, out_channels, kernel_size, dilation, layer, up_or_down_sample=False):
"""Each of the causal convolution layers as depicted in Fig. 2 (b) of the paper. :param in_channels: channel size of the input to the causal layer :param out_channels: ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CausalCNNLayer:
def __init__(self, in_channels, out_channels, kernel_size, dilation, layer, up_or_down_sample=False):
"""Each of the causal convolution layers as depicted in Fig. 2 (b) of the paper. :param in_channels: channel size of the input to the causal layer :param out_channels: channel size of ... | the_stack_v2_python_sparse | src/encoder.py | lhvu2/reproducibility_NeurIPS19 | train | 0 | |
b5ceffb8a97758119b065e9c36f73fd000fb0b99 | [
"self.number_points = number_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.number_points:\n x_step = get_step()\n y_step = get_step()\n if x_step == 0 and y_step == 0:\n continue\n next_x = self.x_values[-1] + x_step\n next_y = self.y_values[-1] + y_step... | <|body_start_0|>
self.number_points = number_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.number_points:
x_step = get_step()
y_step = get_step()
if x_step == 0 and y_step == 0:
... | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
def __init__(self, number_points=5000) -> None:
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.number_points = number_points
self.x_values = [0]
self.... | stack_v2_sparse_classes_36k_train_028821 | 1,327 | no_license | [
{
"docstring": "初始化随机漫步的属性",
"name": "__init__",
"signature": "def __init__(self, number_points=5000) -> None"
},
{
"docstring": "计算随机漫步包含的所有点",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012729 | Implement the Python class `RandomWalk` described below.
Class description:
Implement the RandomWalk class.
Method signatures and docstrings:
- def __init__(self, number_points=5000) -> None: 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有点 | Implement the Python class `RandomWalk` described below.
Class description:
Implement the RandomWalk class.
Method signatures and docstrings:
- def __init__(self, number_points=5000) -> None: 初始化随机漫步的属性
- def fill_walk(self): 计算随机漫步包含的所有点
<|skeleton|>
class RandomWalk:
def __init__(self, number_points=5000) -> ... | 062427d9e320afd89fe161e54affa0566fd07123 | <|skeleton|>
class RandomWalk:
def __init__(self, number_points=5000) -> None:
"""初始化随机漫步的属性"""
<|body_0|>
def fill_walk(self):
"""计算随机漫步包含的所有点"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
def __init__(self, number_points=5000) -> None:
"""初始化随机漫步的属性"""
self.number_points = number_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
while len(self.x_values) < self.number_points:
x_step... | the_stack_v2_python_sparse | chapter_15/random_walk.py | star428/learn_matplotlib | train | 0 | |
ad7c23a3b0f4129ed4497ee6d8732e24f2350591 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | A set of methods for managing resource presets. | ResourcePresetServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcePresetServiceServicer:
"""A set of methods for managing resource presets."""
def Get(self, request, context):
"""Returns the specified resource preset. To get the list of available resource presets, make a [List] request."""
<|body_0|>
def List(self, request, con... | stack_v2_sparse_classes_36k_train_028822 | 5,242 | permissive | [
{
"docstring": "Returns the specified resource preset. To get the list of available resource presets, make a [List] request.",
"name": "Get",
"signature": "def Get(self, request, context)"
},
{
"docstring": "Retrieves the list of available resource presets.",
"name": "List",
"signature":... | 2 | null | Implement the Python class `ResourcePresetServiceServicer` described below.
Class description:
A set of methods for managing resource presets.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified resource preset. To get the list of available resource presets, make a [List] reques... | Implement the Python class `ResourcePresetServiceServicer` described below.
Class description:
A set of methods for managing resource presets.
Method signatures and docstrings:
- def Get(self, request, context): Returns the specified resource preset. To get the list of available resource presets, make a [List] reques... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ResourcePresetServiceServicer:
"""A set of methods for managing resource presets."""
def Get(self, request, context):
"""Returns the specified resource preset. To get the list of available resource presets, make a [List] request."""
<|body_0|>
def List(self, request, con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourcePresetServiceServicer:
"""A set of methods for managing resource presets."""
def Get(self, request, context):
"""Returns the specified resource preset. To get the list of available resource presets, make a [List] request."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | yandex/cloud/mdb/greenplum/v1/resource_preset_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
340ef55fa2401cc8b6b519c70bc4e348b6772a05 | [
"if len(graph) == 0:\n return 0\ncount = 0\nfor row in range(len(graph)):\n for col in range(len(graph[0])):\n if graph[row][col] == '1':\n self.dfs(graph, row, col)\n print(type(graph))\n count += 1\nreturn count",
"if row < 0 or row >= len(graph) or col < 0 or (col ... | <|body_start_0|>
if len(graph) == 0:
return 0
count = 0
for row in range(len(graph)):
for col in range(len(graph[0])):
if graph[row][col] == '1':
self.dfs(graph, row, col)
print(type(graph))
count... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, graph):
""":type graph: List[List[str]] :rtype: int"""
<|body_0|>
def dfs(self, graph, row, col):
"""根据起始点row, col开始往周围搜素,采用函数迭代,如果不满足条件推出 增加一个小trick,当访问过的节点把graph内容变为#号,表示这个节点访问过了,防止再次访问 这里所有的dfs函数都在numIslands内部调用,因此graph更改后会作用与整个函数"""... | stack_v2_sparse_classes_36k_train_028823 | 1,655 | no_license | [
{
"docstring": ":type graph: List[List[str]] :rtype: int",
"name": "numIslands",
"signature": "def numIslands(self, graph)"
},
{
"docstring": "根据起始点row, col开始往周围搜素,采用函数迭代,如果不满足条件推出 增加一个小trick,当访问过的节点把graph内容变为#号,表示这个节点访问过了,防止再次访问 这里所有的dfs函数都在numIslands内部调用,因此graph更改后会作用与整个函数",
"name": "dfs",... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, graph): :type graph: List[List[str]] :rtype: int
- def dfs(self, graph, row, col): 根据起始点row, col开始往周围搜素,采用函数迭代,如果不满足条件推出 增加一个小trick,当访问过的节点把graph内容变为#号,表示这个节... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, graph): :type graph: List[List[str]] :rtype: int
- def dfs(self, graph, row, col): 根据起始点row, col开始往周围搜素,采用函数迭代,如果不满足条件推出 增加一个小trick,当访问过的节点把graph内容变为#号,表示这个节... | 2903e5500e242768f5ae51f0cc875a2f291fcfff | <|skeleton|>
class Solution:
def numIslands(self, graph):
""":type graph: List[List[str]] :rtype: int"""
<|body_0|>
def dfs(self, graph, row, col):
"""根据起始点row, col开始往周围搜素,采用函数迭代,如果不满足条件推出 增加一个小trick,当访问过的节点把graph内容变为#号,表示这个节点访问过了,防止再次访问 这里所有的dfs函数都在numIslands内部调用,因此graph更改后会作用与整个函数"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, graph):
""":type graph: List[List[str]] :rtype: int"""
if len(graph) == 0:
return 0
count = 0
for row in range(len(graph)):
for col in range(len(graph[0])):
if graph[row][col] == '1':
sel... | the_stack_v2_python_sparse | Number of Islands/DFS.py | MSJYYT/LeetCode_with_Python | train | 0 | |
f7a21b8e4d34f3cb46f5d52d0176e9620b9994ce | [
"if not root:\n return ''\nvals = []\n\ndef _preorder(node):\n if not node:\n vals.append('')\n return\n vals.append(node.val)\n _preorder(node.left)\n _preorder(node.right)\n_preorder(root)\nreturn '#'.join(map(str, vals))",
"vals = data.split('#')\n\ndef _deseralized():\n val = v... | <|body_start_0|>
if not root:
return ''
vals = []
def _preorder(node):
if not node:
vals.append('')
return
vals.append(node.val)
_preorder(node.left)
_preorder(node.right)
_preorder(root)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_028824 | 965 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: Optional[TreeNode]) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> Optional[TreeNode... | 2 | stack_v2_sparse_classes_30k_train_007745 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: Optional[TreeNode]) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> Optional[TreeNode]: Decodes your encoded data to tree.
<... | b093920748012cddb77258b1900c6c177579bff8 | <|skeleton|>
class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> Optional[TreeNode]:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: Optional[TreeNode]) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
vals = []
def _preorder(node):
if not node:
vals.append('')
return
vals.append(node.... | the_stack_v2_python_sparse | 2022/huahua_449_Serialize_and_Deserialize_BST.py | everbird/leetcode-py | train | 2 | |
b36feeb7394d867806e54a7e166be4639e1f67cc | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center. | MerchantCenterLinkServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available tor th... | stack_v2_sparse_classes_36k_train_028825 | 4,994 | permissive | [
{
"docstring": "Returns Merchant Center links available tor this customer.",
"name": "ListMerchantCenterLinks",
"signature": "def ListMerchantCenterLinks(self, request, context)"
},
{
"docstring": "Returns the Merchant Center link in full detail.",
"name": "GetMerchantCenterLink",
"signa... | 3 | null | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | Implement the Python class `MerchantCenterLinkServiceServicer` described below.
Class description:
Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center.
Method signatures and docstrings:
- def ListMerchantCenterLinks(self, request,... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available tor th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MerchantCenterLinkServiceServicer:
"""Proto file describing the MerchantCenterLink service. This service allows management of links between Google Ads and Google Merchant Center."""
def ListMerchantCenterLinks(self, request, context):
"""Returns Merchant Center links available tor this customer."... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/merchant_center_link_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
e12425b5d7f16f3a610af654e32c44981a88b9ee | [
"candidates = sorted(candidates)\nrst = []\n\ndef dfs(remain, ele, idx_can):\n if remain == 0:\n rst.append(ele)\n return\n for i in range(idx_can, len(candidates)):\n can = candidates[i]\n if i > idx_can and can == candidates[i - 1]:\n continue\n if remain >= can... | <|body_start_0|>
candidates = sorted(candidates)
rst = []
def dfs(remain, ele, idx_can):
if remain == 0:
rst.append(ele)
return
for i in range(idx_can, len(candidates)):
can = candidates[i]
if i > idx_can an... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum2_mysecond(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[... | stack_v2_sparse_classes_36k_train_028826 | 2,586 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum2",
"signature": "def combinationSum2(self, candidates, target)"
},
{
"docstring": ":type candidates: List[int] :type target: int :rtype: List[List[int]]",
"name": "combinationSum2_... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum2_mysecond(self, candidates, target): :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum2(self, candidates, target): :type candidates: List[int] :type target: int :rtype: List[List[int]]
- def combinationSum2_mysecond(self, candidates, target): :ty... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def combinationSum2_mysecond(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum2(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: List[List[int]]"""
candidates = sorted(candidates)
rst = []
def dfs(remain, ele, idx_can):
if remain == 0:
rst.append(ele)
... | the_stack_v2_python_sparse | 40.CombinationSumii.py | JerryRoc/leetcode | train | 0 | |
1c15971ec2be21599e09a4e8ec9a32cb288b8efd | [
"super(BayesianLSTMCell, self).__init__(num_units, **kwargs)\nself.w = None\nself.b = None\nself.prior = prior\nself.n = name\nself.is_training = is_training\nself.num_units = num_units\nself.X_dim = X_dim",
"with tf.variable_scope('BayesLSTMCell'):\n if self.w is None:\n print(['------- Size input LSTM... | <|body_start_0|>
super(BayesianLSTMCell, self).__init__(num_units, **kwargs)
self.w = None
self.b = None
self.prior = prior
self.n = name
self.is_training = is_training
self.num_units = num_units
self.X_dim = X_dim
<|end_body_0|>
<|body_start_1|>
... | BayesianLSTMCell | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BayesianLSTMCell:
def __init__(self, X_dim, num_units, prior, is_training, name=None, **kwargs):
"""In the initialization of the Cell, we will set: - The internal weights structures w and b. Which will hold the weights and biases for the 4 gates of the LSTM cell. - The Prior of the weigh... | stack_v2_sparse_classes_36k_train_028827 | 4,584 | no_license | [
{
"docstring": "In the initialization of the Cell, we will set: - The internal weights structures w and b. Which will hold the weights and biases for the 4 gates of the LSTM cell. - The Prior of the weights: Needed to compute the first set of weights before seeing any data As wwll as the number of units in each... | 2 | stack_v2_sparse_classes_30k_train_003999 | Implement the Python class `BayesianLSTMCell` described below.
Class description:
Implement the BayesianLSTMCell class.
Method signatures and docstrings:
- def __init__(self, X_dim, num_units, prior, is_training, name=None, **kwargs): In the initialization of the Cell, we will set: - The internal weights structures w... | Implement the Python class `BayesianLSTMCell` described below.
Class description:
Implement the BayesianLSTMCell class.
Method signatures and docstrings:
- def __init__(self, X_dim, num_units, prior, is_training, name=None, **kwargs): In the initialization of the Cell, we will set: - The internal weights structures w... | f1248011010e95906e291316aec1679c23a834e3 | <|skeleton|>
class BayesianLSTMCell:
def __init__(self, X_dim, num_units, prior, is_training, name=None, **kwargs):
"""In the initialization of the Cell, we will set: - The internal weights structures w and b. Which will hold the weights and biases for the 4 gates of the LSTM cell. - The Prior of the weigh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BayesianLSTMCell:
def __init__(self, X_dim, num_units, prior, is_training, name=None, **kwargs):
"""In the initialization of the Cell, we will set: - The internal weights structures w and b. Which will hold the weights and biases for the 4 gates of the LSTM cell. - The Prior of the weights: Needed to ... | the_stack_v2_python_sparse | libs/BBBLSTM/BayesianLSTMCell.py | Sdoof/Trapyng | train | 0 | |
2e32566f6bad1475d8a564ebd29afeaf0608c571 | [
"def memoization(index: int, s: str) -> int:\n if index == len(s):\n return 1\n if s[index] == '0':\n return 0\n if index == len(s) - 1:\n return 1\n if index in cache:\n return cache[index]\n result = memoization(index + 1, s) + (memoization(index + 2, s) if int(s[index:i... | <|body_start_0|>
def memoization(index: int, s: str) -> int:
if index == len(s):
return 1
if s[index] == '0':
return 0
if index == len(s) - 1:
return 1
if index in cache:
return cache[index]
... | Decode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decode:
def get_number_of_ways(self, s: str) -> int:
"""Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
<|body_0|>
def get_number_of_ways_(self, s: str) -> int:
"""Approach: Iteration with recursion_memoization... | stack_v2_sparse_classes_36k_train_028828 | 2,175 | no_license | [
{
"docstring": "Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:",
"name": "get_number_of_ways",
"signature": "def get_number_of_ways(self, s: str) -> int"
},
{
"docstring": "Approach: Iteration with recursion_memoization_dp Time Complexity: O... | 2 | null | Implement the Python class `Decode` described below.
Class description:
Implement the Decode class.
Method signatures and docstrings:
- def get_number_of_ways(self, s: str) -> int: Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:
- def get_number_of_ways_(self, s: ... | Implement the Python class `Decode` described below.
Class description:
Implement the Decode class.
Method signatures and docstrings:
- def get_number_of_ways(self, s: str) -> int: Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:
- def get_number_of_ways_(self, s: ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Decode:
def get_number_of_ways(self, s: str) -> int:
"""Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
<|body_0|>
def get_number_of_ways_(self, s: str) -> int:
"""Approach: Iteration with recursion_memoization... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decode:
def get_number_of_ways(self, s: str) -> int:
"""Approach: Recursion with memoization. Time Complexity: O(N) Space Complexity: O(N) :param s: :return:"""
def memoization(index: int, s: str) -> int:
if index == len(s):
return 1
if s[index] == '0':
... | the_stack_v2_python_sparse | data_structures/recurrsion_dp/decode_ways.py | Shiv2157k/leet_code | train | 1 | |
c96eb0fb2ed957665c37ffd4266319d14e4f7d5d | [
"reader = csv.reader(data)\nnext(reader)\nreturn collections.Counter(map(lambda item: self.safe_name(item[4]), filter(lambda item: len(item[1].split('-')) != 2, reader)))",
"if self.record[self.safe_name(name)] > 1:\n name = f'{name}_0x{code}'\nreturn self.safe_name(name)",
"reader = csv.reader(data)\nnext(r... | <|body_start_0|>
reader = csv.reader(data)
next(reader)
return collections.Counter(map(lambda item: self.safe_name(item[4]), filter(lambda item: len(item[1].split('-')) != 2, reader)))
<|end_body_0|>
<|body_start_1|>
if self.record[self.safe_name(name)] > 1:
name = f'{name}_... | Ethertype IEEE 802 Numbers | EtherType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EtherType:
"""Ethertype IEEE 802 Numbers"""
def count(self, data: 'list[str]') -> 'Counter[str]':
"""Count field records. Args: data: CSV data. Returns: Field recordings."""
<|body_0|>
def rename(self, name: 'str', code: 'str', *, original: 'Optional[str]'=None) -> 'str'... | stack_v2_sparse_classes_36k_train_028829 | 3,752 | permissive | [
{
"docstring": "Count field records. Args: data: CSV data. Returns: Field recordings.",
"name": "count",
"signature": "def count(self, data: 'list[str]') -> 'Counter[str]'"
},
{
"docstring": "Rename duplicated fields. Args: name: Field name. code: Field code. Keyword Args: original: Original fie... | 3 | null | Implement the Python class `EtherType` described below.
Class description:
Ethertype IEEE 802 Numbers
Method signatures and docstrings:
- def count(self, data: 'list[str]') -> 'Counter[str]': Count field records. Args: data: CSV data. Returns: Field recordings.
- def rename(self, name: 'str', code: 'str', *, original... | Implement the Python class `EtherType` described below.
Class description:
Ethertype IEEE 802 Numbers
Method signatures and docstrings:
- def count(self, data: 'list[str]') -> 'Counter[str]': Count field records. Args: data: CSV data. Returns: Field recordings.
- def rename(self, name: 'str', code: 'str', *, original... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class EtherType:
"""Ethertype IEEE 802 Numbers"""
def count(self, data: 'list[str]') -> 'Counter[str]':
"""Count field records. Args: data: CSV data. Returns: Field recordings."""
<|body_0|>
def rename(self, name: 'str', code: 'str', *, original: 'Optional[str]'=None) -> 'str'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EtherType:
"""Ethertype IEEE 802 Numbers"""
def count(self, data: 'list[str]') -> 'Counter[str]':
"""Count field records. Args: data: CSV data. Returns: Field recordings."""
reader = csv.reader(data)
next(reader)
return collections.Counter(map(lambda item: self.safe_name(i... | the_stack_v2_python_sparse | pcapkit/vendor/reg/ethertype.py | JarryShaw/PyPCAPKit | train | 204 |
598da755a8e74ac6d70895132c01e6e5d63f02c6 | [
"super(CreateUserTermAndConditionSerializer, self).__init__(*args, **kwargs)\nself.context['terms'] = TermAndCondition.objects.all().order_by('id')\nfor term in self.context['terms']:\n field_name = term.slug_name\n self.fields[field_name] = serializers.BooleanField()",
"if not data['general']:\n raise V... | <|body_start_0|>
super(CreateUserTermAndConditionSerializer, self).__init__(*args, **kwargs)
self.context['terms'] = TermAndCondition.objects.all().order_by('id')
for term in self.context['terms']:
field_name = term.slug_name
self.fields[field_name] = serializers.BooleanF... | Create user terms and conditions. | CreateUserTermAndConditionSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateUserTermAndConditionSerializer:
"""Create user terms and conditions."""
def __init__(self, *args, **kwargs):
"""Handle serializer instance."""
<|body_0|>
def validate(self, data):
"""Validate input data."""
<|body_1|>
def create(self, data):
... | stack_v2_sparse_classes_36k_train_028830 | 14,720 | permissive | [
{
"docstring": "Handle serializer instance.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Validate input data.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "Create user's term and condition.",
"n... | 3 | stack_v2_sparse_classes_30k_train_011890 | Implement the Python class `CreateUserTermAndConditionSerializer` described below.
Class description:
Create user terms and conditions.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Handle serializer instance.
- def validate(self, data): Validate input data.
- def create(self, data): Create... | Implement the Python class `CreateUserTermAndConditionSerializer` described below.
Class description:
Create user terms and conditions.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Handle serializer instance.
- def validate(self, data): Validate input data.
- def create(self, data): Create... | ba013f8a06d4b68464a599a1bfaad917e801eeef | <|skeleton|>
class CreateUserTermAndConditionSerializer:
"""Create user terms and conditions."""
def __init__(self, *args, **kwargs):
"""Handle serializer instance."""
<|body_0|>
def validate(self, data):
"""Validate input data."""
<|body_1|>
def create(self, data):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateUserTermAndConditionSerializer:
"""Create user terms and conditions."""
def __init__(self, *args, **kwargs):
"""Handle serializer instance."""
super(CreateUserTermAndConditionSerializer, self).__init__(*args, **kwargs)
self.context['terms'] = TermAndCondition.objects.all().o... | the_stack_v2_python_sparse | id/modules/api/accounts/serializers.py | argob/id-mi-argentina-distro | train | 5 |
008f11c0588153e4cc558fcef75f9dae392c7868 | [
"if len(Arr) == 0 or rows <= 0 or cols <= 0:\n return 0\nmaxValue = [[0] * rows] * cols\nfor i in range(rows):\n for j in range(cols):\n up, left = (0, 0)\n if i > 0:\n up = maxValue[i - 1][j]\n if j > 0:\n left = maxValue[i][j - 1]\n maxValue[i][j] = max(up, ... | <|body_start_0|>
if len(Arr) == 0 or rows <= 0 or cols <= 0:
return 0
maxValue = [[0] * rows] * cols
for i in range(rows):
for j in range(cols):
up, left = (0, 0)
if i > 0:
up = maxValue[i - 1][j]
if j > ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getMaxValue(self, Arr, rows, cols):
"""记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将"""
<|body_0|>
def getMaxValue2(self, Arr, rows, cols):
"""动态规划:构造二维动态规划矩阵,需要双层循环——可能会超出内存"""
<|body_1|>
def getMaxValue3(self, Arr, rows, cols):
"""动态规划:构造一维动态规划矩阵,... | stack_v2_sparse_classes_36k_train_028831 | 3,925 | no_license | [
{
"docstring": "记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将",
"name": "getMaxValue",
"signature": "def getMaxValue(self, Arr, rows, cols)"
},
{
"docstring": "动态规划:构造二维动态规划矩阵,需要双层循环——可能会超出内存",
"name": "getMaxValue2",
"signature": "def getMaxValue2(self, Arr, rows, cols)"
},
{
"docstring": "动态规划:... | 3 | stack_v2_sparse_classes_30k_test_000063 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMaxValue(self, Arr, rows, cols): 记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将
- def getMaxValue2(self, Arr, rows, cols): 动态规划:构造二维动态规划矩阵,需要双层循环——可能会超出内存
- def getMaxValue3(self, Arr, rows... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMaxValue(self, Arr, rows, cols): 记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将
- def getMaxValue2(self, Arr, rows, cols): 动态规划:构造二维动态规划矩阵,需要双层循环——可能会超出内存
- def getMaxValue3(self, Arr, rows... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class Solution:
def getMaxValue(self, Arr, rows, cols):
"""记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将"""
<|body_0|>
def getMaxValue2(self, Arr, rows, cols):
"""动态规划:构造二维动态规划矩阵,需要双层循环——可能会超出内存"""
<|body_1|>
def getMaxValue3(self, Arr, rows, cols):
"""动态规划:构造一维动态规划矩阵,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getMaxValue(self, Arr, rows, cols):
"""记忆化搜索:构造二维动态规划矩阵,需要双层循环,每次都将"""
if len(Arr) == 0 or rows <= 0 or cols <= 0:
return 0
maxValue = [[0] * rows] * cols
for i in range(rows):
for j in range(cols):
up, left = (0, 0)
... | the_stack_v2_python_sparse | 剑指offer/补充1.礼物的最大价值.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 | |
b2e43cf9236edf1bf28002f259e1b4fb89048c8d | [
"super().__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\nhi... | <|body_start_0|>
super().__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|en... | inherits from tensorflow.keras.layers.Layer | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""inherits from tensorflow.keras.layers.Layer"""
def __init__(self, vocab, embedding, units, batch):
"""def init constructor"""
<|body_0|>
def initialize_hidden_state(self):
"""Initializes the hidden states"""
<|body_1|>
def call(self, x... | stack_v2_sparse_classes_36k_train_028832 | 1,293 | no_license | [
{
"docstring": "def init constructor",
"name": "__init__",
"signature": "def __init__(self, vocab, embedding, units, batch)"
},
{
"docstring": "Initializes the hidden states",
"name": "initialize_hidden_state",
"signature": "def initialize_hidden_state(self)"
},
{
"docstring": "t... | 3 | stack_v2_sparse_classes_30k_train_020937 | Implement the Python class `RNNEncoder` described below.
Class description:
inherits from tensorflow.keras.layers.Layer
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): def init constructor
- def initialize_hidden_state(self): Initializes the hidden states
- def call(self, x, in... | Implement the Python class `RNNEncoder` described below.
Class description:
inherits from tensorflow.keras.layers.Layer
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): def init constructor
- def initialize_hidden_state(self): Initializes the hidden states
- def call(self, x, in... | f887cfd48bb44bc4ac440e27014c82390994f04d | <|skeleton|>
class RNNEncoder:
"""inherits from tensorflow.keras.layers.Layer"""
def __init__(self, vocab, embedding, units, batch):
"""def init constructor"""
<|body_0|>
def initialize_hidden_state(self):
"""Initializes the hidden states"""
<|body_1|>
def call(self, x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""inherits from tensorflow.keras.layers.Layer"""
def __init__(self, vocab, embedding, units, batch):
"""def init constructor"""
super().__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | AhmedOmi/holbertonschool-machine_learning | train | 0 |
4c63fbd7c64251ffc4ab2e8b269460ee951a99fd | [
"queryset = model_admin.get_queryset(request)\nresults = queryset.values_list('country').order_by('country').distinct()\ndata = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])\nreturn data",
"value = self.value()\nif value == 'none':\n return qu... | <|body_start_0|>
queryset = model_admin.get_queryset(request)
results = queryset.values_list('country').order_by('country').distinct()
data = ((code[0] or 'none', dict(COUNTRIES).get(code[0], _('None'))) for code in results if code[0] not in ['None', ''])
return data
<|end_body_0|>
<|bo... | Filtre admin des pays des IPs | IPCountryFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IPCountryFilter:
"""Filtre admin des pays des IPs"""
def lookups(self, request, model_admin):
"""Renvoyer les options des pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_028833 | 1,802 | no_license | [
{
"docstring": "Renvoyer les options des pays",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Filtrer le queryset par le pays sélectionné",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010134 | Implement the Python class `IPCountryFilter` described below.
Class description:
Filtre admin des pays des IPs
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options des pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné | Implement the Python class `IPCountryFilter` described below.
Class description:
Filtre admin des pays des IPs
Method signatures and docstrings:
- def lookups(self, request, model_admin): Renvoyer les options des pays
- def queryset(self, request, queryset): Filtrer le queryset par le pays sélectionné
<|skeleton|>
c... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class IPCountryFilter:
"""Filtre admin des pays des IPs"""
def lookups(self, request, model_admin):
"""Renvoyer les options des pays"""
<|body_0|>
def queryset(self, request, queryset):
"""Filtrer le queryset par le pays sélectionné"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IPCountryFilter:
"""Filtre admin des pays des IPs"""
def lookups(self, request, model_admin):
"""Renvoyer les options des pays"""
queryset = model_admin.get_queryset(request)
results = queryset.values_list('country').order_by('country').distinct()
data = ((code[0] or 'none... | the_stack_v2_python_sparse | scoop/user/access/admin/filters.py | artscoop/scoop | train | 0 |
fb02d3d84fc24021136a445d340ab74ce2e0cb44 | [
"super(FFTConv, self).__init__()\nself.fftsize = FFTSize\nself.tilsize = TilSize\nself.krnsize = FFTSize - TilSize + 1\nself.ichnl = Wreal.shape[1]\nself.ochnl = Wreal.shape[0]\nself.binit = B\nself.k = K\nself.mode = Mode\nself.mask = np.zeros_like(Wreal, dtype=bool)\nprint(Wreal.shape)\nif opt.admm:\n self.wre... | <|body_start_0|>
super(FFTConv, self).__init__()
self.fftsize = FFTSize
self.tilsize = TilSize
self.krnsize = FFTSize - TilSize + 1
self.ichnl = Wreal.shape[1]
self.ochnl = Wreal.shape[0]
self.binit = B
self.k = K
self.mode = Mode
self.mask... | FFTConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFTConv:
def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'):
"""FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial weights [h,w,ichnl,ochnl] B: Initial spatial bias K: Keep K nonzeros values"""
<|body_0|>... | stack_v2_sparse_classes_36k_train_028834 | 7,874 | no_license | [
{
"docstring": "FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial weights [h,w,ichnl,ochnl] B: Initial spatial bias K: Keep K nonzeros values",
"name": "__init__",
"signature": "def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'... | 4 | stack_v2_sparse_classes_30k_train_012605 | Implement the Python class `FFTConv` described below.
Class description:
Implement the FFTConv class.
Method signatures and docstrings:
- def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'): FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial w... | Implement the Python class `FFTConv` described below.
Class description:
Implement the FFTConv class.
Method signatures and docstrings:
- def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'): FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial w... | b7ea8e6108b73094c53a3100645f14f3985278b1 | <|skeleton|>
class FFTConv:
def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'):
"""FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial weights [h,w,ichnl,ochnl] B: Initial spatial bias K: Keep K nonzeros values"""
<|body_0|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFTConv:
def __init__(self, FFTSize, TilSize, Wreal, Wimag, B, K, Mode='valid'):
"""FFTSize: FFT window size for kernel and input TilSize: Tile size when decomposing input W: Initial spatial weights [h,w,ichnl,ochnl] B: Initial spatial bias K: Keep K nonzeros values"""
super(FFTConv, self).__i... | the_stack_v2_python_sparse | src/utils/fftConvLayer.py | yuehniu/CNN.frequencyPruning | train | 0 | |
d0f4c7aab929c491e556f50ba681db002d29e4fe | [
"self.collection = str(collection)\nself.sizekey = str(sizekey)\nself.subvars = subvars\nself.maxlen = int(maxlen)\nself.target_columns = OrderedDict()\nself.target_columns[self.sizekey] = np.zeros(1, dtype=np.float32)\nif self.maxlen > 1:\n tree.Branch(self.sizekey, self.target_columns[self.sizekey], '{0}/F'.fo... | <|body_start_0|>
self.collection = str(collection)
self.sizekey = str(sizekey)
self.subvars = subvars
self.maxlen = int(maxlen)
self.target_columns = OrderedDict()
self.target_columns[self.sizekey] = np.zeros(1, dtype=np.float32)
if self.maxlen > 1:
tr... | Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get from the collection subvars (list of str): List of subbranches, e.g. ["pt", ... | Flatten | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Flatten:
"""Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get from the collection subvars (list of str)... | stack_v2_sparse_classes_36k_train_028835 | 7,967 | no_license | [
{
"docstring": "Given an output tree and the collection data, creates the branch values and branches Args: tree (TYPE): Description collection (str): Base name of the collection, e.g. \"jets\" sizekey (str): The branch that indexes the number of objects, e.g. \"njets\" subvars (list of str): List of subbranches... | 3 | stack_v2_sparse_classes_30k_train_018111 | Implement the Python class `Flatten` described below.
Class description:
Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get fr... | Implement the Python class `Flatten` described below.
Class description:
Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get fr... | 7792c96048e250e0008861062d4f63069204efeb | <|skeleton|>
class Flatten:
"""Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get from the collection subvars (list of str)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Flatten:
"""Flattens an input collection like jets_pt[njets], jets_phi[njets] to jets_pt_0...jets_pt_MAXLEN, jets_phi_0...jets_phi_MAXLEN Attributes: collection (str): Base name of the collection, e.g. "jets" maxlen (int): Maximum number of objects to get from the collection subvars (list of str): List of sub... | the_stack_v2_python_sparse | TTH/MEAnalysis/python/flattener.py | mmeinhard/CodeThesis | train | 0 |
a1bde53129f20def892088324f5f051d8b5b0018 | [
"super().__init__(websession, API_URL)\nself._oauth_session = oauth_session\nself._client_id = client_id\nself._client_secret = client_secret",
"if not self._oauth_session.valid_token:\n await self._oauth_session.async_ensure_token_valid()\nreturn cast(str, self._oauth_session.token['access_token'])",
"token... | <|body_start_0|>
super().__init__(websession, API_URL)
self._oauth_session = oauth_session
self._client_id = client_id
self._client_secret = client_secret
<|end_body_0|>
<|body_start_1|>
if not self._oauth_session.valid_token:
await self._oauth_session.async_ensure_t... | Provide Google Nest Device Access authentication tied to an OAuth2 based config entry. | AsyncConfigEntryAuth | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Ne... | stack_v2_sparse_classes_36k_train_028836 | 4,887 | permissive | [
{
"docstring": "Initialize Google Nest Device Access auth.",
"name": "__init__",
"signature": "def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None"
},
{
"docstring": "Return a valid access token for SDM ... | 3 | stack_v2_sparse_classes_30k_train_008289 | Implement the Python class `AsyncConfigEntryAuth` described below.
Class description:
Provide Google Nest Device Access authentication tied to an OAuth2 based config entry.
Method signatures and docstrings:
- def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_i... | Implement the Python class `AsyncConfigEntryAuth` described below.
Class description:
Provide Google Nest Device Access authentication tied to an OAuth2 based config entry.
Method signatures and docstrings:
- def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_i... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncConfigEntryAuth:
"""Provide Google Nest Device Access authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, client_id: str, client_secret: str) -> None:
"""Initialize Google Nest Device Acc... | the_stack_v2_python_sparse | homeassistant/components/nest/api.py | home-assistant/core | train | 35,501 |
0c13511c4dc20ec314d05cb7544dd6eceefcee2a | [
"if not self.root:\n self.root = None\n return\nnode = Node(value)\nif value < self.root.value:\n if not self.root.left:\n self.root.left = node\nelif not self.root.right:\n self.root.right = node",
"node = node or self.root\nif not self.root:\n return False\nif node.value == value:\n ret... | <|body_start_0|>
if not self.root:
self.root = None
return
node = Node(value)
if value < self.root.value:
if not self.root.left:
self.root.left = node
elif not self.root.right:
self.root.right = node
<|end_body_0|>
<|body_s... | BinarySearchTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
<|body_0|>
def contains(self, value, node=None):
"""Define a method named contains tha... | stack_v2_sparse_classes_36k_train_028837 | 2,902 | no_license | [
{
"docstring": "Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.",
"name": "add",
"signature": "def add(self, value)"
},
{
"docstring": "Define a method named contains that accepts a value, and returns a boolea... | 2 | stack_v2_sparse_classes_30k_train_007853 | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def add(self, value): Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.
- def... | Implement the Python class `BinarySearchTree` described below.
Class description:
Implement the BinarySearchTree class.
Method signatures and docstrings:
- def add(self, value): Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree.
- def... | a0d681ce73ae284980df3a88e437ebb23ffed5eb | <|skeleton|>
class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
<|body_0|>
def contains(self, value, node=None):
"""Define a method named contains tha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BinarySearchTree:
def add(self, value):
"""Define a method named add that accepts a value, and adds a new node with that value in the correct location in the binary search tree."""
if not self.root:
self.root = None
return
node = Node(value)
if value < s... | the_stack_v2_python_sparse | Data-Structures/tree/tree.py | AmyE29/python-data-structures-and-algorithms | train | 0 | |
ee7b959f12a81d2d981a9ebf5c2fdb4cef154f76 | [
"super(InfoGAN_Discriminator, self).__init__()\nself.n_layer = n_layer\nself.n_conti = n_conti\nself.n_discrete = n_discrete\nself.num_category = num_category\nself.featmap_dim = featmap_dim\nconvs = []\nBNs = []\nfor layer in range(self.n_layer):\n if layer == self.n_layer - 1:\n n_conv_in = n_channel\n ... | <|body_start_0|>
super(InfoGAN_Discriminator, self).__init__()
self.n_layer = n_layer
self.n_conti = n_conti
self.n_discrete = n_discrete
self.num_category = num_category
self.featmap_dim = featmap_dim
convs = []
BNs = []
for layer in range(self.n_... | InfoGAN_Discriminator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoGAN_Discriminator:
def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Discriminator, have additional outputs for latent codes. Architecture brought from DCGAN."""
<|body_0|>
def forward(self, x... | stack_v2_sparse_classes_36k_train_028838 | 19,546 | no_license | [
{
"docstring": "InfoGAN Discriminator, have additional outputs for latent codes. Architecture brought from DCGAN.",
"name": "__init__",
"signature": "def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1)"
},
{
"docstring": "Output th... | 2 | stack_v2_sparse_classes_30k_val_000317 | Implement the Python class `InfoGAN_Discriminator` described below.
Class description:
Implement the InfoGAN_Discriminator class.
Method signatures and docstrings:
- def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Discriminator, have additi... | Implement the Python class `InfoGAN_Discriminator` described below.
Class description:
Implement the InfoGAN_Discriminator class.
Method signatures and docstrings:
- def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1): InfoGAN Discriminator, have additi... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class InfoGAN_Discriminator:
def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Discriminator, have additional outputs for latent codes. Architecture brought from DCGAN."""
<|body_0|>
def forward(self, x... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfoGAN_Discriminator:
def __init__(self, n_layer=3, n_conti=2, n_discrete=1, num_category=10, use_gpu=False, featmap_dim=256, n_channel=1):
"""InfoGAN Discriminator, have additional outputs for latent codes. Architecture brought from DCGAN."""
super(InfoGAN_Discriminator, self).__init__()
... | the_stack_v2_python_sparse | generated/test_AaronYALai_Generative_Adversarial_Networks_PyTorch.py | jansel/pytorch-jit-paritybench | train | 35 | |
97ebce496fec0e631051250b8233f33e37cfd559 | [
"n = len(A)\npq = Queue.PriorityQueue()\n\nclass Nd(object):\n\n def __init__(self, x, y):\n self.p = x\n self.q = y\n\n def __cmp__(self, other):\n return cmp(A[self.p] * 1.0 / A[self.q], A[other.p] * 1.0 / A[other.q])\nk = K\nvis = [[0 for i in xrange(n)] for j in xrange(n)]\n\ndef vali... | <|body_start_0|>
n = len(A)
pq = Queue.PriorityQueue()
class Nd(object):
def __init__(self, x, y):
self.p = x
self.q = y
def __cmp__(self, other):
return cmp(A[self.p] * 1.0 / A[self.q], A[other.p] * 1.0 / A[other.q])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def kthSmallestPrimeFractionTLE(self, A, K):
""":type A: List[int] :type K: int :rtype: List[int]"""
<|body_0|>
def kthSmallestPrimeFraction(self, A, K):
""":type A: List[int] :type K: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_st... | stack_v2_sparse_classes_36k_train_028839 | 2,190 | no_license | [
{
"docstring": ":type A: List[int] :type K: int :rtype: List[int]",
"name": "kthSmallestPrimeFractionTLE",
"signature": "def kthSmallestPrimeFractionTLE(self, A, K)"
},
{
"docstring": ":type A: List[int] :type K: int :rtype: List[int]",
"name": "kthSmallestPrimeFraction",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallestPrimeFractionTLE(self, A, K): :type A: List[int] :type K: int :rtype: List[int]
- def kthSmallestPrimeFraction(self, A, K): :type A: List[int] :type K: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def kthSmallestPrimeFractionTLE(self, A, K): :type A: List[int] :type K: int :rtype: List[int]
- def kthSmallestPrimeFraction(self, A, K): :type A: List[int] :type K: int :rtype:... | 02ebe56cd92b9f4baeee132c5077892590018650 | <|skeleton|>
class Solution:
def kthSmallestPrimeFractionTLE(self, A, K):
""":type A: List[int] :type K: int :rtype: List[int]"""
<|body_0|>
def kthSmallestPrimeFraction(self, A, K):
""":type A: List[int] :type K: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def kthSmallestPrimeFractionTLE(self, A, K):
""":type A: List[int] :type K: int :rtype: List[int]"""
n = len(A)
pq = Queue.PriorityQueue()
class Nd(object):
def __init__(self, x, y):
self.p = x
self.q = y
def ... | the_stack_v2_python_sparse | python/leetcode.786.py | CalvinNeo/LeetCode | train | 3 | |
c7ab3cf0404fe5ac98dc54572ddb24dd26a58afa | [
"self.capacity = capacity\nself.queue = deque()\nself.items = {}",
"if key in self.items:\n self.queue.remove(key)\n self.queue.appendleft(key)\n return self.items[key]\nelse:\n return -1",
"if key in self.items:\n self.queue.remove(key)\nelif len(self.queue) == self.capacity:\n del self.items... | <|body_start_0|>
self.capacity = capacity
self.queue = deque()
self.items = {}
<|end_body_0|>
<|body_start_1|>
if key in self.items:
self.queue.remove(key)
self.queue.appendleft(key)
return self.items[key]
else:
return -1
<|end_bod... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_028840 | 1,103 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_val_000943 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 3e66f89e02ade703715237722eda2fa2b135bb79 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.queue = deque()
self.items = {}
def get(self, key):
""":type key: int :rtype: int"""
if key in self.items:
self.queue.remove(key)
self.qu... | the_stack_v2_python_sparse | Amazon/Design/LRUCache.py | sameersaini/hackerank | train | 0 | |
840e7b9ec9da1bfb6e1ea03702b21c13e531bb2e | [
"layout = self.layout\ncolumn = layout.column()\ncolumn.label(text=self.target + ':')\nif self.bone == '':\n ConstraintButtons.main(ConstraintButtons, context, layout, bpy.data.objects[self.object].constraints[self.target])\nelif context.mode == 'POSE':\n ConstraintButtons.main(ConstraintButtons, context, lay... | <|body_start_0|>
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
if self.bone == '':
ConstraintButtons.main(ConstraintButtons, context, layout, bpy.data.objects[self.object].constraints[self.target])
elif context.mode == 'POSE':
... | This is operator is used to create the required pop-up panel. | constraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event)... | stack_v2_sparse_classes_36k_train_028841 | 17,024 | no_license | [
{
"docstring": "Draw the constraint options.",
"name": "draw",
"signature": "def draw(self, context)"
},
{
"docstring": "Execute the operator.",
"name": "execute",
"signature": "def execute(self, context)"
},
{
"docstring": "Invoke the operator panel/menu, control its width.",
... | 3 | stack_v2_sparse_classes_30k_train_001791 | Implement the Python class `constraint` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the constraint options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): In... | Implement the Python class `constraint` described below.
Class description:
This is operator is used to create the required pop-up panel.
Method signatures and docstrings:
- def draw(self, context): Draw the constraint options.
- def execute(self, context): Execute the operator.
- def invoke(self, context, event): In... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
<|body_0|>
def execute(self, context):
"""Execute the operator."""
<|body_1|>
def invoke(self, context, event)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class constraint:
"""This is operator is used to create the required pop-up panel."""
def draw(self, context):
"""Draw the constraint options."""
layout = self.layout
column = layout.column()
column.label(text=self.target + ':')
if self.bone == '':
Constraint... | the_stack_v2_python_sparse | All_In_One/addons/name_panel/scripts/operator/icon.py | 2434325680/Learnbgame | train | 0 |
f74120235cfced49f55798b4bf7d36fd68e3188f | [
"def preorder(root):\n if not root:\n return []\n return [root.val] + preorder(root.left) + preorder(root.right)\nreturn ' '.join([str(i) for i in preorder(root)])",
"data = [int(i) for i in data.split()]\n\ndef buildTree(data):\n if not data:\n return None\n root = TreeNode(data[0])\n ... | <|body_start_0|>
def preorder(root):
if not root:
return []
return [root.val] + preorder(root.left) + preorder(root.right)
return ' '.join([str(i) for i in preorder(root)])
<|end_body_0|>
<|body_start_1|>
data = [int(i) for i in data.split()]
def... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_028842 | 1,346 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def preorder(root):
if not root:
return []
return [root.val] + preorder(root.left) + preorder(root.right)
return ' '.join([str(i) for i in... | the_stack_v2_python_sparse | 0449_Serialize_and_Deserialize_BST.py | bingli8802/leetcode | train | 0 | |
4a76b24fa6e01a636115bf6580db88ddb5b821c7 | [
"H0_range = np.linspace(10, 100, 90)\nomega_m_range = np.linspace(0.05, 1, 95)\ngrid2d = np.dstack(np.meshgrid(H0_range, omega_m_range)).reshape(-1, 2)\nH0_grid = grid2d[:, 0]\nomega_m_grid = grid2d[:, 1]\nDd_grid = np.zeros_like(H0_grid)\nDs_Dds_grid = np.zeros_like(H0_grid)\nfor i in range(len(H0_grid)):\n Dd,... | <|body_start_0|>
H0_range = np.linspace(10, 100, 90)
omega_m_range = np.linspace(0.05, 1, 95)
grid2d = np.dstack(np.meshgrid(H0_range, omega_m_range)).reshape(-1, 2)
H0_grid = grid2d[:, 0]
omega_m_grid = grid2d[:, 1]
Dd_grid = np.zeros_like(H0_grid)
Ds_Dds_grid = ... | class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m | InvertCosmo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvertCosmo:
"""class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m"""
def _make_interpolation(self):
"""creates an interpolation grid in H_0, omega_m and computes quantities in Dd and Ds_Dds :return:"""
<|body_0|>
def get_cosmo... | stack_v2_sparse_classes_36k_train_028843 | 3,505 | permissive | [
{
"docstring": "creates an interpolation grid in H_0, omega_m and computes quantities in Dd and Ds_Dds :return:",
"name": "_make_interpolation",
"signature": "def _make_interpolation(self)"
},
{
"docstring": "return the values of H0 and omega_m computed with an interpolation :param Dd: flat :par... | 2 | stack_v2_sparse_classes_30k_val_000010 | Implement the Python class `InvertCosmo` described below.
Class description:
class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m
Method signatures and docstrings:
- def _make_interpolation(self): creates an interpolation grid in H_0, omega_m and computes quantities in Dd and... | Implement the Python class `InvertCosmo` described below.
Class description:
class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m
Method signatures and docstrings:
- def _make_interpolation(self): creates an interpolation grid in H_0, omega_m and computes quantities in Dd and... | dcdfc61ce5351ac94565228c822f1c94392c1ad6 | <|skeleton|>
class InvertCosmo:
"""class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m"""
def _make_interpolation(self):
"""creates an interpolation grid in H_0, omega_m and computes quantities in Dd and Ds_Dds :return:"""
<|body_0|>
def get_cosmo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvertCosmo:
"""class to do an interpolation and call the inverse of this interpolation to get H_0 and omega_m"""
def _make_interpolation(self):
"""creates an interpolation grid in H_0, omega_m and computes quantities in Dd and Ds_Dds :return:"""
H0_range = np.linspace(10, 100, 90)
... | the_stack_v2_python_sparse | lenstronomy/Cosmo/cosmo_solver.py | guoxiaowhu/lenstronomy | train | 1 |
5593bea058acff78672a3ff2d952182eb2c9dbf7 | [
"self._station_code = station_code\nself._calling_at = calling_at\nself._next_trains = []\nsensor_name = f'Next train to {calling_at}'\nquery_url = f'train/station/{station_code}/live.json'\nUkTransportSensor.__init__(self, sensor_name, api_app_id, api_app_key, query_url)\nself.update = Throttle(interval)(self._upd... | <|body_start_0|>
self._station_code = station_code
self._calling_at = calling_at
self._next_trains = []
sensor_name = f'Next train to {calling_at}'
query_url = f'train/station/{station_code}/live.json'
UkTransportSensor.__init__(self, sensor_name, api_app_id, api_app_key,... | Live train time sensor from UK transportapi.com. | UkTransportLiveTrainTimeSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UkTransportLiveTrainTimeSensor:
"""Live train time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval):
"""Construct a live bus time sensor."""
<|body_0|>
def _update(self):
"""Get the latest live de... | stack_v2_sparse_classes_36k_train_028844 | 9,762 | permissive | [
{
"docstring": "Construct a live bus time sensor.",
"name": "__init__",
"signature": "def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval)"
},
{
"docstring": "Get the latest live departure data for the specified stop.",
"name": "_update",
"signature": "def _upd... | 3 | null | Implement the Python class `UkTransportLiveTrainTimeSensor` described below.
Class description:
Live train time sensor from UK transportapi.com.
Method signatures and docstrings:
- def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval): Construct a live bus time sensor.
- def _update(self): G... | Implement the Python class `UkTransportLiveTrainTimeSensor` described below.
Class description:
Live train time sensor from UK transportapi.com.
Method signatures and docstrings:
- def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval): Construct a live bus time sensor.
- def _update(self): G... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class UkTransportLiveTrainTimeSensor:
"""Live train time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval):
"""Construct a live bus time sensor."""
<|body_0|>
def _update(self):
"""Get the latest live de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UkTransportLiveTrainTimeSensor:
"""Live train time sensor from UK transportapi.com."""
def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval):
"""Construct a live bus time sensor."""
self._station_code = station_code
self._calling_at = calling_at
s... | the_stack_v2_python_sparse | homeassistant/components/uk_transport/sensor.py | home-assistant/core | train | 35,501 |
c258acbae6ae508f22572c91473380ead503130e | [
"vowels = 'aeiou'\nlst = list(s)\nl, r = (0, len(s) - 1)\nwhile l <= r:\n if lst[l].lower() not in vowels:\n l += 1\n elif lst[r].lower() not in vowels:\n r -= 1\n else:\n lst[l], lst[r] = (lst[r], lst[l])\n l += 1\n r -= 1\nreturn ''.join(lst)",
"vowels = re.findall('[... | <|body_start_0|>
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s) - 1)
while l <= r:
if lst[l].lower() not in vowels:
l += 1
elif lst[r].lower() not in vowels:
r -= 1
else:
lst[l], lst[r] = (lst[r], lst[l... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s)... | stack_v2_sparse_classes_36k_train_028845 | 861 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels",
"signature": "def reverseVowels(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "reverseVowels2",
"signature": "def reverseVowels2(self, s)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseVowels(self, s): :type s: str :rtype: str
- def reverseVowels2(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def reverseVowels(self, s):
... | 0ac672a1582707fcaa6b6ad1f2a1d927034447df | <|skeleton|>
class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def reverseVowels2(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseVowels(self, s):
""":type s: str :rtype: str"""
vowels = 'aeiou'
lst = list(s)
l, r = (0, len(s) - 1)
while l <= r:
if lst[l].lower() not in vowels:
l += 1
elif lst[r].lower() not in vowels:
r ... | the_stack_v2_python_sparse | Chapter01_ArrayProblem/leetcode345.py | HuichuanLI/alogritme-interview | train | 1 | |
39053fb1f97ced82614ed7dd612cfe1f84f6dc1b | [
"self.typology = 'SimpleFault'\nself.source_id = identifier\nself.name = name\nself.tectonic_region_type = tectonic_region\nself.aspect_ratio = aspect_ratio\nself.mfd = None\nself.msr = None\nif upper_depth < 0.0:\n raise ValueError('Upper Depth Must be Non Negative')\nif lower_depth < 0.0 or lower_depth < upper... | <|body_start_0|>
self.typology = 'SimpleFault'
self.source_id = identifier
self.name = name
self.tectonic_region_type = tectonic_region
self.aspect_ratio = aspect_ratio
self.mfd = None
self.msr = None
if upper_depth < 0.0:
raise ValueError('Upp... | New class to describe the mtk Simple fault source object | mtkSimpleFaultSource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, fault_trace, dip, upper_depth, lower_depth, mesh_spacing=1.0):
"""Instantiate class with just the basic attributes :param identifie... | stack_v2_sparse_classes_36k_train_028846 | 5,539 | no_license | [
{
"docstring": "Instantiate class with just the basic attributes :param identifier: Integer ID code for the source :param name: Source Name (string) :param tectonic_region: Tectonic Region Type (String) :param aspect_ratio: Ratio of along-strike length to down-dip width (float) :param fault_trace: Surface trace... | 2 | stack_v2_sparse_classes_30k_train_001140 | Implement the Python class `mtkSimpleFaultSource` described below.
Class description:
New class to describe the mtk Simple fault source object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, fault_trace, dip, upper_depth, lower_depth, mesh_spacing=1.0): Instanti... | Implement the Python class `mtkSimpleFaultSource` described below.
Class description:
New class to describe the mtk Simple fault source object
Method signatures and docstrings:
- def __init__(self, identifier, name, tectonic_region, aspect_ratio, fault_trace, dip, upper_depth, lower_depth, mesh_spacing=1.0): Instanti... | cb98126555d54548f8e6ff8305eef15328930310 | <|skeleton|>
class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, fault_trace, dip, upper_depth, lower_depth, mesh_spacing=1.0):
"""Instantiate class with just the basic attributes :param identifie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mtkSimpleFaultSource:
"""New class to describe the mtk Simple fault source object"""
def __init__(self, identifier, name, tectonic_region, aspect_ratio, fault_trace, dip, upper_depth, lower_depth, mesh_spacing=1.0):
"""Instantiate class with just the basic attributes :param identifier: Integer ID... | the_stack_v2_python_sparse | seismicity_modeller/mtk/sources/mtk_simple_fault.py | g-weatherill/prototype_code | train | 0 |
651efcd1a4ea6736a294ef0f27409fc42281fbb0 | [
"namespace = self.read_req_string(root, self.NAMESPACE)\nif self.has(root, self.RESOURCES):\n self.__resources(namespace, root, data)\nif self.has(root, self.TYPES):\n self.__types(namespace, root, data)",
"resources = self.read_req_object(root, self.RESOURCES)\nnamespace_list = [namespace, self.read_req_st... | <|body_start_0|>
namespace = self.read_req_string(root, self.NAMESPACE)
if self.has(root, self.RESOURCES):
self.__resources(namespace, root, data)
if self.has(root, self.TYPES):
self.__types(namespace, root, data)
<|end_body_0|>
<|body_start_1|>
resources = self.... | Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES | YamlResourcesReader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YamlResourcesReader:
"""Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES"""
def parse(self, root, data):
"""Parse the style structure. Writes the parsed information into the data object."""
<|body_0|>
def __resources(self, na... | stack_v2_sparse_classes_36k_train_028847 | 1,938 | no_license | [
{
"docstring": "Parse the style structure. Writes the parsed information into the data object.",
"name": "parse",
"signature": "def parse(self, root, data)"
},
{
"docstring": "Parse resources.",
"name": "__resources",
"signature": "def __resources(self, namespace, root, data)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_019851 | Implement the Python class `YamlResourcesReader` described below.
Class description:
Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES
Method signatures and docstrings:
- def parse(self, root, data): Parse the style structure. Writes the parsed information into the data ob... | Implement the Python class `YamlResourcesReader` described below.
Class description:
Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES
Method signatures and docstrings:
- def parse(self, root, data): Parse the style structure. Writes the parsed information into the data ob... | c38b43edb7ec54f18768564c42859195bc2477e4 | <|skeleton|>
class YamlResourcesReader:
"""Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES"""
def parse(self, root, data):
"""Parse the style structure. Writes the parsed information into the data object."""
<|body_0|>
def __resources(self, na... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YamlResourcesReader:
"""Yaml reader for resource types. Constants: ENTITY NAME NAMESPACE RESOURCE RESOURCES TYPE TYPES"""
def parse(self, root, data):
"""Parse the style structure. Writes the parsed information into the data object."""
namespace = self.read_req_string(root, self.NAMESPACE... | the_stack_v2_python_sparse | python-prototype/config/resourcesreader.py | tea2code/fantasy-rts | train | 0 |
7eedc947434afaa8282d60b4fcbefb9a26cba7b3 | [
"self.zoo_obj = zoo_obj\nself.t = t\nself.f_info = f_info",
"distn = self.zoo_obj.get_distn(X)\nQ = self.zoo_obj.get_rate_matrix(X)\nreturn -self.f_info(Q, distn, self.t)"
] | <|body_start_0|>
self.zoo_obj = zoo_obj
self.t = t
self.f_info = f_info
<|end_body_0|>
<|body_start_1|>
distn = self.zoo_obj.get_distn(X)
Q = self.zoo_obj.get_rate_matrix(X)
return -self.f_info(Q, distn, self.t)
<|end_body_1|>
| OptDep | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptDep:
def __init__(self, zoo_obj, t, f_info):
"""@param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time"""
<|body_0|>
def __call__(self, X):
"""@param X: some log ratio probabiliti... | stack_v2_sparse_classes_36k_train_028848 | 5,413 | no_license | [
{
"docstring": "@param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time",
"name": "__init__",
"signature": "def __init__(self, zoo_obj, t, f_info)"
},
{
"docstring": "@param X: some log ratio probabilities @retur... | 2 | stack_v2_sparse_classes_30k_train_021148 | Implement the Python class `OptDep` described below.
Class description:
Implement the OptDep class.
Method signatures and docstrings:
- def __init__(self, zoo_obj, t, f_info): @param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time
- ... | Implement the Python class `OptDep` described below.
Class description:
Implement the OptDep class.
Method signatures and docstrings:
- def __init__(self, zoo_obj, t, f_info): @param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time
- ... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class OptDep:
def __init__(self, zoo_obj, t, f_info):
"""@param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time"""
<|body_0|>
def __call__(self, X):
"""@param X: some log ratio probabiliti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptDep:
def __init__(self, zoo_obj, t, f_info):
"""@param zoo_obj: an object from the evozoo module @param t: divergence time @param f_info: info function that takes a rate matrix and a time"""
self.zoo_obj = zoo_obj
self.t = t
self.f_info = f_info
def __call__(self, X):
... | the_stack_v2_python_sparse | 20120531a.py | argriffing/xgcode | train | 1 | |
bb9c313f4e43ad43334f9e63121f8ab9639d4ccd | [
"self.cluster_entity = cluster_entity\nself.datacenter_entity = datacenter_entity\nself.power_state_config = power_state_config\nself.rename_restored_object_param = rename_restored_object_param\nself.restored_objects_network_config = restored_objects_network_config\nself.storagedomain_entity = storagedomain_entity"... | <|body_start_0|>
self.cluster_entity = cluster_entity
self.datacenter_entity = datacenter_entity
self.power_state_config = power_state_config
self.rename_restored_object_param = rename_restored_object_param
self.restored_objects_network_config = restored_objects_network_config
... | Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. power_state_config (Pow... | RestoreKVMVMsParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest stat... | stack_v2_sparse_classes_36k_train_028849 | 4,642 | permissive | [
{
"docstring": "Constructor for the RestoreKVMVMsParams class",
"name": "__init__",
"signature": "def __init__(self, cluster_entity=None, datacenter_entity=None, power_state_config=None, rename_restored_object_param=None, restored_objects_network_config=None, storagedomain_entity=None)"
},
{
"do... | 2 | stack_v2_sparse_classes_30k_train_000690 | Implement the Python class `RestoreKVMVMsParams` described below.
Class description:
Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Speci... | Implement the Python class `RestoreKVMVMsParams` described below.
Class description:
Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Speci... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest stat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreKVMVMsParams:
"""Implementation of the 'RestoreKVMVMsParams' model. TODO: type model description here. Attributes: cluster_entity (EntityProto): Specifies the attributes and the latest statistics about an entity. datacenter_entity (EntityProto): Specifies the attributes and the latest statistics about ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_kvmv_ms_params.py | cohesity/management-sdk-python | train | 24 |
749cb62adc0e5f60e11a859c015727f20c46d617 | [
"clf = None\nif not is_categorical:\n clf = neighbors.KNeighborsRegressor(n_neighbors=k)\nelse:\n clf = neighbors.KNeighborsClassifier(n_neighbors=k)\nmissing_idxes = np.where(pd.isnull(X[:, column]))[0]\nif len(missing_idxes) == 0:\n return None\nX_copy = np.delete(X, missing_idxes, 0)\nX_train = np.delet... | <|body_start_0|>
clf = None
if not is_categorical:
clf = neighbors.KNeighborsRegressor(n_neighbors=k)
else:
clf = neighbors.KNeighborsClassifier(n_neighbors=k)
missing_idxes = np.where(pd.isnull(X[:, column]))[0]
if len(missing_idxes) == 0:
ret... | Imputer class. | Imputer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti... | stack_v2_sparse_classes_36k_train_028850 | 4,549 | no_license | [
{
"docstring": "Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or categorical feature - Returns: clf: trained k nearest neighbour classifier",
"name": "_... | 4 | stack_v2_sparse_classes_30k_train_010098 | Implement the Python class `Imputer` described below.
Class description:
Imputer class.
Method signatures and docstrings:
- def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares... | Implement the Python class `Imputer` described below.
Class description:
Imputer class.
Method signatures and docstrings:
- def _fit(self, X, column, k=10, is_categorical=False): Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of neares... | f940ab166ba57f06288a64ae0b6978c11450a806 | <|skeleton|>
class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is conti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Imputer:
"""Imputer class."""
def _fit(self, X, column, k=10, is_categorical=False):
"""Fit a knn classifier for missing column. - Args: X(numpy.ndarray): input data column(int): column id to be imputed k(int): number of nearest neighbors, default 10 is_categorical(boolean): is continuous or cate... | the_stack_v2_python_sparse | ForML/imputerBybwanglzu.py | JRLi/untitled | train | 0 |
d65bec5d7bf6d022f0e3faabb8f4b54a381bde70 | [
"self.head = Node(value) if value else None\nself.tail = self.head if self.head else None\nself.length = 1 if value else 0",
"if not new_value:\n return False\nelif self.tail:\n isAdded = self.tail.add_value(new_value)\n self.tail = self.tail.next_node\n self.length += 1\n return isAdded\nelse:\n ... | <|body_start_0|>
self.head = Node(value) if value else None
self.tail = self.head if self.head else None
self.length = 1 if value else 0
<|end_body_0|>
<|body_start_1|>
if not new_value:
return False
elif self.tail:
isAdded = self.tail.add_value(new_value... | DoublyLinkedList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
<|body_0|>
def add_value(self, new_value=None):
"""Adds a new value to the Doubly-Linked List"""
<|body_1|>
def sort_list(self):
"""Sor... | stack_v2_sparse_classes_36k_train_028851 | 4,372 | permissive | [
{
"docstring": "Constructor for instantiating a new Doubly-Linked List",
"name": "__init__",
"signature": "def __init__(self, value=None)"
},
{
"docstring": "Adds a new value to the Doubly-Linked List",
"name": "add_value",
"signature": "def add_value(self, new_value=None)"
},
{
... | 5 | null | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, value=None): Constructor for instantiating a new Doubly-Linked List
- def add_value(self, new_value=None): Adds a new value to the Doubly-Linke... | Implement the Python class `DoublyLinkedList` described below.
Class description:
Implement the DoublyLinkedList class.
Method signatures and docstrings:
- def __init__(self, value=None): Constructor for instantiating a new Doubly-Linked List
- def add_value(self, new_value=None): Adds a new value to the Doubly-Linke... | 27ffb6b32d6d18d279c51cfa45bf305a409be5c2 | <|skeleton|>
class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
<|body_0|>
def add_value(self, new_value=None):
"""Adds a new value to the Doubly-Linked List"""
<|body_1|>
def sort_list(self):
"""Sor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoublyLinkedList:
def __init__(self, value=None):
"""Constructor for instantiating a new Doubly-Linked List"""
self.head = Node(value) if value else None
self.tail = self.head if self.head else None
self.length = 1 if value else 0
def add_value(self, new_value=None):
... | the_stack_v2_python_sparse | src/daily-coding-problem/medium/sort-linked-list/sort_linked_list.py | nwthomas/code-challenges | train | 2 | |
15fab9ef1e7b32434d9902f8a627b5241df7d943 | [
"self.access_token = auth_cofense(COFENSE_TO_SENTINEL)\nself.proxy = create_proxy()\nself.headers = {'Accept': 'application/vnd.api+json', 'Content-Type': 'application/vnd.api+json', 'Authorization': 'Bearer ' + self.access_token}",
"__method_name = inspect.currentframe().f_code.co_name\ntry:\n retry_count_429... | <|body_start_0|>
self.access_token = auth_cofense(COFENSE_TO_SENTINEL)
self.proxy = create_proxy()
self.headers = {'Accept': 'application/vnd.api+json', 'Content-Type': 'application/vnd.api+json', 'Authorization': 'Bearer ' + self.access_token}
<|end_body_0|>
<|body_start_1|>
__method_n... | This class contains methods to pull the data from cofense apis and transform it to create TI indicator. | CofenseTriage | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CofenseTriage:
"""This class contains methods to pull the data from cofense apis and transform it to create TI indicator."""
def __init__(self):
"""Initialize instance variable for class."""
<|body_0|>
def get_indicators_from_cofense(self, url, params):
"""Pull t... | stack_v2_sparse_classes_36k_train_028852 | 3,900 | permissive | [
{
"docstring": "Initialize instance variable for class.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Pull the cofense indicators from REST APIs of Cofense.",
"name": "get_indicators_from_cofense",
"signature": "def get_indicators_from_cofense(self, url, para... | 2 | null | Implement the Python class `CofenseTriage` described below.
Class description:
This class contains methods to pull the data from cofense apis and transform it to create TI indicator.
Method signatures and docstrings:
- def __init__(self): Initialize instance variable for class.
- def get_indicators_from_cofense(self,... | Implement the Python class `CofenseTriage` described below.
Class description:
This class contains methods to pull the data from cofense apis and transform it to create TI indicator.
Method signatures and docstrings:
- def __init__(self): Initialize instance variable for class.
- def get_indicators_from_cofense(self,... | 4536a3f6b9bdef902312b3d96f9c2e66b8bf52c1 | <|skeleton|>
class CofenseTriage:
"""This class contains methods to pull the data from cofense apis and transform it to create TI indicator."""
def __init__(self):
"""Initialize instance variable for class."""
<|body_0|>
def get_indicators_from_cofense(self, url, params):
"""Pull t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CofenseTriage:
"""This class contains methods to pull the data from cofense apis and transform it to create TI indicator."""
def __init__(self):
"""Initialize instance variable for class."""
self.access_token = auth_cofense(COFENSE_TO_SENTINEL)
self.proxy = create_proxy()
... | the_stack_v2_python_sparse | Solutions/CofenseTriage/Data Connectors/CofenseTriageDataConnector/CofenseBasedIndicatorCreator/cofense.py | Azure/Azure-Sentinel | train | 3,697 |
c81624c4783dc646905660330cd168870740eaf9 | [
"n = Nim([2, 3, 4])\nn = Nim([1, 1, 1])\nn = Nim([2, 3, 4, 5, 6])",
"n = Nim([2, 3, 4])\nself.assertEqual(n.isover(), False)\nn = Nim([2, 0, 1])\nself.assertEqual(n.isover(), False)\nn = Nim([0, 1, 0])\nself.assertEqual(n.isover(), True)",
"n = Nim([1, 2, 1])\nnmoves = n.moves()\nmoveslist = []\nfor mv in nmove... | <|body_start_0|>
n = Nim([2, 3, 4])
n = Nim([1, 1, 1])
n = Nim([2, 3, 4, 5, 6])
<|end_body_0|>
<|body_start_1|>
n = Nim([2, 3, 4])
self.assertEqual(n.isover(), False)
n = Nim([2, 0, 1])
self.assertEqual(n.isover(), False)
n = Nim([0, 1, 0])
self.a... | Tests for the Nim data structure | TestNim | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestNim:
"""Tests for the Nim data structure"""
def testinit(self):
"""Test the initializer"""
<|body_0|>
def testisover(self):
"""Test isover()"""
<|body_1|>
def testmoves(self):
"""Test moves()"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_028853 | 1,196 | no_license | [
{
"docstring": "Test the initializer",
"name": "testinit",
"signature": "def testinit(self)"
},
{
"docstring": "Test isover()",
"name": "testisover",
"signature": "def testisover(self)"
},
{
"docstring": "Test moves()",
"name": "testmoves",
"signature": "def testmoves(sel... | 3 | stack_v2_sparse_classes_30k_test_000557 | Implement the Python class `TestNim` described below.
Class description:
Tests for the Nim data structure
Method signatures and docstrings:
- def testinit(self): Test the initializer
- def testisover(self): Test isover()
- def testmoves(self): Test moves() | Implement the Python class `TestNim` described below.
Class description:
Tests for the Nim data structure
Method signatures and docstrings:
- def testinit(self): Test the initializer
- def testisover(self): Test isover()
- def testmoves(self): Test moves()
<|skeleton|>
class TestNim:
"""Tests for the Nim data st... | bfbe91d698e650d78c20fd535c45108a8dba1030 | <|skeleton|>
class TestNim:
"""Tests for the Nim data structure"""
def testinit(self):
"""Test the initializer"""
<|body_0|>
def testisover(self):
"""Test isover()"""
<|body_1|>
def testmoves(self):
"""Test moves()"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestNim:
"""Tests for the Nim data structure"""
def testinit(self):
"""Test the initializer"""
n = Nim([2, 3, 4])
n = Nim([1, 1, 1])
n = Nim([2, 3, 4, 5, 6])
def testisover(self):
"""Test isover()"""
n = Nim([2, 3, 4])
self.assertEqual(n.isover... | the_stack_v2_python_sparse | Labs/Lab 11_ Game Starter Code/testgame.py | AlbMej/CSE-2050-Data-Structures-and-Object-Oriented-Design | train | 0 |
bf242df11a7dc89244883c4a3c23d5ea7b035951 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the FeedItemSetLink service. Service to manage feed item set links. | FeedItemSetLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeedItemSetLinkServiceServicer:
"""Proto file describing the FeedItemSetLink service. Service to manage feed item set links."""
def GetFeedItemSetLink(self, request, context):
"""Returns the requested feed item set link in full detail."""
<|body_0|>
def MutateFeedItemSet... | stack_v2_sparse_classes_36k_train_028854 | 5,744 | permissive | [
{
"docstring": "Returns the requested feed item set link in full detail.",
"name": "GetFeedItemSetLink",
"signature": "def GetFeedItemSetLink(self, request, context)"
},
{
"docstring": "Creates, updates, or removes feed item set links.",
"name": "MutateFeedItemSetLinks",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_015572 | Implement the Python class `FeedItemSetLinkServiceServicer` described below.
Class description:
Proto file describing the FeedItemSetLink service. Service to manage feed item set links.
Method signatures and docstrings:
- def GetFeedItemSetLink(self, request, context): Returns the requested feed item set link in full... | Implement the Python class `FeedItemSetLinkServiceServicer` described below.
Class description:
Proto file describing the FeedItemSetLink service. Service to manage feed item set links.
Method signatures and docstrings:
- def GetFeedItemSetLink(self, request, context): Returns the requested feed item set link in full... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class FeedItemSetLinkServiceServicer:
"""Proto file describing the FeedItemSetLink service. Service to manage feed item set links."""
def GetFeedItemSetLink(self, request, context):
"""Returns the requested feed item set link in full detail."""
<|body_0|>
def MutateFeedItemSet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeedItemSetLinkServiceServicer:
"""Proto file describing the FeedItemSetLink service. Service to manage feed item set links."""
def GetFeedItemSetLink(self, request, context):
"""Returns the requested feed item set link in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/feed_item_set_link_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
b3526a249fcb888daf9e58dc196d3cefdf584119 | [
"logger.info({'message': 'awaiting matching', 'plate': plate})\ntry:\n parking_space = (yield AvailableParkingSpacePool.read_one(plate=plate))\n if parking_space.is_active:\n raise AwaitingMatching\nexcept NoResultFound:\n try:\n parking_space = (yield cls._post_new_parking_space(plate=plate)... | <|body_start_0|>
logger.info({'message': 'awaiting matching', 'plate': plate})
try:
parking_space = (yield AvailableParkingSpacePool.read_one(plate=plate))
if parking_space.is_active:
raise AwaitingMatching
except NoResultFound:
try:
... | ParkingSpaceService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSpaceService:
def post_parking_space(cls, plate):
"""Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the other user if matching successfully, otherwise throw exception after timeout :param str plate: plate of the... | stack_v2_sparse_classes_36k_train_028855 | 10,220 | no_license | [
{
"docstring": "Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the other user if matching successfully, otherwise throw exception after timeout :param str plate: plate of the vehicle in the parking space :return parking_space: parking_space :... | 4 | null | Implement the Python class `ParkingSpaceService` described below.
Class description:
Implement the ParkingSpaceService class.
Method signatures and docstrings:
- def post_parking_space(cls, plate): Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the... | Implement the Python class `ParkingSpaceService` described below.
Class description:
Implement the ParkingSpaceService class.
Method signatures and docstrings:
- def post_parking_space(cls, plate): Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the... | fd759c16b9864f6b1b47b1ba3f1af77f8d08af20 | <|skeleton|>
class ParkingSpaceService:
def post_parking_space(cls, plate):
"""Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the other user if matching successfully, otherwise throw exception after timeout :param str plate: plate of the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParkingSpaceService:
def post_parking_space(cls, plate):
"""Publish a checked-in parking space to the Available Parking Space Pool Return a real time loc token with location of the other user if matching successfully, otherwise throw exception after timeout :param str plate: plate of the vehicle in th... | the_stack_v2_python_sparse | ParkingFinder/services/parking_space.py | Big-Lemon/ParkingFinder | train | 2 | |
03616a4e5e7c906570b129961e8c5d71c38bce50 | [
"self.created_at = created_at\nself.id = id\nself.is_nfs_interface = is_nfs_interface\nself.is_smb_interface = is_smb_interface\nself.name = name\nself.protocols = protocols\nself.used_bytes = used_bytes\nself.uuid = uuid",
"if dictionary is None:\n return None\ncreated_at = dictionary.get('createdAt')\nid = d... | <|body_start_0|>
self.created_at = created_at
self.id = id
self.is_nfs_interface = is_nfs_interface
self.is_smb_interface = is_smb_interface
self.name = name
self.protocols = protocols
self.used_bytes = used_bytes
self.uuid = uuid
<|end_body_0|>
<|body_st... | Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile Container in a Cluster. is_nfs_interface (bool): Specifies if the container has NFS vol... | ElastifileContainer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElastifileContainer:
"""Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile Container in a Cluster. is_nfs_interface... | stack_v2_sparse_classes_36k_train_028856 | 3,291 | permissive | [
{
"docstring": "Constructor for the ElastifileContainer class",
"name": "__init__",
"signature": "def __init__(self, created_at=None, id=None, is_nfs_interface=None, is_smb_interface=None, name=None, protocols=None, used_bytes=None, uuid=None)"
},
{
"docstring": "Creates an instance of this mode... | 2 | stack_v2_sparse_classes_30k_train_004748 | Implement the Python class `ElastifileContainer` described below.
Class description:
Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile C... | Implement the Python class `ElastifileContainer` described below.
Class description:
Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile C... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ElastifileContainer:
"""Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile Container in a Cluster. is_nfs_interface... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElastifileContainer:
"""Implementation of the 'ElastifileContainer' model. Specifies information about container in an Elastifile Cluster. Attributes: created_at (string): Specifies the creation date of the container. id (int): Specifies id of a Elastifile Container in a Cluster. is_nfs_interface (bool): Spec... | the_stack_v2_python_sparse | cohesity_management_sdk/models/elastifile_container.py | cohesity/management-sdk-python | train | 24 |
04ff6c9a18d51f668a6d0132de24fa882c712995 | [
"self.rpcstatslist = []\nself.timestamp = statsproto.start_timestamp_milliseconds() * 0.001\nself.totalresponsetime = int(statsproto.duration_milliseconds())\nfor t in statsproto.individual_stats_list():\n self.AddRPCStats(t)\nself.totalrpctime = self.TotalRPCTime()",
"totalrpctime = 0\nfor rpc in self.rpcstat... | <|body_start_0|>
self.rpcstatslist = []
self.timestamp = statsproto.start_timestamp_milliseconds() * 0.001
self.totalresponsetime = int(statsproto.duration_milliseconds())
for t in statsproto.individual_stats_list():
self.AddRPCStats(t)
self.totalrpctime = self.TotalR... | Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request. | URLRequestStats | [
"Apache-2.0",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"GPL-2.0-or-later",
"MPL-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLRequestStats:
"""Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request."""
def __init__(self, statsproto):
"""Constructor."""
<|body_0|>
def Tota... | stack_v2_sparse_classes_36k_train_028857 | 13,320 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, statsproto)"
},
{
"docstring": "Compute total time spent in all RPCs.",
"name": "TotalRPCTime",
"signature": "def TotalRPCTime(self)"
},
{
"docstring": "Update statistics for a given RPC called fo... | 6 | null | Implement the Python class `URLRequestStats` described below.
Class description:
Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request.
Method signatures and docstrings:
- def __init__(self, stat... | Implement the Python class `URLRequestStats` described below.
Class description:
Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request.
Method signatures and docstrings:
- def __init__(self, stat... | be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f | <|skeleton|>
class URLRequestStats:
"""Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request."""
def __init__(self, statsproto):
"""Constructor."""
<|body_0|>
def Tota... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class URLRequestStats:
"""Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request."""
def __init__(self, statsproto):
"""Constructor."""
self.rpcstatslist = []
self.t... | the_stack_v2_python_sparse | AppServer/google/appengine/ext/analytics/stats.py | obino/appscale | train | 1 |
b83060636de10a57b4268a169cde11df08e1f4ce | [
"if not isinstance(user_id, int) or not isinstance(group_name, str):\n return (False, {'status': 'Invalid input'})\nuser_group_data = {'name': group_name, 'user_id': user_id}\nuser_group = session.query(UserGroup).filter(UserGroup.user_id == user_id, UserGroup.name == group_name).first()\nif user_group:\n ret... | <|body_start_0|>
if not isinstance(user_id, int) or not isinstance(group_name, str):
return (False, {'status': 'Invalid input'})
user_group_data = {'name': group_name, 'user_id': user_id}
user_group = session.query(UserGroup).filter(UserGroup.user_id == user_id, UserGroup.name == gro... | UserGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserGroup:
def insert(session, user_id: int, group_name: str) -> dict:
"""Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with status key that indicates the success of the operation Note: If group already exists the function w... | stack_v2_sparse_classes_36k_train_028858 | 42,539 | permissive | [
{
"docstring": "Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with status key that indicates the success of the operation Note: If group already exists the function will return that it has been added, but a duplicate group isn't added. It simply de... | 3 | null | Implement the Python class `UserGroup` described below.
Class description:
Implement the UserGroup class.
Method signatures and docstrings:
- def insert(session, user_id: int, group_name: str) -> dict: Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with s... | Implement the Python class `UserGroup` described below.
Class description:
Implement the UserGroup class.
Method signatures and docstrings:
- def insert(session, user_id: int, group_name: str) -> dict: Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with s... | 03e5cf8bef4cd6fd5c3458393d1ae839d7bcc3c3 | <|skeleton|>
class UserGroup:
def insert(session, user_id: int, group_name: str) -> dict:
"""Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with status key that indicates the success of the operation Note: If group already exists the function w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserGroup:
def insert(session, user_id: int, group_name: str) -> dict:
"""Add a group to the user. Args user_id: id of the user group_name: name of the group being added Returns: Dict with status key that indicates the success of the operation Note: If group already exists the function will return tha... | the_stack_v2_python_sparse | augur/application/db/models/augur_operations.py | chaoss/augur | train | 580 | |
b402fedd165b97de4032cb90d940543aff9f9d3b | [
"def dfs(left, right, n, path, res):\n if left == n and right == n:\n res.append(path)\n return\n if left < n:\n dfs(left + 1, right, n, path + '(', res)\n if right < left:\n dfs(left, right + 1, n, path + ')', res)\nres = []\ndfs(0, 0, n, '', res)\nreturn res",
"if n == 0:\n ... | <|body_start_0|>
def dfs(left, right, n, path, res):
if left == n and right == n:
res.append(path)
return
if left < n:
dfs(left + 1, right, n, path + '(', res)
if right < left:
dfs(left, right + 1, n, path + ')',... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis3(self, n):
"""闭合数 看不懂。 :param n: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_028859 | 2,370 | no_license | [
{
"docstring": "dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": "闭合数 看不懂。 :param n: :return:",
"name": "generateParenthesis3",
... | 3 | stack_v2_sparse_classes_30k_train_009100 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]
- def generateParenthesis3(self, n... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]
- def generateParenthesis3(self, n... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis3(self, n):
"""闭合数 看不懂。 :param n: :return:"""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n):
"""dfs添加所有有效括号 剪枝: 1. 每次可以放置左括号的条件是当前左括号的数目不超过n 2. 每次可以放置右括号的条件是当前右括号的数目不超过左括号的数目 :type n: int :rtype: List[str]"""
def dfs(left, right, n, path, res):
if left == n and right == n:
res.append(path)
return
... | the_stack_v2_python_sparse | 22_括号生成.py | lovehhf/LeetCode | train | 0 | |
bec1708975a581c9b0a899f17034f4d5d908db00 | [
"super().__init__()\nself.num_actions = num_actions\nself.embedding_size = embedding_size\nself.d2e = nn.Embedding(vocab_size, embedding_size)\nself.rnn = nn.GRUCell(embedding_size, embedding_size)\nself.h1 = nn.Linear(embedding_size, num_actions)",
"batch_size = utterance.size()[0]\nutterance_max = utterance.siz... | <|body_start_0|>
super().__init__()
self.num_actions = num_actions
self.embedding_size = embedding_size
self.d2e = nn.Embedding(vocab_size, embedding_size)
self.rnn = nn.GRUCell(embedding_size, embedding_size)
self.h1 = nn.Linear(embedding_size, num_actions)
<|end_body_0|... | Listener | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Listener:
def __init__(self, embedding_size, vocab_size, num_actions):
"""- input: utterance - output: action"""
<|body_0|>
def forward(self, utterance, global_idxes):
"""utterance etc might be sieved, which is why we receive global_idxes alive_masks will then create... | stack_v2_sparse_classes_36k_train_028860 | 16,840 | permissive | [
{
"docstring": "- input: utterance - output: action",
"name": "__init__",
"signature": "def __init__(self, embedding_size, vocab_size, num_actions)"
},
{
"docstring": "utterance etc might be sieved, which is why we receive global_idxes alive_masks will then create subsets of this already-sieved ... | 2 | stack_v2_sparse_classes_30k_train_008072 | Implement the Python class `Listener` described below.
Class description:
Implement the Listener class.
Method signatures and docstrings:
- def __init__(self, embedding_size, vocab_size, num_actions): - input: utterance - output: action
- def forward(self, utterance, global_idxes): utterance etc might be sieved, whic... | Implement the Python class `Listener` described below.
Class description:
Implement the Listener class.
Method signatures and docstrings:
- def __init__(self, embedding_size, vocab_size, num_actions): - input: utterance - output: action
- def forward(self, utterance, global_idxes): utterance etc might be sieved, whic... | 0286849d42d56a382820d4118b72cf6585e23160 | <|skeleton|>
class Listener:
def __init__(self, embedding_size, vocab_size, num_actions):
"""- input: utterance - output: action"""
<|body_0|>
def forward(self, utterance, global_idxes):
"""utterance etc might be sieved, which is why we receive global_idxes alive_masks will then create... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Listener:
def __init__(self, embedding_size, vocab_size, num_actions):
"""- input: utterance - output: action"""
super().__init__()
self.num_actions = num_actions
self.embedding_size = embedding_size
self.d2e = nn.Embedding(vocab_size, embedding_size)
self.rnn =... | the_stack_v2_python_sparse | mll/run_mll.py | Sandy4321/compositional-inductive-bias | train | 0 | |
256d5909a6f2498f0013ecea215dc525009e74b1 | [
"self.id = id\nself.name = name\nself.status = status\nself.estimate_inclusion = estimate_inclusion\nself.confidence = confidence\nself.cadence = cadence\nself.net_monthly = net_monthly\nself.net_annual = net_annual\nself.projected_net_annual = projected_net_annual\nself.estimated_gross_annual = estimated_gross_ann... | <|body_start_0|>
self.id = id
self.name = name
self.status = status
self.estimate_inclusion = estimate_inclusion
self.confidence = confidence
self.cadence = cadence
self.net_monthly = net_monthly
self.net_annual = net_annual
self.projected_net_annu... | Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream status (StatusEnum): active or inactive estimate_inclusion... | VOIReportIncomeStreamRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream sta... | stack_v2_sparse_classes_36k_train_028861 | 6,477 | permissive | [
{
"docstring": "Constructor for the VOIReportIncomeStreamRecord class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, status=None, estimate_inclusion=None, confidence=None, cadence=None, net_monthly=None, net_annual=None, projected_net_annual=None, estimated_gross_annual=None,... | 2 | null | Implement the Python class `VOIReportIncomeStreamRecord` described below.
Class description:
Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the ... | Implement the Python class `VOIReportIncomeStreamRecord` described below.
Class description:
Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the ... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream sta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VOIReportIncomeStreamRecord:
"""Implementation of the 'VOI Report Income Stream Record' model. VOI Report Income Stream Record Attributes: id (string): Finicity’s income stream ID name (string): A human-readable name based on the normalizedPayee name of the transactions for this income stream status (StatusEn... | the_stack_v2_python_sparse | finicityapi/models/voi_report_income_stream_record.py | monarchmoney/finicity-python | train | 0 |
74ea1a7712887485c37bfe30f267d382bbeb1fe3 | [
"self.logger = logging.getLogger(self.__class__.__name__)\nself.zk_client = zk_client\nself.section_name = section\nself.data = {}\nself._stopped = False\nself.section_node = '/appscale/config/{}'.format(section)\nself.watch = zk_client.DataWatch(self.section_node, self._update_section)",
"if self._stopped:\n ... | <|body_start_0|>
self.logger = logging.getLogger(self.__class__.__name__)
self.zk_client = zk_client
self.section_name = section
self.data = {}
self._stopped = False
self.section_node = '/appscale/config/{}'.format(section)
self.watch = zk_client.DataWatch(self.se... | Keeps track of a section of configuration data. | DeploymentConfigSection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeploymentConfigSection:
"""Keeps track of a section of configuration data."""
def __init__(self, zk_client, section):
"""Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a configuration section name."""
<|body_0|>
def e... | stack_v2_sparse_classes_36k_train_028862 | 5,420 | permissive | [
{
"docstring": "Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a configuration section name.",
"name": "__init__",
"signature": "def __init__(self, zk_client, section)"
},
{
"docstring": "Restart the watch if it has been cancelled.",
"name... | 3 | null | Implement the Python class `DeploymentConfigSection` described below.
Class description:
Keeps track of a section of configuration data.
Method signatures and docstrings:
- def __init__(self, zk_client, section): Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a con... | Implement the Python class `DeploymentConfigSection` described below.
Class description:
Keeps track of a section of configuration data.
Method signatures and docstrings:
- def __init__(self, zk_client, section): Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a con... | be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f | <|skeleton|>
class DeploymentConfigSection:
"""Keeps track of a section of configuration data."""
def __init__(self, zk_client, section):
"""Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a configuration section name."""
<|body_0|>
def e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeploymentConfigSection:
"""Keeps track of a section of configuration data."""
def __init__(self, zk_client, section):
"""Creates a new DeploymentConfigSection. Args: zk_client: A KazooClient. section: A string specifying a configuration section name."""
self.logger = logging.getLogger(se... | the_stack_v2_python_sparse | common/appscale/common/deployment_config.py | obino/appscale | train | 1 |
a3d8a0feb197cf9d6bbd52db340b014d1049fbb3 | [
"if not any((amount, hold_uri)):\n raise ResourceError('Must have amount or hold_uri')\nmeta = meta or {}\nparticipant = getattr(self, 'account', None) or self.customer\nreturn Debit(uri=participant.debits_uri, amount=amount, appears_on_statement_as=appears_on_statement_as, hold_uri=hold_uri, meta=meta, descript... | <|body_start_0|>
if not any((amount, hold_uri)):
raise ResourceError('Must have amount or hold_uri')
meta = meta or {}
participant = getattr(self, 'account', None) or self.customer
return Debit(uri=participant.debits_uri, amount=amount, appears_on_statement_as=appears_on_stat... | A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card. | Card | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Card:
"""A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card."""
def debit(self, amount=None, appears_on_statement_as=None, hold_uri=None, meta=None, description=None):
"""Creates a Debit of funds from this Card to... | stack_v2_sparse_classes_36k_train_028863 | 44,969 | no_license | [
{
"docstring": "Creates a Debit of funds from this Card to your Marketplace's escrow account. If `appears_on_statement_as` is nil, then Balanced will use the `domain_name` property from your Marketplace. :rtype: Debit",
"name": "debit",
"signature": "def debit(self, amount=None, appears_on_statement_as=... | 2 | null | Implement the Python class `Card` described below.
Class description:
A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card.
Method signatures and docstrings:
- def debit(self, amount=None, appears_on_statement_as=None, hold_uri=None, meta=None, desc... | Implement the Python class `Card` described below.
Class description:
A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card.
Method signatures and docstrings:
- def debit(self, amount=None, appears_on_statement_as=None, hold_uri=None, meta=None, desc... | c706683cf448dc5763bb2ce8ea2f5968fcefb375 | <|skeleton|>
class Card:
"""A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card."""
def debit(self, amount=None, appears_on_statement_as=None, hold_uri=None, meta=None, description=None):
"""Creates a Debit of funds from this Card to... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Card:
"""A card represents a source of funds for an Account. You may Hold or Debit funds from the account associated with the Card."""
def debit(self, amount=None, appears_on_statement_as=None, hold_uri=None, meta=None, description=None):
"""Creates a Debit of funds from this Card to your Marketp... | the_stack_v2_python_sparse | balanced/resources.py | elaineo/barnacle-gae | train | 0 |
0128e38667ef8026c1aa51c0d2c8516097af9435 | [
"if request.user.is_authenticated():\n appointment = Appointment.objects.get(id=appointment_id)\n user = UserFactory.get_user(request)\n if user != None and appointment.can_view(user):\n appointment_update_form = self.update_form_class(None)\n form_data = {'description': appointment.descripti... | <|body_start_0|>
if request.user.is_authenticated():
appointment = Appointment.objects.get(id=appointment_id)
user = UserFactory.get_user(request)
if user != None and appointment.can_view(user):
appointment_update_form = self.update_form_class(None)
... | Edit existing appointments using the UpdateAppointmentsForm | DoctorAppointmentEdit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DoctorAppointmentEdit:
"""Edit existing appointments using the UpdateAppointmentsForm"""
def get(self, request, appointment_id):
"""When loading the page, the fields should be filled with their existing values :param request: The user who is requesting the page :param appointment_id:... | stack_v2_sparse_classes_36k_train_028864 | 21,300 | no_license | [
{
"docstring": "When loading the page, the fields should be filled with their existing values :param request: The user who is requesting the page :param appointment_id: The unique id of the appointment to be edited :return: If the request is valid, a page that has a form loaded with the current appointment info... | 2 | stack_v2_sparse_classes_30k_train_017882 | Implement the Python class `DoctorAppointmentEdit` described below.
Class description:
Edit existing appointments using the UpdateAppointmentsForm
Method signatures and docstrings:
- def get(self, request, appointment_id): When loading the page, the fields should be filled with their existing values :param request: T... | Implement the Python class `DoctorAppointmentEdit` described below.
Class description:
Edit existing appointments using the UpdateAppointmentsForm
Method signatures and docstrings:
- def get(self, request, appointment_id): When loading the page, the fields should be filled with their existing values :param request: T... | 75cddb44ee24e1ec9916379b80739525dcee721c | <|skeleton|>
class DoctorAppointmentEdit:
"""Edit existing appointments using the UpdateAppointmentsForm"""
def get(self, request, appointment_id):
"""When loading the page, the fields should be filled with their existing values :param request: The user who is requesting the page :param appointment_id:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DoctorAppointmentEdit:
"""Edit existing appointments using the UpdateAppointmentsForm"""
def get(self, request, appointment_id):
"""When loading the page, the fields should be filled with their existing values :param request: The user who is requesting the page :param appointment_id: The unique i... | the_stack_v2_python_sparse | employee/views.py | kevuno/HealthNet | train | 0 |
b30c537409d91c0629cda5199c7b1648cc719525 | [
"def build_tree(nums, l, r):\n if l > r:\n return None\n if l == r:\n node = Node(l, r)\n node.val = nums[l]\n return node\n mid = (l + r) // 2\n node = Node(l, r)\n node.left = build_tree(nums, l, mid)\n node.right = build_tree(nums, mid + 1, r)\n node.val = node.le... | <|body_start_0|>
def build_tree(nums, l, r):
if l > r:
return None
if l == r:
node = Node(l, r)
node.val = nums[l]
return node
mid = (l + r) // 2
node = Node(l, r)
node.left = build_tree(n... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_028865 | 2,637 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | ede2a2e19f27ef4adf6e57d6692216b8990cf62b | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
def build_tree(nums, l, r):
if l > r:
return None
if l == r:
node = Node(l, r)
node.val = nums[l]
return node
mid = (l + r) // 2
... | the_stack_v2_python_sparse | range_sum_query_mutable.py | ShunKaiZhang/LeetCode | train | 0 | |
413973fe2c109f9747000d793dfa108bdbf7a173 | [
"self.map_func = map_func\nself.reduce_func = reduce_func\nself.pool = multiprocessing.Pool(num_workers)",
"partitioned_data = collections.defaultdict(list)\nfor key, value in mapped_values:\n partitioned_data[key].append(value)\nreturn partitioned_data.items()",
"map_responses = self.pool.map(self.map_func,... | <|body_start_0|>
self.map_func = map_func
self.reduce_func = reduce_func
self.pool = multiprocessing.Pool(num_workers)
<|end_body_0|>
<|body_start_1|>
partitioned_data = collections.defaultdict(list)
for key, value in mapped_values:
partitioned_data[key].append(value... | SimpleMapReduce | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of interm... | stack_v2_sparse_classes_36k_train_028866 | 2,086 | no_license | [
{
"docstring": "map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of intermediate data to final output. Takes as argument a key as produced by map_func and a sequen... | 3 | stack_v2_sparse_classes_30k_train_003701 | Implement the Python class `SimpleMapReduce` described below.
Class description:
Implement the SimpleMapReduce class.
Method signatures and docstrings:
- def __init__(self, map_func, reduce_func, num_workers=None): map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tu... | Implement the Python class `SimpleMapReduce` described below.
Class description:
Implement the SimpleMapReduce class.
Method signatures and docstrings:
- def __init__(self, map_func, reduce_func, num_workers=None): map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tu... | c3c554f14b378b487c632e11f22e5e3118be940c | <|skeleton|>
class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of interm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleMapReduce:
def __init__(self, map_func, reduce_func, num_workers=None):
"""map_func Function to map inputs to intermediate data.Takes as argument one input value and returns a tuple with the key and a value to be reduced. reduce_func Function to reduce partitioned version of intermediate data to... | the_stack_v2_python_sparse | Simple_Python/standard/multiprocessing/multiprocessing_24.py | yafeile/Simple_Study | train | 0 | |
ed43a7799d830fa862b8605648720556a5f46fde | [
"model_file = os.path.join(os.path.dirname(__file__), 'newsgroups_model.joblib')\nloaded_model: Tuple[Pipeline, List[str]] = joblib.load(model_file)\nmodel, targets = loaded_model\nself.model = model\nself.targets = targets",
"if not self.model or not self.targets:\n raise RuntimeError('Model is not loaded')\n... | <|body_start_0|>
model_file = os.path.join(os.path.dirname(__file__), 'newsgroups_model.joblib')
loaded_model: Tuple[Pipeline, List[str]] = joblib.load(model_file)
model, targets = loaded_model
self.model = model
self.targets = targets
<|end_body_0|>
<|body_start_1|>
if ... | NewsgroupsModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewsgroupsModel:
def load_model(self):
"""Loads the model"""
<|body_0|>
def predict(self, input: PredictionInput) -> PredictionOutput:
"""Runs a prediction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
model_file = os.path.join(os.path.dirname(__f... | stack_v2_sparse_classes_36k_train_028867 | 1,647 | permissive | [
{
"docstring": "Loads the model",
"name": "load_model",
"signature": "def load_model(self)"
},
{
"docstring": "Runs a prediction",
"name": "predict",
"signature": "def predict(self, input: PredictionInput) -> PredictionOutput"
}
] | 2 | null | Implement the Python class `NewsgroupsModel` described below.
Class description:
Implement the NewsgroupsModel class.
Method signatures and docstrings:
- def load_model(self): Loads the model
- def predict(self, input: PredictionInput) -> PredictionOutput: Runs a prediction | Implement the Python class `NewsgroupsModel` described below.
Class description:
Implement the NewsgroupsModel class.
Method signatures and docstrings:
- def load_model(self): Loads the model
- def predict(self, input: PredictionInput) -> PredictionOutput: Runs a prediction
<|skeleton|>
class NewsgroupsModel:
d... | 99b472d8295a57c5a74a63d8184ac053dc4012f2 | <|skeleton|>
class NewsgroupsModel:
def load_model(self):
"""Loads the model"""
<|body_0|>
def predict(self, input: PredictionInput) -> PredictionOutput:
"""Runs a prediction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewsgroupsModel:
def load_model(self):
"""Loads the model"""
model_file = os.path.join(os.path.dirname(__file__), 'newsgroups_model.joblib')
loaded_model: Tuple[Pipeline, List[str]] = joblib.load(model_file)
model, targets = loaded_model
self.model = model
self.... | the_stack_v2_python_sparse | chapter13/chapter13_caching.py | msg4rajesh/Building-Data-Science-Applications-with-FastAPI | train | 0 | |
1fdc70a281dcc9080b2b4180aa28d55e9a154226 | [
"if isinstance(obj, Decimal):\n return float(obj)\nif isinstance(obj, ObjectId):\n return str(obj)\nreturn super().default(obj)",
"if self.check_circular:\n markers = {}\nelse:\n markers = None\nif self.ensure_ascii:\n _encoder = json.encoder.encode_basestring_ascii\nelse:\n _encoder = json.enco... | <|body_start_0|>
if isinstance(obj, Decimal):
return float(obj)
if isinstance(obj, ObjectId):
return str(obj)
return super().default(obj)
<|end_body_0|>
<|body_start_1|>
if self.check_circular:
markers = {}
else:
markers = None
... | Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers. | EWAHJSONEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EWAHJSONEncoder:
"""Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers."""
def default(self, obj):
"""Method is called if an object cannot be serialized. Ought to return a serializeable value for the object. Ought t... | stack_v2_sparse_classes_36k_train_028868 | 10,358 | permissive | [
{
"docstring": "Method is called if an object cannot be serialized. Ought to return a serializeable value for the object. Ought to raise an error if unable to do so. Implemented types: - Decimal -> float - bson.objectid.ObjectId -> string",
"name": "default",
"signature": "def default(self, obj)"
},
... | 2 | stack_v2_sparse_classes_30k_train_012278 | Implement the Python class `EWAHJSONEncoder` described below.
Class description:
Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers.
Method signatures and docstrings:
- def default(self, obj): Method is called if an object cannot be serialized. Ough... | Implement the Python class `EWAHJSONEncoder` described below.
Class description:
Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers.
Method signatures and docstrings:
- def default(self, obj): Method is called if an object cannot be serialized. Ough... | 1f31721cb93842bdad7caeb3e92fd5087f41821a | <|skeleton|>
class EWAHJSONEncoder:
"""Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers."""
def default(self, obj):
"""Method is called if an object cannot be serialized. Ought to return a serializeable value for the object. Ought t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EWAHJSONEncoder:
"""Extension of the native json encoder to deal with additional datatypes and issues relating to (+/-) Inf and NaN numbers."""
def default(self, obj):
"""Method is called if an object cannot be serialized. Ought to return a serializeable value for the object. Ought to raise an er... | the_stack_v2_python_sparse | ewah/cleaner.py | Gemma-Analytics/ewah | train | 24 |
fb1b204278c9ce1b5842acaaf0145cdac587bdb9 | [
"check_scalar(self.epsilon, 'epsilon', float, min_val=0.0)\nself.policy_name = f'linear_ucb_{self.epsilon}'\nsuper().__post_init__()",
"check_array(array=context, name='context', expected_dim=2)\nif context.shape[0] != 1:\n raise ValueError('Expected `context.shape[0] == 1`, but found it False')\nself.theta_ha... | <|body_start_0|>
check_scalar(self.epsilon, 'epsilon', float, min_val=0.0)
self.policy_name = f'linear_ucb_{self.epsilon}'
super().__post_init__()
<|end_body_0|>
<|body_start_1|>
check_array(array=context, name='context', expected_dim=2)
if context.shape[0] != 1:
rai... | Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: int, default=1 Number of samples us... | LinUCB | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinUCB:
"""Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: i... | stack_v2_sparse_classes_36k_train_028869 | 9,194 | permissive | [
{
"docstring": "Initialize class.",
"name": "__post_init__",
"signature": "def __post_init__(self) -> None"
},
{
"docstring": "Select action for new data. Parameters ---------- context: array Observed context vector. Returns ---------- selected_actions: array-like, shape (len_list, ) List of sel... | 2 | stack_v2_sparse_classes_30k_train_017480 | Implement the Python class `LinUCB` described below.
Class description:
Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset ... | Implement the Python class `LinUCB` described below.
Class description:
Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset ... | 53598edab284b4364d127ec5662137de3f9c1206 | <|skeleton|>
class LinUCB:
"""Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinUCB:
"""Linear Upper Confidence Bound. Parameters ---------- dim: int Number of dimensions of context vectors. n_actions: int Number of actions. len_list: int, default=1 Length of a list of actions recommended in each impression. When Open Bandit Dataset is used, 3 should be set. batch_size: int, default=1... | the_stack_v2_python_sparse | obp/policy/linear.py | han20192019/newRL | train | 0 |
8ac58475a17ee4bddb2491eb40a0caf50f0d823f | [
"md5, sha1 = cls.download_latest_mimikatz()\nwith open('/tmp/Win32/mimikatz.exe', 'rb') as fd:\n size = len(fd.read())\n fd.seek(0)\n sample = InMemoryUploadedFile(fd, 'uploaded', 'mimikatz.exe', content_type='application/octet-stream', size=size, charset='binary')\n return SampleItem.save_sample(md5, s... | <|body_start_0|>
md5, sha1 = cls.download_latest_mimikatz()
with open('/tmp/Win32/mimikatz.exe', 'rb') as fd:
size = len(fd.read())
fd.seek(0)
sample = InMemoryUploadedFile(fd, 'uploaded', 'mimikatz.exe', content_type='application/octet-stream', size=size, charset='bi... | Helpers for creating test sample files. | SampleFileHelpers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleFileHelpers:
"""Helpers for creating test sample files."""
def create_sample_mimikatz(cls):
"""Import mimikatz Sample in the items."""
<|body_0|>
def download_latest_mimikatz(cls):
"""Download the latest Mimikatz version from GitHub."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_028870 | 8,990 | permissive | [
{
"docstring": "Import mimikatz Sample in the items.",
"name": "create_sample_mimikatz",
"signature": "def create_sample_mimikatz(cls)"
},
{
"docstring": "Download the latest Mimikatz version from GitHub.",
"name": "download_latest_mimikatz",
"signature": "def download_latest_mimikatz(cl... | 3 | stack_v2_sparse_classes_30k_train_016068 | Implement the Python class `SampleFileHelpers` described below.
Class description:
Helpers for creating test sample files.
Method signatures and docstrings:
- def create_sample_mimikatz(cls): Import mimikatz Sample in the items.
- def download_latest_mimikatz(cls): Download the latest Mimikatz version from GitHub.
- ... | Implement the Python class `SampleFileHelpers` described below.
Class description:
Helpers for creating test sample files.
Method signatures and docstrings:
- def create_sample_mimikatz(cls): Import mimikatz Sample in the items.
- def download_latest_mimikatz(cls): Download the latest Mimikatz version from GitHub.
- ... | d562e1191b5ef10480be819ba8c584034c25259b | <|skeleton|>
class SampleFileHelpers:
"""Helpers for creating test sample files."""
def create_sample_mimikatz(cls):
"""Import mimikatz Sample in the items."""
<|body_0|>
def download_latest_mimikatz(cls):
"""Download the latest Mimikatz version from GitHub."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleFileHelpers:
"""Helpers for creating test sample files."""
def create_sample_mimikatz(cls):
"""Import mimikatz Sample in the items."""
md5, sha1 = cls.download_latest_mimikatz()
with open('/tmp/Win32/mimikatz.exe', 'rb') as fd:
size = len(fd.read())
f... | the_stack_v2_python_sparse | toucan/canary_utils/test_helpers.py | toucan-project/TOUCAN | train | 3 |
16bae8251e1c9f9269359910f2d2aa2caca9fa81 | [
"self.locale = Bonjour.locale()\ntry:\n self.func = import_function(auth_func)\nexcept:\n self.func = None\ntry:\n self.allowed = parse_numbers(auth)\nexcept:\n self.allowed = []\nself.allow = ('*', 'all', 'true', 'True').count(auth) > 0\nself.disallow = ('none', 'false', 'False').count(auth) > 0",
"i... | <|body_start_0|>
self.locale = Bonjour.locale()
try:
self.func = import_function(auth_func)
except:
self.func = None
try:
self.allowed = parse_numbers(auth)
except:
self.allowed = []
self.allow = ('*', 'all', 'true', 'True')... | Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system. | App | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class App:
"""Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system."""
def configure(self, auth_func=None, auth=None):
"""set up authentication mechanism configured from [ping] in rapidsms.i... | stack_v2_sparse_classes_36k_train_028871 | 3,409 | no_license | [
{
"docstring": "set up authentication mechanism configured from [ping] in rapidsms.ini",
"name": "configure",
"signature": "def configure(self, auth_func=None, auth=None)"
},
{
"docstring": "check authorization and respond if auth contained deny string => return if auth contained allow string =>... | 2 | null | Implement the Python class `App` described below.
Class description:
Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system.
Method signatures and docstrings:
- def configure(self, auth_func=None, auth=None): set up auth... | Implement the Python class `App` described below.
Class description:
Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system.
Method signatures and docstrings:
- def configure(self, auth_func=None, auth=None): set up auth... | 5cb1764a637c69d65c0bfbba1baacf07a50e174b | <|skeleton|>
class App:
"""Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system."""
def configure(self, auth_func=None, auth=None):
"""set up authentication mechanism configured from [ping] in rapidsms.i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class App:
"""Reply to `ping` messages to confirm system is up and running. One can specify a number or authentication function to limit users who can ping the system."""
def configure(self, auth_func=None, auth=None):
"""set up authentication mechanism configured from [ping] in rapidsms.ini"""
... | the_stack_v2_python_sparse | apps/ping/app.py | mvpdev/rapidsms | train | 4 |
43d76d82a3febc268f235315ece3a3e5423d0b62 | [
"self.attr = attr\nself.compare_fx = compare_fx\nself.attr_transformer = attr_transformer",
"from types import LambdaType\ncompare = self.compare_fx\nattributes = ds.sa[self.attr].value.copy()\nif self.attr_transformer is not None:\n attributes = self.attr_transformer(attributes)\nif isinstance(value, LambdaTy... | <|body_start_0|>
self.attr = attr
self.compare_fx = compare_fx
self.attr_transformer = attr_transformer
<|end_body_0|>
<|body_start_1|>
from types import LambdaType
compare = self.compare_fx
attributes = ds.sa[self.attr].value.copy()
if self.attr_transformer is n... | SampleExpressionSlicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampleExpressionSlicer:
def __init__(self, attr, compare_fx=np.greater, attr_transformer=None):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude samples from subjects with an age greater than the average plus one ... | stack_v2_sparse_classes_36k_train_028872 | 7,736 | no_license | [
{
"docstring": "This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude samples from subjects with an age greater than the average plus one standard deviation, or on some trials with an amplitude smaller than a particular value. Parameters -------... | 2 | stack_v2_sparse_classes_30k_train_019316 | Implement the Python class `SampleExpressionSlicer` described below.
Class description:
Implement the SampleExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, attr, compare_fx=np.greater, attr_transformer=None): This object is used when we want to slice samples based on some values and thr... | Implement the Python class `SampleExpressionSlicer` described below.
Class description:
Implement the SampleExpressionSlicer class.
Method signatures and docstrings:
- def __init__(self, attr, compare_fx=np.greater, attr_transformer=None): This object is used when we want to slice samples based on some values and thr... | 3adbbd4feaaac4d1bb00e88f9ed62debef2a0483 | <|skeleton|>
class SampleExpressionSlicer:
def __init__(self, attr, compare_fx=np.greater, attr_transformer=None):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude samples from subjects with an age greater than the average plus one ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SampleExpressionSlicer:
def __init__(self, attr, compare_fx=np.greater, attr_transformer=None):
"""This object is used when we want to slice samples based on some values and thresholds. For example if we want to exclude samples from subjects with an age greater than the average plus one standard devia... | the_stack_v2_python_sparse | pyitab/preprocessing/slicers.py | robbisg/pyitab | train | 1 | |
a248462386adc932b7f01f1d346593b1a21b98a5 | [
"self.dic = [0] * 26\nself.next = [None] * 26\nself.end = False",
"if word:\n index = ord(word[0]) - ord('a')\n if not self.dic[index]:\n self.dic[index] = 1\n if len(word) > 1:\n if self.next[index] is None:\n self.next[index] = WordDictionary()\n self.next[index].addWord... | <|body_start_0|>
self.dic = [0] * 26
self.next = [None] * 26
self.end = False
<|end_body_0|>
<|body_start_1|>
if word:
index = ord(word[0]) - ord('a')
if not self.dic[index]:
self.dic[index] = 1
if len(word) > 1:
if sel... | WordDictionary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_36k_train_028873 | 3,055 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds a word into the data structure. :type word: str :rtype: void",
"name": "addWord",
"signature": "def addWord(self, word)"
},
{
"docstring": "Returns... | 3 | null | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | Implement the Python class `WordDictionary` described below.
Class description:
Implement the WordDictionary class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def addWord(self, word): Adds a word into the data structure. :type word: str :rtype: void
- def search(sel... | 4599634f31d78a0372cf0ff6fb7935d054d5ecb5 | <|skeleton|>
class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
<|body_1|>
def search(self, word):
"""Returns if the word i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDictionary:
def __init__(self):
"""Initialize your data structure here."""
self.dic = [0] * 26
self.next = [None] * 26
self.end = False
def addWord(self, word):
"""Adds a word into the data structure. :type word: str :rtype: void"""
if word:
... | the_stack_v2_python_sparse | leetcode_python/201-300/211.py | jhgdike/leetCode | train | 3 | |
4ba4d94433caa510db0cf6f095714a45ac3148fc | [
"self.config = config\nself.executor = executor\nself.cacheobj = cacheobj\nself.pii_salt = self.config.piisalt\nself.nworkers = self.config.workers\nself.ratelimits = self.config.ratelimits",
"self.set_header('content-type', 'text/plain; charset=UTF-8')\nif status_code == 400:\n self.write(f'HTTP {status_code}... | <|body_start_0|>
self.config = config
self.executor = executor
self.cacheobj = cacheobj
self.pii_salt = self.config.piisalt
self.nworkers = self.config.workers
self.ratelimits = self.config.ratelimits
<|end_body_0|>
<|body_start_1|>
self.set_header('content-type'... | This handles health check endpoints. | HealthCheckHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HealthCheckHandler:
"""This handles health check endpoints."""
def initialize(self, config, executor, cacheobj):
"""This sets up some config."""
<|body_0|>
def write_error(self, status_code, **kwargs):
"""This writes the error as a response."""
<|body_1|>... | stack_v2_sparse_classes_36k_train_028874 | 4,066 | permissive | [
{
"docstring": "This sets up some config.",
"name": "initialize",
"signature": "def initialize(self, config, executor, cacheobj)"
},
{
"docstring": "This writes the error as a response.",
"name": "write_error",
"signature": "def write_error(self, status_code, **kwargs)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_008333 | Implement the Python class `HealthCheckHandler` described below.
Class description:
This handles health check endpoints.
Method signatures and docstrings:
- def initialize(self, config, executor, cacheobj): This sets up some config.
- def write_error(self, status_code, **kwargs): This writes the error as a response.
... | Implement the Python class `HealthCheckHandler` described below.
Class description:
This handles health check endpoints.
Method signatures and docstrings:
- def initialize(self, config, executor, cacheobj): This sets up some config.
- def write_error(self, status_code, **kwargs): This writes the error as a response.
... | 9a038e3734bb8f66115384a1e0917042a4bc4681 | <|skeleton|>
class HealthCheckHandler:
"""This handles health check endpoints."""
def initialize(self, config, executor, cacheobj):
"""This sets up some config."""
<|body_0|>
def write_error(self, status_code, **kwargs):
"""This writes the error as a response."""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HealthCheckHandler:
"""This handles health check endpoints."""
def initialize(self, config, executor, cacheobj):
"""This sets up some config."""
self.config = config
self.executor = executor
self.cacheobj = cacheobj
self.pii_salt = self.config.piisalt
self.... | the_stack_v2_python_sparse | authnzerver/healthcheck.py | waqasbhatti/authnzerver | train | 3 |
56bab1c0af90187458995f68217f93e7f210ec5c | [
"for k, v in classdict.iteritems():\n if isinstance(v, TraitType):\n v._attr_name = k\n elif inspect.isclass(v):\n if issubclass(v, TraitType):\n vinst = v()\n vinst._attr_name = k\n classdict[k] = vinst\nreturn super(MetaHasTraits, mcls).__new__(mcls, name, base... | <|body_start_0|>
for k, v in classdict.iteritems():
if isinstance(v, TraitType):
v._attr_name = k
elif inspect.isclass(v):
if issubclass(v, TraitType):
vinst = v()
vinst._attr_name = k
classdict[k... | A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute. | MetaHasTraits | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetaHasTraits:
"""A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute."""
def __new__(mcls, name, bases, classdict):
"""Create the HasTraits class. This instantiates all TraitTypes in the class dict a... | stack_v2_sparse_classes_36k_train_028875 | 34,850 | no_license | [
{
"docstring": "Create the HasTraits class. This instantiates all TraitTypes in the class dict and sets their :attr:`name` attribute.",
"name": "__new__",
"signature": "def __new__(mcls, name, bases, classdict)"
},
{
"docstring": "Finish initializing the HasTraits class. This sets the :attr:`thi... | 2 | stack_v2_sparse_classes_30k_train_013381 | Implement the Python class `MetaHasTraits` described below.
Class description:
A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute.
Method signatures and docstrings:
- def __new__(mcls, name, bases, classdict): Create the HasTraits cl... | Implement the Python class `MetaHasTraits` described below.
Class description:
A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute.
Method signatures and docstrings:
- def __new__(mcls, name, bases, classdict): Create the HasTraits cl... | 5e7cc7de3495145501ca53deb9efee2233ab7e1c | <|skeleton|>
class MetaHasTraits:
"""A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute."""
def __new__(mcls, name, bases, classdict):
"""Create the HasTraits class. This instantiates all TraitTypes in the class dict a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetaHasTraits:
"""A metaclass for HasTraits. This metaclass makes sure that any TraitType class attributes are instantiated and sets their name attribute."""
def __new__(mcls, name, bases, classdict):
"""Create the HasTraits class. This instantiates all TraitTypes in the class dict and sets their... | the_stack_v2_python_sparse | Extensions/Deal Package/FPythonCode/traitlets.py | webclinic017/fa-absa-py3 | train | 0 |
479a6a3becb493d0dd7a917cbd86fc15e763947a | [
"m = len(x)\ncost = 1 / (2 * m) * np.power(np.dot(x, theta.T) - y.T, 2).sum() + l / (2 * m) * np.power(theta, 2).sum()\ntheta_temp = np.mat([0] + theta.tolist()[1:])\ngrad = 1 / m * np.dot(x.T, np.dot(x, theta.T) - y.T) + l / m * theta_temp.T\nreturn (cost, grad)",
"alpha, lam, times, theta = (settings['alpha'], ... | <|body_start_0|>
m = len(x)
cost = 1 / (2 * m) * np.power(np.dot(x, theta.T) - y.T, 2).sum() + l / (2 * m) * np.power(theta, 2).sum()
theta_temp = np.mat([0] + theta.tolist()[1:])
grad = 1 / m * np.dot(x.T, np.dot(x, theta.T) - y.T) + l / m * theta_temp.T
return (cost, grad)
<|en... | GradientDescent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
<|body_0|>
def optimize_param(... | stack_v2_sparse_classes_36k_train_028876 | 6,270 | no_license | [
{
"docstring": "获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值",
"name": "__get_cost_and_grad",
"signature": "def __get_cost_and_grad(x, theta, l, y)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_014400 | Implement the Python class `GradientDescent` described below.
Class description:
Implement the GradientDescent class.
Method signatures and docstrings:
- def __get_cost_and_grad(x, theta, l, y): 获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: num... | Implement the Python class `GradientDescent` described below.
Class description:
Implement the GradientDescent class.
Method signatures and docstrings:
- def __get_cost_and_grad(x, theta, l, y): 获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: num... | 4d6c45a07ea9456a635793006b13cc3d62fc7419 | <|skeleton|>
class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
<|body_0|>
def optimize_param(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientDescent:
def __get_cost_and_grad(x, theta, l, y):
"""获得损失函数值和损失函数导数值 :param x: numpy矩阵,每行为一个样本,每列为对应参数的取值,包括第一列补充的1 :param theta: numpy行矩阵,每列为一个参数 :param l: 正则化参数 :param y: numpy行矩阵,每列为每个样本对应的标签值 :return: 在当前参数(theta)下,损失函数值和损失函数的导数值"""
m = len(x)
cost = 1 / (2 * m) * np.power(... | the_stack_v2_python_sparse | app/admin/algorithm.py | llf-970310/expression-api | train | 0 | |
2cd00c4dcaa0796fcc8c37809ff81c0fb2af11c5 | [
"category = {'ontology': ontology, 'type': type, 'difficulty': difficulty, 'average_time': average_time, 'nature': nature}\nsubmission = cls(submitted_by_type=submitted_by_type, submitted_by_id=submitted_by_id, question_id=question_id, category=json.dumps(category), status=status)\ndb.session.add(submission)\ndb.se... | <|body_start_0|>
category = {'ontology': ontology, 'type': type, 'difficulty': difficulty, 'average_time': average_time, 'nature': nature}
submission = cls(submitted_by_type=submitted_by_type, submitted_by_id=submitted_by_id, question_id=question_id, category=json.dumps(category), status=status)
... | CategorySubmission | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategorySubmission:
def create(cls, submitted_by_type, submitted_by_id, question_id, ontology=None, nature=None, type=None, difficulty=None, average_time=None, status=None):
"""Create a new categorization submission :param submitted_by_type: the user type who submitted :param submitted_b... | stack_v2_sparse_classes_36k_train_028877 | 3,133 | no_license | [
{
"docstring": "Create a new categorization submission :param submitted_by_type: the user type who submitted :param submitted_by_id: the user id who submitted :param question_id: the question id this submission corresponds too :param ontology: the ontology node's complete path :param type: :param difficulty: :p... | 2 | null | Implement the Python class `CategorySubmission` described below.
Class description:
Implement the CategorySubmission class.
Method signatures and docstrings:
- def create(cls, submitted_by_type, submitted_by_id, question_id, ontology=None, nature=None, type=None, difficulty=None, average_time=None, status=None): Crea... | Implement the Python class `CategorySubmission` described below.
Class description:
Implement the CategorySubmission class.
Method signatures and docstrings:
- def create(cls, submitted_by_type, submitted_by_id, question_id, ontology=None, nature=None, type=None, difficulty=None, average_time=None, status=None): Crea... | c8af233693cd6a97489a2d73a85646b15220389c | <|skeleton|>
class CategorySubmission:
def create(cls, submitted_by_type, submitted_by_id, question_id, ontology=None, nature=None, type=None, difficulty=None, average_time=None, status=None):
"""Create a new categorization submission :param submitted_by_type: the user type who submitted :param submitted_b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategorySubmission:
def create(cls, submitted_by_type, submitted_by_id, question_id, ontology=None, nature=None, type=None, difficulty=None, average_time=None, status=None):
"""Create a new categorization submission :param submitted_by_type: the user type who submitted :param submitted_by_id: the user... | the_stack_v2_python_sparse | exam_app/models/category_submission.py | GraphicalDot/testrocketbackend | train | 0 | |
25ae21c37d321f9355af0d73d009beea2c4d4893 | [
"super().__init__(vein, **kwargs)\nself.diameter = diameter\nself.height = height\nself.is_round = is_round",
"result = super().as_json()\nresult['generator'].update({'height': max(0, round(self.height / 2.0)), 'radius': max(1, round(self.diameter / 2.0)), 'shape': 'CIRCLE' if self.is_round else 'SQUARE', 'slim':... | <|body_start_0|>
super().__init__(vein, **kwargs)
self.diameter = diameter
self.height = height
self.is_round = is_round
<|end_body_0|>
<|body_start_1|>
result = super().as_json()
result['generator'].update({'height': max(0, round(self.height / 2.0)), 'radius': max(1, ro... | PlateDeposit create s a deposit as a large cylinder of the given material. | PlateDeposit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlateDeposit:
"""PlateDeposit create s a deposit as a large cylinder of the given material."""
def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs):
"""Create a new plate deposit."""
<|body_0|>
def as_json(self):
"""Creat... | stack_v2_sparse_classes_36k_train_028878 | 1,183 | no_license | [
{
"docstring": "Create a new plate deposit.",
"name": "__init__",
"signature": "def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs)"
},
{
"docstring": "Create a dict representation of this deposit suitable for being converted to JSON.",
"name": "as_... | 2 | stack_v2_sparse_classes_30k_train_007015 | Implement the Python class `PlateDeposit` described below.
Class description:
PlateDeposit create s a deposit as a large cylinder of the given material.
Method signatures and docstrings:
- def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs): Create a new plate deposit.
- def... | Implement the Python class `PlateDeposit` described below.
Class description:
PlateDeposit create s a deposit as a large cylinder of the given material.
Method signatures and docstrings:
- def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs): Create a new plate deposit.
- def... | 9bd6e74cb3817eec76119978ea31cf5b04e0ed51 | <|skeleton|>
class PlateDeposit:
"""PlateDeposit create s a deposit as a large cylinder of the given material."""
def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs):
"""Create a new plate deposit."""
<|body_0|>
def as_json(self):
"""Creat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlateDeposit:
"""PlateDeposit create s a deposit as a large cylinder of the given material."""
def __init__(self, vein: Vein, height: int=2, diameter: int=16, is_round: bool=True, **kwargs):
"""Create a new plate deposit."""
super().__init__(vein, **kwargs)
self.diameter = diamete... | the_stack_v2_python_sparse | src/packconfig/oregen/deposits/plate_deposit.py | tungstonminer/packconfig | train | 0 |
c6a05b94f899cd1dcea921fbd855f008d037e123 | [
"self.learning_rate = learning_rate\nself.beta1 = beta1\nself.beta2 = beta2\nself.m = None\nself.v = None\nself.step = 0",
"epsilon = 1e-07\nif self.m is None:\n self.m = {}\n for key, value in params.items():\n self.m[key] = np.zeros_like(value)\nif self.v is None:\n self.v = {}\n for key, val... | <|body_start_0|>
self.learning_rate = learning_rate
self.beta1 = beta1
self.beta2 = beta2
self.m = None
self.v = None
self.step = 0
<|end_body_0|>
<|body_start_1|>
epsilon = 1e-07
if self.m is None:
self.m = {}
for key, value in pa... | Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1] | Adam | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adam:
"""Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1]"""
def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999):
"""initialize learning_rate: learning rate for iteration beta1: exponential decay rate for 1st order moment `m` beta2: exponential decay rate ... | stack_v2_sparse_classes_36k_train_028879 | 2,008 | permissive | [
{
"docstring": "initialize learning_rate: learning rate for iteration beta1: exponential decay rate for 1st order moment `m` beta2: exponential decay rate for 2nd order moment `v`",
"name": "__init__",
"signature": "def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_005739 | Implement the Python class `Adam` described below.
Class description:
Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1]
Method signatures and docstrings:
- def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999): initialize learning_rate: learning rate for iteration beta1: exponential decay rat... | Implement the Python class `Adam` described below.
Class description:
Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1]
Method signatures and docstrings:
- def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999): initialize learning_rate: learning rate for iteration beta1: exponential decay rat... | 70ec531578f099136744d2c1ec11959b239c3854 | <|skeleton|>
class Adam:
"""Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1]"""
def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999):
"""initialize learning_rate: learning rate for iteration beta1: exponential decay rate for 1st order moment `m` beta2: exponential decay rate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adam:
"""Implementation of https://arxiv.org/abs/1412.6980v9 [Algorithm 1]"""
def __init__(self, learning_rate=0.01, beta1=0.9, beta2=0.999):
"""initialize learning_rate: learning rate for iteration beta1: exponential decay rate for 1st order moment `m` beta2: exponential decay rate for 2nd order... | the_stack_v2_python_sparse | ch06/Adam.py | sankaku/deep-learning-from-scratch-py | train | 0 |
b9787fcc1519cb2e7bf64d336e68282ade85c2ff | [
"super(Postnet, self).__init__()\nself.postnet = torch.nn.ModuleList()\nfor layer in six.moves.range(n_layers - 1):\n ichans = odim if layer == 0 else n_chans\n ochans = odim if layer == n_layers - 1 else n_chans\n if use_batch_norm:\n self.postnet += [torch.nn.Sequential(torch.nn.Conv1d(ichans, och... | <|body_start_0|>
super(Postnet, self).__init__()
self.postnet = torch.nn.ModuleList()
for layer in six.moves.range(n_layers - 1):
ichans = odim if layer == 0 else n_chans
ochans = odim if layer == n_layers - 1 else n_chans
if use_batch_norm:
se... | Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which helps to compensate the de... | Postnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_36k_train_028880 | 3,105 | permissive | [
{
"docstring": "Initialize postnet module. Args: idim (int): Dimension of the inputs. odim (int): Dimension of the outputs. n_layers (int, optional): The number of layers. n_filts (int, optional): The number of filter size. n_units (int, optional): The number of filter channels. use_batch_norm (bool, optional):... | 2 | stack_v2_sparse_classes_30k_train_003500 | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | 41dc231931907e8c1fa9b85c5263f87163c723a4 | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which help... | the_stack_v2_python_sparse | modules/postnet.py | wangfn/FastSpeech2 | train | 0 |
f80309fc39e0b13de36980e8d6a8a416319e2ee6 | [
"self.agregar_textura(recursos_com % 'Iori_0.png')\nobj = le.ObjetoImagenAvanzado('Iori', self.texturas[0], [100, 50])\nobj.tipo = 0\nobj.escala = le.Vec2((3, 3))\nself.agregar_objeto(obj)",
"teclado = self.eventos.entrada_teclado\nif teclado[K_ESCAPE][0]:\n self.nucleo.salir()\nif teclado[K_SPACE][0]:\n se... | <|body_start_0|>
self.agregar_textura(recursos_com % 'Iori_0.png')
obj = le.ObjetoImagenAvanzado('Iori', self.texturas[0], [100, 50])
obj.tipo = 0
obj.escala = le.Vec2((3, 3))
self.agregar_objeto(obj)
<|end_body_0|>
<|body_start_1|>
teclado = self.eventos.entrada_teclado... | Escena con lógica. | EscenaBasica | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EscenaBasica:
"""Escena con lógica."""
def logica_ini(self):
"""Lógica inicial de la escena."""
<|body_0|>
def logica(self, tiempo):
"""Lógica continua de la escena. tiempo = tiempo transcurrido desde el último fotograma"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_028881 | 2,031 | no_license | [
{
"docstring": "Lógica inicial de la escena.",
"name": "logica_ini",
"signature": "def logica_ini(self)"
},
{
"docstring": "Lógica continua de la escena. tiempo = tiempo transcurrido desde el último fotograma",
"name": "logica",
"signature": "def logica(self, tiempo)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004727 | Implement the Python class `EscenaBasica` described below.
Class description:
Escena con lógica.
Method signatures and docstrings:
- def logica_ini(self): Lógica inicial de la escena.
- def logica(self, tiempo): Lógica continua de la escena. tiempo = tiempo transcurrido desde el último fotograma | Implement the Python class `EscenaBasica` described below.
Class description:
Escena con lógica.
Method signatures and docstrings:
- def logica_ini(self): Lógica inicial de la escena.
- def logica(self, tiempo): Lógica continua de la escena. tiempo = tiempo transcurrido desde el último fotograma
<|skeleton|>
class E... | 0a15918fce53e432ee1e954227ffe18fc2f84abd | <|skeleton|>
class EscenaBasica:
"""Escena con lógica."""
def logica_ini(self):
"""Lógica inicial de la escena."""
<|body_0|>
def logica(self, tiempo):
"""Lógica continua de la escena. tiempo = tiempo transcurrido desde el último fotograma"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EscenaBasica:
"""Escena con lógica."""
def logica_ini(self):
"""Lógica inicial de la escena."""
self.agregar_textura(recursos_com % 'Iori_0.png')
obj = le.ObjetoImagenAvanzado('Iori', self.texturas[0], [100, 50])
obj.tipo = 0
obj.escala = le.Vec2((3, 3))
se... | the_stack_v2_python_sparse | LE/Ejemplos/ej_basico.py | Lizard-13/LizardEngine | train | 1 |
4da7a814cf45b80cfe2ec79bfc96cbbdf55a6a7b | [
"dp = [2 ** 31 - 1] * (1 + amount)\ndp[0] = 0\nfor i in range(1, 1 + amount):\n for coin in coins:\n if i >= coin:\n dp[i] = min(dp[i], 1 + dp[i - coin])\nreturn dp[amount] if dp[amount] != 2 ** 31 - 1 else -1",
"if not coins or amount < 0:\n return -1\nif amount == 0:\n return 0\ncoins... | <|body_start_0|>
dp = [2 ** 31 - 1] * (1 + amount)
dp[0] = 0
for i in range(1, 1 + amount):
for coin in coins:
if i >= coin:
dp[i] = min(dp[i], 1 + dp[i - coin])
return dp[amount] if dp[amount] != 2 ** 31 - 1 else -1
<|end_body_0|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_028882 | 1,870 | no_license | [
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange",
"signature": "def coinChange(self, coins, amount)"
},
{
"docstring": ":type coins: List[int] :type amount: int :rtype: int",
"name": "coinChange2",
"signature": "def coinChange2(self, coins, amou... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def coinChange(self, coins, amount): :type coins: List[int] :type amount: int :rtype: int
- def coinChange2(self, coins, amount): :type coins: List[int] :type amount: int :rtype:... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_0|>
def coinChange2(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def coinChange(self, coins, amount):
""":type coins: List[int] :type amount: int :rtype: int"""
dp = [2 ** 31 - 1] * (1 + amount)
dp[0] = 0
for i in range(1, 1 + amount):
for coin in coins:
if i >= coin:
dp[i] = min(dp[i... | the_stack_v2_python_sparse | code322CoinChange.py | cybelewang/leetcode-python | train | 0 | |
1048a6df81a7f8bf3035efdb8dbba8f9b4679815 | [
"self.l = l\nself.p = p\nself.k = k\nself.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5\nself.e = np.zeros((self.p + 1) * (self.k + 1))\nself.distance = np.zeros((self.p + 1) * (self.k + 1))\nself.grid = np.zeros(((self.p + 1) * (self.k + 1), 2))\ncount = 0\nfor i in range(self.p + 1):\n for j in range... | <|body_start_0|>
self.l = l
self.p = p
self.k = k
self.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5
self.e = np.zeros((self.p + 1) * (self.k + 1))
self.distance = np.zeros((self.p + 1) * (self.k + 1))
self.grid = np.zeros(((self.p + 1) * (self.k + 1), 2... | QLearningAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
<|body_0|>
def act(self):
"""Choose action depending on your internal state"""
<|body_1|>
def update(self, next_state, reward):
"""Update you... | stack_v2_sparse_classes_36k_train_028883 | 6,178 | no_license | [
{
"docstring": "Initialize your internal state",
"name": "__init__",
"signature": "def __init__(self, l, p, k, epsilon, alpha, gamma)"
},
{
"docstring": "Choose action depending on your internal state",
"name": "act",
"signature": "def act(self)"
},
{
"docstring": "Update your in... | 3 | stack_v2_sparse_classes_30k_train_013856 | Implement the Python class `QLearningAgent` described below.
Class description:
Implement the QLearningAgent class.
Method signatures and docstrings:
- def __init__(self, l, p, k, epsilon, alpha, gamma): Initialize your internal state
- def act(self): Choose action depending on your internal state
- def update(self, ... | Implement the Python class `QLearningAgent` described below.
Class description:
Implement the QLearningAgent class.
Method signatures and docstrings:
- def __init__(self, l, p, k, epsilon, alpha, gamma): Initialize your internal state
- def act(self): Choose action depending on your internal state
- def update(self, ... | aee821e9668702e1628d55dcbd1d0227b2c526c5 | <|skeleton|>
class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
<|body_0|>
def act(self):
"""Choose action depending on your internal state"""
<|body_1|>
def update(self, next_state, reward):
"""Update you... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QLearningAgent:
def __init__(self, l, p, k, epsilon, alpha, gamma):
"""Initialize your internal state"""
self.l = l
self.p = p
self.k = k
self.theta = np.ones(((self.p + 1) * (self.k + 1), 3)) * 0.5
self.e = np.zeros((self.p + 1) * (self.k + 1))
self.dis... | the_stack_v2_python_sparse | TD3/starter2.py | bastienbrier/Reinforcement-Learning | train | 0 | |
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_36k_train_028884 | 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_007731 | 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_36k | 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 | |
b9ba8bc514f92951ddf1f5fa1ea52ec657739105 | [
"ksizes = [1] + ksizes + [1]\nstrides = [1] + strides + [1]\nfor dtype in [np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype]:\n out_tensor = array_ops.extract_volume_patches(constant_op.constant(image.astype(dtype)), ksizes=ksizes, strides=strides, padding=padding, name='im2col_3d')\n self.a... | <|body_start_0|>
ksizes = [1] + ksizes + [1]
strides = [1] + strides + [1]
for dtype in [np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype]:
out_tensor = array_ops.extract_volume_patches(constant_op.constant(image.astype(dtype)), ksizes=ksizes, strides=strides, paddi... | Functional tests for ExtractVolumePatches op. | ExtractVolumePatches | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractVolumePatches:
"""Functional tests for ExtractVolumePatches op."""
def _VerifyValues(self, image, ksizes, strides, padding, patches):
"""Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor with shape: [batch, in_planes, in_rows, in_cols, depth].... | stack_v2_sparse_classes_36k_train_028885 | 4,639 | permissive | [
{
"docstring": "Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor with shape: [batch, in_planes, in_rows, in_cols, depth]. ksizes: Patch size specified as: [ksize_planes, ksize_rows, ksize_cols]. strides: Output strides, specified as: [stride_planes, stride_rows, stride_cols]. ... | 6 | null | Implement the Python class `ExtractVolumePatches` described below.
Class description:
Functional tests for ExtractVolumePatches op.
Method signatures and docstrings:
- def _VerifyValues(self, image, ksizes, strides, padding, patches): Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor... | Implement the Python class `ExtractVolumePatches` described below.
Class description:
Functional tests for ExtractVolumePatches op.
Method signatures and docstrings:
- def _VerifyValues(self, image, ksizes, strides, padding, patches): Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class ExtractVolumePatches:
"""Functional tests for ExtractVolumePatches op."""
def _VerifyValues(self, image, ksizes, strides, padding, patches):
"""Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor with shape: [batch, in_planes, in_rows, in_cols, depth].... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractVolumePatches:
"""Functional tests for ExtractVolumePatches op."""
def _VerifyValues(self, image, ksizes, strides, padding, patches):
"""Tests input-output pairs for the ExtractVolumePatches op. Args: image: Input tensor with shape: [batch, in_planes, in_rows, in_cols, depth]. ksizes: Patc... | the_stack_v2_python_sparse | tensorflow/python/kernel_tests/image_ops/extract_volume_patches_op_test.py | tensorflow/tensorflow | train | 208,740 |
9ffdaddc380386c160648550ce0bdf534650aead | [
"self.disable_network = disable_network\nself.network_id = network_id\nself.powered_on = powered_on\nself.prefix = prefix\nself.storage_container_id = storage_container_id\nself.suffix = suffix",
"if dictionary is None:\n return None\ndisable_network = dictionary.get('disableNetwork')\nnetwork_id = dictionary.... | <|body_start_0|>
self.disable_network = disable_network
self.network_id = network_id
self.powered_on = powered_on
self.prefix = prefix
self.storage_container_id = storage_container_id
self.suffix = suffix
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left in disabled state. Attached network is enabled by default. Set this flag to true to disable i... | AcropolisRestoreParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AcropolisRestoreParameters:
"""Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left in disabled state. Attached network is ... | stack_v2_sparse_classes_36k_train_028886 | 4,730 | permissive | [
{
"docstring": "Constructor for the AcropolisRestoreParameters class",
"name": "__init__",
"signature": "def __init__(self, disable_network=None, network_id=None, powered_on=None, prefix=None, storage_container_id=None, suffix=None)"
},
{
"docstring": "Creates an instance of this model from a di... | 2 | null | Implement the Python class `AcropolisRestoreParameters` described below.
Class description:
Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left ... | Implement the Python class `AcropolisRestoreParameters` described below.
Class description:
Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AcropolisRestoreParameters:
"""Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left in disabled state. Attached network is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AcropolisRestoreParameters:
"""Implementation of the 'AcropolisRestoreParameters' model. This field defines the Acropolis specific params for restore tasks of type kRecoverVMs. Attributes: disable_network (bool): Specifies whether the network should be left in disabled state. Attached network is enabled by de... | the_stack_v2_python_sparse | cohesity_management_sdk/models/acropolis_restore_parameters.py | cohesity/management-sdk-python | train | 24 |
fe3b184b1cad8ddf0b5726b4e121f77e69362c34 | [
"is_reputation_valid = all([super().is_valid_file(validate_rn), self.is_valid_version(), self.is_valid_expiration(), self.is_required_fields_empty(), self.is_valid_indicator_type_id()])\nif not self.old_file:\n is_reputation_valid = all([is_reputation_valid, self.is_id_equals_details()])\nreturn is_reputation_va... | <|body_start_0|>
is_reputation_valid = all([super().is_valid_file(validate_rn), self.is_valid_version(), self.is_valid_expiration(), self.is_required_fields_empty(), self.is_valid_indicator_type_id()])
if not self.old_file:
is_reputation_valid = all([is_reputation_valid, self.is_id_equals_de... | ReputationValidator is designed to validate the correctness of the file structure we enter to content repo. | ReputationValidator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
<|body_0|>
def is_valid_version(self)... | stack_v2_sparse_classes_36k_train_028887 | 4,381 | permissive | [
{
"docstring": "Check whether the reputation file is valid or not",
"name": "is_valid_file",
"signature": "def is_valid_file(self, validate_rn=True)"
},
{
"docstring": "Validate that the reputations file as version of -1.",
"name": "is_valid_version",
"signature": "def is_valid_version(s... | 6 | null | Implement the Python class `ReputationValidator` described below.
Class description:
ReputationValidator is designed to validate the correctness of the file structure we enter to content repo.
Method signatures and docstrings:
- def is_valid_file(self, validate_rn=True): Check whether the reputation file is valid or ... | Implement the Python class `ReputationValidator` described below.
Class description:
ReputationValidator is designed to validate the correctness of the file structure we enter to content repo.
Method signatures and docstrings:
- def is_valid_file(self, validate_rn=True): Check whether the reputation file is valid or ... | 3169757a2f98c8457e46572bf656ec6b69cc3a2e | <|skeleton|>
class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
<|body_0|>
def is_valid_version(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReputationValidator:
"""ReputationValidator is designed to validate the correctness of the file structure we enter to content repo."""
def is_valid_file(self, validate_rn=True):
"""Check whether the reputation file is valid or not"""
is_reputation_valid = all([super().is_valid_file(valida... | the_stack_v2_python_sparse | demisto_sdk/commands/common/hook_validations/reputation.py | demisto/demisto-sdk | train | 63 |
f1e6740f2196bbc526164dd74e577c9007211703 | [
"if len(matrix) == 0:\n return False\nm, n = (len(matrix), len(matrix[0]))\nrow, col = (0, n - 1)\nwhile m > row and col >= 0:\n pointer = matrix[row][col]\n if target == pointer:\n return True\n elif target < pointer:\n col -= 1\n else:\n row += 1\nreturn False",
"for row in m... | <|body_start_0|>
if len(matrix) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (0, n - 1)
while m > row and col >= 0:
pointer = matrix[row][col]
if target == pointer:
return True
elif target < pointer:
... | 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 searchMatrixCheat(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k_train_028888 | 1,025 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def searchMatrix(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrixCheat",
"signature": "def se... | 2 | stack_v2_sparse_classes_30k_train_012777 | 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 searchMatrixCheat(self, matrix, target): :type matrix: List[List[int]] ... | 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 searchMatrixCheat(self, matrix, target): :type matrix: List[List[int]] ... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrixCheat(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if len(matrix) == 0:
return False
m, n = (len(matrix), len(matrix[0]))
row, col = (0, n - 1)
while m > row and col >= 0:
pointer ... | the_stack_v2_python_sparse | cs_notes/arrays/search_a_2d_matrix_ii.py | hwc1824/LeetCodeSolution | train | 0 | |
03a24b4c7c034f47b11c890dbbaa1f3c763634a3 | [
"errors = {}\noptions: dict[str, str] = {}\ninst_desc = None\ninst_id = None\nif user_input is not None:\n inst_id = user_input[CONF_ID]\ntry:\n inst_list = await self.airzone.list_installations()\nexcept AirzoneCloudError:\n errors['base'] = 'cannot_connect'\nelse:\n for inst in inst_list:\n _da... | <|body_start_0|>
errors = {}
options: dict[str, str] = {}
inst_desc = None
inst_id = None
if user_input is not None:
inst_id = user_input[CONF_ID]
try:
inst_list = await self.airzone.list_installations()
except AirzoneCloudError:
... | Handle config flow for an Airzone Cloud device. | ConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfigFlow:
"""Handle config flow for an Airzone Cloud device."""
async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the installation selection."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | ... | stack_v2_sparse_classes_36k_train_028889 | 3,812 | permissive | [
{
"docstring": "Handle the installation selection.",
"name": "async_step_inst_pick",
"signature": "async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult"
},
{
"docstring": "Handle the initial step.",
"name": "async_step_user",
"signature": "async def ... | 2 | null | Implement the Python class `ConfigFlow` described below.
Class description:
Handle config flow for an Airzone Cloud device.
Method signatures and docstrings:
- async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the installation selection.
- async def async_step_user(sel... | Implement the Python class `ConfigFlow` described below.
Class description:
Handle config flow for an Airzone Cloud device.
Method signatures and docstrings:
- async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult: Handle the installation selection.
- async def async_step_user(sel... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ConfigFlow:
"""Handle config flow for an Airzone Cloud device."""
async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the installation selection."""
<|body_0|>
async def async_step_user(self, user_input: dict[str, Any] | ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfigFlow:
"""Handle config flow for an Airzone Cloud device."""
async def async_step_inst_pick(self, user_input: dict[str, Any] | None=None) -> FlowResult:
"""Handle the installation selection."""
errors = {}
options: dict[str, str] = {}
inst_desc = None
inst_id ... | the_stack_v2_python_sparse | homeassistant/components/airzone_cloud/config_flow.py | home-assistant/core | train | 35,501 |
8b97c98bf42d874fb37efff427c11076cf06cf5a | [
"s = sen_diff(self.x)\ns.sort()\nif alpha:\n N = len(s)\n C_alpha = norm.ppf(1 - alpha / 2) * np.sqrt(np.nanvar(self.x))\n U = int(np.round(1 + (N + C_alpha) / 2))\n L = int(np.round((N - C_alpha) / 2))\n return (np.nanmedian(s), s[L], s[U])\nelse:\n return np.nanmedian(s)",
"s = 0\nfor season i... | <|body_start_0|>
s = sen_diff(self.x)
s.sort()
if alpha:
N = len(s)
C_alpha = norm.ppf(1 - alpha / 2) * np.sqrt(np.nanvar(self.x))
U = int(np.round(1 + (N + C_alpha) / 2))
L = int(np.round((N - C_alpha) / 2))
return (np.nanmedian(s), s[... | Arguments: x array/list/series: 1d array or array like whose features are to be calculated. | Trends | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trends:
"""Arguments: x array/list/series: 1d array or array like whose features are to be calculated."""
def sen_slope(self, alpha=None):
"""A nonparametric estimate of trend. Parameters ---------- x : array_like Observations taken at a fixed frequency. Notes ----- This method works... | stack_v2_sparse_classes_36k_train_028890 | 7,976 | permissive | [
{
"docstring": "A nonparametric estimate of trend. Parameters ---------- x : array_like Observations taken at a fixed frequency. Notes ----- This method works with missing or censored data, as long as less <20% of observations are censored. References ---------- .. [1] Helsel and Hirsch, R.M. 2002. Statistical ... | 5 | stack_v2_sparse_classes_30k_train_019147 | Implement the Python class `Trends` described below.
Class description:
Arguments: x array/list/series: 1d array or array like whose features are to be calculated.
Method signatures and docstrings:
- def sen_slope(self, alpha=None): A nonparametric estimate of trend. Parameters ---------- x : array_like Observations ... | Implement the Python class `Trends` described below.
Class description:
Arguments: x array/list/series: 1d array or array like whose features are to be calculated.
Method signatures and docstrings:
- def sen_slope(self, alpha=None): A nonparametric estimate of trend. Parameters ---------- x : array_like Observations ... | ec2a4a426673b11e3589b64cef9d7160b1de28d4 | <|skeleton|>
class Trends:
"""Arguments: x array/list/series: 1d array or array like whose features are to be calculated."""
def sen_slope(self, alpha=None):
"""A nonparametric estimate of trend. Parameters ---------- x : array_like Observations taken at a fixed frequency. Notes ----- This method works... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trends:
"""Arguments: x array/list/series: 1d array or array like whose features are to be calculated."""
def sen_slope(self, alpha=None):
"""A nonparametric estimate of trend. Parameters ---------- x : array_like Observations taken at a fixed frequency. Notes ----- This method works with missing... | the_stack_v2_python_sparse | ai4water/preprocessing/seq_features.py | AtrCheema/AI4Water | train | 47 |
f4d35570ffb65b145d3c55b5c1b8a6b1aec058ec | [
"storage = [None] * 38\nstorage[0] = 0\nstorage[1] = 1\nstorage[2] = 1\nfor i in range(3, n + 1):\n storage[i] = storage[i - 1] + storage[i - 2] + storage[i - 3]\nreturn storage[n]",
"storage = [0, 1, 1]\nfor i in range(3, n + 1):\n storage.append(storage[i - 1] + storage[i - 2] + storage[i - 3])\nreturn st... | <|body_start_0|>
storage = [None] * 38
storage[0] = 0
storage[1] = 1
storage[2] = 1
for i in range(3, n + 1):
storage[i] = storage[i - 1] + storage[i - 2] + storage[i - 3]
return storage[n]
<|end_body_0|>
<|body_start_1|>
storage = [0, 1, 1]
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def tribonacci(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def tribonacci(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
storage = [None] * 38
storage[0] = 0
storage[1] = 1
... | stack_v2_sparse_classes_36k_train_028891 | 790 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "tribonacci",
"signature": "def tribonacci(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "tribonacci",
"signature": "def tribonacci(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tribonacci(self, n): :type n: int :rtype: int
- def tribonacci(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def tribonacci(self, n): :type n: int :rtype: int
- def tribonacci(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def tribonacci(self, n):
""":type... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
def tribonacci(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def tribonacci(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def tribonacci(self, n):
""":type n: int :rtype: int"""
storage = [None] * 38
storage[0] = 0
storage[1] = 1
storage[2] = 1
for i in range(3, n + 1):
storage[i] = storage[i - 1] + storage[i - 2] + storage[i - 3]
return storage[n]
... | the_stack_v2_python_sparse | 1137-nth_tribonacci_number.py | stevestar888/leetcode-problems | train | 2 | |
4ed101dfcaaddfae808b4a785445182a2965f516 | [
"self.matrix = matrix\nself.sums = {}\nfor row in range(len(matrix)):\n self.sums[row] = {}\n for col1 in range(len(matrix[0])):\n self.sums[row][col1] = {}\n for col2 in range(col1 + 1, len(matrix[0]) + 1):\n self.sums[row][col1][col2 - 1] = sum(matrix[row][col1:col2])",
"value = 0... | <|body_start_0|>
self.matrix = matrix
self.sums = {}
for row in range(len(matrix)):
self.sums[row] = {}
for col1 in range(len(matrix[0])):
self.sums[row][col1] = {}
for col2 in range(col1 + 1, len(matrix[0]) + 1):
self.s... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_028892 | 1,003 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 79eec04cc6b1ac69295530bda1575ecb613a769e | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.matrix = matrix
self.sums = {}
for row in range(len(matrix)):
self.sums[row] = {}
for col1 in range(len(matrix[0])):
self.sums[row][col1] = {}
... | the_stack_v2_python_sparse | LeetCode/Range_Sum_Query_2D_Immutable.py | sharadbhat/Competitive-Coding | train | 1 | |
45a2b73b5b66b0059ee6dcbfeac393737c946a39 | [
"super().__init__(pos_enc_class)\nself.conv = nn.Sequential(Conv2D(1, odim, 3, 2), nn.ReLU(), Conv2D(odim, odim, 5, 3), nn.ReLU())\nself.linear = Linear(odim * (((idim - 1) // 2 - 2) // 3), odim)\nself.subsampling_rate = 6\nself.right_context = 10",
"x = x.unsqueeze(1)\nx = self.conv(x)\nb, c, t, f = x.shape\nx =... | <|body_start_0|>
super().__init__(pos_enc_class)
self.conv = nn.Sequential(Conv2D(1, odim, 3, 2), nn.ReLU(), Conv2D(odim, odim, 5, 3), nn.ReLU())
self.linear = Linear(odim * (((idim - 1) // 2 - 2) // 3), odim)
self.subsampling_rate = 6
self.right_context = 10
<|end_body_0|>
<|bo... | Convolutional 2D subsampling (to 1/6 length). | Conv2dSubsampling6 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2dSubsampling6:
"""Convolutional 2D subsampling (to 1/6 length)."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an Conv2dSubsampling6 object. Args: idim (int): Input dimension. odim (int): Output dimensio... | stack_v2_sparse_classes_36k_train_028893 | 11,942 | permissive | [
{
"docstring": "Construct an Conv2dSubsampling6 object. Args: idim (int): Input dimension. odim (int): Output dimension. dropout_rate (float): Dropout rate. pos_enc (PositionalEncoding): Custom position encoding layer.",
"name": "__init__",
"signature": "def __init__(self, idim: int, odim: int, dropout_... | 2 | stack_v2_sparse_classes_30k_train_010269 | Implement the Python class `Conv2dSubsampling6` described below.
Class description:
Convolutional 2D subsampling (to 1/6 length).
Method signatures and docstrings:
- def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding): Construct an Conv2dSubsampling6 object. Args:... | Implement the Python class `Conv2dSubsampling6` described below.
Class description:
Convolutional 2D subsampling (to 1/6 length).
Method signatures and docstrings:
- def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding): Construct an Conv2dSubsampling6 object. Args:... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class Conv2dSubsampling6:
"""Convolutional 2D subsampling (to 1/6 length)."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an Conv2dSubsampling6 object. Args: idim (int): Input dimension. odim (int): Output dimensio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2dSubsampling6:
"""Convolutional 2D subsampling (to 1/6 length)."""
def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class: nn.Layer=PositionalEncoding):
"""Construct an Conv2dSubsampling6 object. Args: idim (int): Input dimension. odim (int): Output dimension. dropout_ra... | the_stack_v2_python_sparse | paddlespeech/s2t/modules/subsampling.py | anniyanvr/DeepSpeech-1 | train | 0 |
8a94ea375a14729d6ef975ccaddac63862b3d6a4 | [
"self.pump = Pump('127.0.0.1', 1000)\nself.sensor = Sensor('127.0.0.2', 2000)\nself.decider = Decider(100, 0.05)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=130)\nself.pump.get_state = MagicMock(return_value='PUMP_OFF')\nself.controller.tick ... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(100, 0.05)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=130)
... | This class performs a unit test on Controller | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""This class performs a unit test on Controller"""
def setUp(self):
"""This method does a setup for unit testing Controller"""
<|body_0|>
def test_tick(self):
"""This method performs a unit test on tick"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_028894 | 3,475 | no_license | [
{
"docstring": "This method does a setup for unit testing Controller",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "This method performs a unit test on tick",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | null | Implement the Python class `ControllerTests` described below.
Class description:
This class performs a unit test on Controller
Method signatures and docstrings:
- def setUp(self): This method does a setup for unit testing Controller
- def test_tick(self): This method performs a unit test on tick | Implement the Python class `ControllerTests` described below.
Class description:
This class performs a unit test on Controller
Method signatures and docstrings:
- def setUp(self): This method does a setup for unit testing Controller
- def test_tick(self): This method performs a unit test on tick
<|skeleton|>
class C... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class ControllerTests:
"""This class performs a unit test on Controller"""
def setUp(self):
"""This method does a setup for unit testing Controller"""
<|body_0|>
def test_tick(self):
"""This method performs a unit test on tick"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""This class performs a unit test on Controller"""
def setUp(self):
"""This method does a setup for unit testing Controller"""
self.pump = Pump('127.0.0.1', 1000)
self.sensor = Sensor('127.0.0.2', 2000)
self.decider = Decider(100, 0.05)
self.contr... | the_stack_v2_python_sparse | students/John_Sekora/lesson06/water_reg/waterregulation/test.py | aurel1212/Sp2018-Online | train | 0 |
8c12d81be46372caf4aa7820e002cc1f08b25e6c | [
"if isinstance(filter_values, list):\n for code in filter_values:\n if not isinstance(code, str) or not cls.validation_pattern.fullmatch(code):\n raise UnprocessableEntityException(f\"PSC codes must be one to four character uppercased alphanumeric strings. Offending code: '{code}'.\")\nelif is... | <|body_start_0|>
if isinstance(filter_values, list):
for code in filter_values:
if not isinstance(code, str) or not cls.validation_pattern.fullmatch(code):
raise UnprocessableEntityException(f"PSC codes must be one to four character uppercased alphanumeric strings... | PSCCodesMixin | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PSCCodesMixin:
def validate_filter_values(cls, filter_values):
"""This is validation on top of whatever TinyShield performs."""
<|body_0|>
def split_filter_values(cls, filter_values):
"""Here we assume that filter_values has already been run through validate_filter_v... | stack_v2_sparse_classes_36k_train_028895 | 4,256 | permissive | [
{
"docstring": "This is validation on top of whatever TinyShield performs.",
"name": "validate_filter_values",
"signature": "def validate_filter_values(cls, filter_values)"
},
{
"docstring": "Here we assume that filter_values has already been run through validate_filter_values.",
"name": "sp... | 3 | null | Implement the Python class `PSCCodesMixin` described below.
Class description:
Implement the PSCCodesMixin class.
Method signatures and docstrings:
- def validate_filter_values(cls, filter_values): This is validation on top of whatever TinyShield performs.
- def split_filter_values(cls, filter_values): Here we assume... | Implement the Python class `PSCCodesMixin` described below.
Class description:
Implement the PSCCodesMixin class.
Method signatures and docstrings:
- def validate_filter_values(cls, filter_values): This is validation on top of whatever TinyShield performs.
- def split_filter_values(cls, filter_values): Here we assume... | 38f920438697930ae3ac57bbcaae9034877d8fb7 | <|skeleton|>
class PSCCodesMixin:
def validate_filter_values(cls, filter_values):
"""This is validation on top of whatever TinyShield performs."""
<|body_0|>
def split_filter_values(cls, filter_values):
"""Here we assume that filter_values has already been run through validate_filter_v... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PSCCodesMixin:
def validate_filter_values(cls, filter_values):
"""This is validation on top of whatever TinyShield performs."""
if isinstance(filter_values, list):
for code in filter_values:
if not isinstance(code, str) or not cls.validation_pattern.fullmatch(code):... | the_stack_v2_python_sparse | usaspending_api/search/filters/mixins/psc.py | fedspendingtransparency/usaspending-api | train | 276 | |
12bfaad3d93abc8989bf3065f638200430de6f5c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.chatMessageHostedContent'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | TeamworkHostedContent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamworkHostedContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent:
"""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 th... | stack_v2_sparse_classes_36k_train_028896 | 2,909 | 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: TeamworkHostedContent",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | stack_v2_sparse_classes_30k_train_004006 | Implement the Python class `TeamworkHostedContent` described below.
Class description:
Implement the TeamworkHostedContent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: Creates a new instance of the appropriate class base... | Implement the Python class `TeamworkHostedContent` described below.
Class description:
Implement the TeamworkHostedContent class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeamworkHostedContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamworkHostedContent:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamworkHostedContent:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/models/teamwork_hosted_content.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
38f03883f70233b31720dca34c8f29a6f3277503 | [
"if self.__api is None:\n datadog.initialize(api_key=self.__arguments['api_key'], app_key=self.__arguments['app_key'], host_name=self.__arguments['host'])\n self.__api = datadog.api\nreturn self.__api",
"if not datadog_available:\n raise ImportError('You must \"pip install datadog\" to get the datadog cl... | <|body_start_0|>
if self.__api is None:
datadog.initialize(api_key=self.__arguments['api_key'], app_key=self.__arguments['app_key'], host_name=self.__arguments['host'])
self.__api = datadog.api
return self.__api
<|end_body_0|>
<|body_start_1|>
if not datadog_available:
... | A metrics service for interacting with Datadog. | DatadogMetricsService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatadogMetricsService:
"""A metrics service for interacting with Datadog."""
def api(self):
"""The Datadog API stub for interacting with Datadog."""
<|body_0|>
def __init__(self, options, spectator_helper, **arguments):
"""Constructs the object."""
<|body... | stack_v2_sparse_classes_36k_train_028897 | 11,965 | permissive | [
{
"docstring": "The Datadog API stub for interacting with Datadog.",
"name": "api",
"signature": "def api(self)"
},
{
"docstring": "Constructs the object.",
"name": "__init__",
"signature": "def __init__(self, options, spectator_helper, **arguments)"
},
{
"docstring": "Creates a ... | 4 | stack_v2_sparse_classes_30k_train_019654 | Implement the Python class `DatadogMetricsService` described below.
Class description:
A metrics service for interacting with Datadog.
Method signatures and docstrings:
- def api(self): The Datadog API stub for interacting with Datadog.
- def __init__(self, options, spectator_helper, **arguments): Constructs the obje... | Implement the Python class `DatadogMetricsService` described below.
Class description:
A metrics service for interacting with Datadog.
Method signatures and docstrings:
- def api(self): The Datadog API stub for interacting with Datadog.
- def __init__(self, options, spectator_helper, **arguments): Constructs the obje... | 77ef6bdc45015f738366b8d8dfe91f008bc5c834 | <|skeleton|>
class DatadogMetricsService:
"""A metrics service for interacting with Datadog."""
def api(self):
"""The Datadog API stub for interacting with Datadog."""
<|body_0|>
def __init__(self, options, spectator_helper, **arguments):
"""Constructs the object."""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatadogMetricsService:
"""A metrics service for interacting with Datadog."""
def api(self):
"""The Datadog API stub for interacting with Datadog."""
if self.__api is None:
datadog.initialize(api_key=self.__arguments['api_key'], app_key=self.__arguments['app_key'], host_name=se... | the_stack_v2_python_sparse | spinnaker-monitoring-daemon/spinnaker-monitoring/datadog_service.py | spinnaker/spinnaker-monitoring | train | 42 |
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_36k_train_028898 | 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 | stack_v2_sparse_classes_30k_train_007801 | 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_36k | 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 |
898cd9b4302787c91ff2a1e0a2233aafc65e601e | [
"maxNum = n + 1\ndp = [maxNum] * maxNum\ndp[0] = 0\nfor i in range(1, maxNum):\n dp[i] = min([dp[i - j * j] for j in range(1, int(i ** 0.5) + 1)]) + 1\nreturn dp[-1]",
"squares = [i * i for i in range(1, int(n ** 0.5) + 1)]\nd, q, nq = (1, {n}, set())\nwhile q:\n for node in q:\n for square in square... | <|body_start_0|>
maxNum = n + 1
dp = [maxNum] * maxNum
dp[0] = 0
for i in range(1, maxNum):
dp[i] = min([dp[i - j * j] for j in range(1, int(i ** 0.5) + 1)]) + 1
return dp[-1]
<|end_body_0|>
<|body_start_1|>
squares = [i * i for i in range(1, int(n ** 0.5) + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . .... | stack_v2_sparse_classes_36k_train_028899 | 1,727 | no_license | [
{
"docstring": "Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . . . dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 ... | 2 | stack_v2_sparse_classes_30k_train_002957 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares(self, n: int) -> int: Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def numSquares(self, n: int) -> int:
"""Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . .... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares(self, n: int) -> int:
"""Use dynamic programming: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . . . dp[13] = Mi... | the_stack_v2_python_sparse | 2020/perfect_squares.py | eronekogin/leetcode | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.