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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32c1571a62386f6d4fb490056be5dc4bfd9763d7 | [
"super(TfGraphConverter, self).__init__(framework, base_path)\nprint('{} bmodel converter init'.format(model_name))\nself.model_name = model_name\nself.models_path = models_path\nself.shapes = shapes\nself.dyns = dyns\nself.outdirs = outdirs\nself.nets_name = nets_name\nself.input_names = input_names\nself.output_n... | <|body_start_0|>
super(TfGraphConverter, self).__init__(framework, base_path)
print('{} bmodel converter init'.format(model_name))
self.model_name = model_name
self.models_path = models_path
self.shapes = shapes
self.dyns = dyns
self.outdirs = outdirs
self... | tf graph bmodel converter | TfGraphConverter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TfGraphConverter:
"""tf graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target):
"""Init tf graph bmodel converter"""
<|body_0|>
def converter(self):
"""conve... | stack_v2_sparse_classes_36k_train_007700 | 15,723 | permissive | [
{
"docstring": "Init tf graph bmodel converter",
"name": "__init__",
"signature": "def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target)"
},
{
"docstring": "convert tf graph",
"name": "converter",
"signature... | 2 | stack_v2_sparse_classes_30k_train_007975 | Implement the Python class `TfGraphConverter` described below.
Class description:
tf graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target): Init tf graph bmodel converter
- def c... | Implement the Python class `TfGraphConverter` described below.
Class description:
tf graph bmodel converter
Method signatures and docstrings:
- def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target): Init tf graph bmodel converter
- def c... | c9fa07851da663dda4953dba72e1d3937299a4ea | <|skeleton|>
class TfGraphConverter:
"""tf graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target):
"""Init tf graph bmodel converter"""
<|body_0|>
def converter(self):
"""conve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TfGraphConverter:
"""tf graph bmodel converter"""
def __init__(self, model_name, base_path, models_path, shapes, dyns, outdirs, nets_name, input_names, output_names, framework, target):
"""Init tf graph bmodel converter"""
super(TfGraphConverter, self).__init__(framework, base_path)
... | the_stack_v2_python_sparse | modules/utils/bmodel_converter.py | sophon-ai-algo/sophon-inference | train | 32 |
18d6b334f0ed1a09d98f7d48464c8642ab8eeabd | [
"self.big = big\nself.medium = medium\nself.small = small",
"if carType == 1:\n if self.big > 0:\n self.big = self.big - 1\n else:\n return False\nif carType == 2:\n if self.medium > 0:\n self.medium = self.medium - 1\n else:\n return False\nif carType == 3:\n if self.sm... | <|body_start_0|>
self.big = big
self.medium = medium
self.small = small
<|end_body_0|>
<|body_start_1|>
if carType == 1:
if self.big > 0:
self.big = self.big - 1
else:
return False
if carType == 2:
if self.mediu... | ParkingSystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.big = big
... | stack_v2_sparse_classes_36k_train_007701 | 984 | no_license | [
{
"docstring": ":type big: int :type medium: int :type small: int",
"name": "__init__",
"signature": "def __init__(self, big, medium, small)"
},
{
"docstring": ":type carType: int :rtype: bool",
"name": "addCar",
"signature": "def addCar(self, carType)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009957 | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool | Implement the Python class `ParkingSystem` described below.
Class description:
Implement the ParkingSystem class.
Method signatures and docstrings:
- def __init__(self, big, medium, small): :type big: int :type medium: int :type small: int
- def addCar(self, carType): :type carType: int :rtype: bool
<|skeleton|>
cla... | d2c0b41bdd181bee999922be820d6ce16312b7ae | <|skeleton|>
class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
<|body_0|>
def addCar(self, carType):
""":type carType: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParkingSystem:
def __init__(self, big, medium, small):
""":type big: int :type medium: int :type small: int"""
self.big = big
self.medium = medium
self.small = small
def addCar(self, carType):
""":type carType: int :rtype: bool"""
if carType == 1:
... | the_stack_v2_python_sparse | 1603.py | khanjason/leetcode | train | 0 | |
dc4ce169c6280093d368b95b81b5e27f8afee658 | [
"self.utils = Utils.Utils()\nself.eucacluster = eucacluster\nself.NoSQLCluster = NoSQLCluster\nself.polManager = PolicyManager('test', self.eucacluster, self.NoSQLCluster)\nself.acted = ['done']\nself.runonce = 'once'\ncluster_size = len(self.utils.get_cluster_from_db(self.utils.cluster_name))\nself.currentState = ... | <|body_start_0|>
self.utils = Utils.Utils()
self.eucacluster = eucacluster
self.NoSQLCluster = NoSQLCluster
self.polManager = PolicyManager('test', self.eucacluster, self.NoSQLCluster)
self.acted = ['done']
self.runonce = 'once'
cluster_size = len(self.utils.get_c... | MyDecisionMaker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
... | stack_v2_sparse_classes_36k_train_007702 | 7,638 | no_license | [
{
"docstring": "Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster",
"name": "__init__",
"signature": "def __init__(self, eucacluster, NoSQLClus... | 2 | null | Implement the Python class `MyDecisionMaker` described below.
Class description:
Implement the MyDecisionMaker class.
Method signatures and docstrings:
- def __init__(self, eucacluster, NoSQLCluster): Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus ... | Implement the Python class `MyDecisionMaker` described below.
Class description:
Implement the MyDecisionMaker class.
Method signatures and docstrings:
- def __init__(self, eucacluster, NoSQLCluster): Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus ... | 234c3e38f8698c5b5a5193ab1d510c6fbccd9623 | <|skeleton|>
class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyDecisionMaker:
def __init__(self, eucacluster, NoSQLCluster):
"""Constructor. EucaCluster is the object with which you can alter the number of running virtual machines in Eucalyptus NoSQLCluster contains methods to add or remove virtual machines from the virtual NoSQLCluster"""
self.utils = ... | the_stack_v2_python_sparse | MyTiramola/LwlosTiramola/MyDecisionMaker.py | gioargyr/MyTiramola | train | 0 | |
81d05eda492e910153beecc435fec5a15393bb48 | [
"forbidden_coupon_product_ids = webapp_cache.get_forbidden_coupon_product_ids(owner_id)\nproduct_id = int(product_id)\nreturn product_id in forbidden_coupon_product_ids",
"hint = ''\nowner_id = args['woid']\nproduct_id = args['id']\nif ProductHint.is_forbidden_coupon(owner_id, product_id):\n hint = u'该商品不参与全场优... | <|body_start_0|>
forbidden_coupon_product_ids = webapp_cache.get_forbidden_coupon_product_ids(owner_id)
product_id = int(product_id)
return product_id in forbidden_coupon_product_ids
<|end_body_0|>
<|body_start_1|>
hint = ''
owner_id = args['woid']
product_id = args['id'... | 商品提示 | ProductHint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductHint:
"""商品提示"""
def is_forbidden_coupon(owner_id, product_id):
"""判断商品是否被禁止使用全场优惠券"""
<|body_0|>
def get(args):
"""获取显示在商品详情页的商品相关的提示信息 @note duhao与2015-09-08增加 `__get_product_hint(owner_id, product_id)`"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_007703 | 1,010 | no_license | [
{
"docstring": "判断商品是否被禁止使用全场优惠券",
"name": "is_forbidden_coupon",
"signature": "def is_forbidden_coupon(owner_id, product_id)"
},
{
"docstring": "获取显示在商品详情页的商品相关的提示信息 @note duhao与2015-09-08增加 `__get_product_hint(owner_id, product_id)`",
"name": "get",
"signature": "def get(args)"
}
] | 2 | null | Implement the Python class `ProductHint` described below.
Class description:
商品提示
Method signatures and docstrings:
- def is_forbidden_coupon(owner_id, product_id): 判断商品是否被禁止使用全场优惠券
- def get(args): 获取显示在商品详情页的商品相关的提示信息 @note duhao与2015-09-08增加 `__get_product_hint(owner_id, product_id)` | Implement the Python class `ProductHint` described below.
Class description:
商品提示
Method signatures and docstrings:
- def is_forbidden_coupon(owner_id, product_id): 判断商品是否被禁止使用全场优惠券
- def get(args): 获取显示在商品详情页的商品相关的提示信息 @note duhao与2015-09-08增加 `__get_product_hint(owner_id, product_id)`
<|skeleton|>
class ProductHin... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class ProductHint:
"""商品提示"""
def is_forbidden_coupon(owner_id, product_id):
"""判断商品是否被禁止使用全场优惠券"""
<|body_0|>
def get(args):
"""获取显示在商品详情页的商品相关的提示信息 @note duhao与2015-09-08增加 `__get_product_hint(owner_id, product_id)`"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProductHint:
"""商品提示"""
def is_forbidden_coupon(owner_id, product_id):
"""判断商品是否被禁止使用全场优惠券"""
forbidden_coupon_product_ids = webapp_cache.get_forbidden_coupon_product_ids(owner_id)
product_id = int(product_id)
return product_id in forbidden_coupon_product_ids
def get(... | the_stack_v2_python_sparse | weapp/wapi/mall/product/product_hint.py | chengdg/weizoom | train | 1 |
e68a41a02b731f3c39305802929f9dd6fc686f1e | [
"myg = myd.grid\ngrav = self.rp.get_param('compressible.grav')\ndens = myd.get_var('density')\nymom = myd.get_var('y-momentum')\nymom_src = myg.scratch_array()\nymom_src.v()[:, :] = dens.v()[:, :] * grav\nE_src = myg.scratch_array()\nE_src.v()[:, :] = ymom.v()[:, :] * grav\nk = myg.scratch_array(nvar=self.ivars.nva... | <|body_start_0|>
myg = myd.grid
grav = self.rp.get_param('compressible.grav')
dens = myd.get_var('density')
ymom = myd.get_var('y-momentum')
ymom_src = myg.scratch_array()
ymom_src.v()[:, :] = dens.v()[:, :] * grav
E_src = myg.scratch_array()
E_src.v()[:, ... | The main simulation class for the method of lines compressible hydrodynamics solver | Simulation | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Simulation:
"""The main simulation class for the method of lines compressible hydrodynamics solver"""
def substep(self, myd):
"""take a single substep in the RK timestepping starting with the conservative state defined as part of myd"""
<|body_0|>
def method_compute_time... | stack_v2_sparse_classes_36k_train_007704 | 2,853 | permissive | [
{
"docstring": "take a single substep in the RK timestepping starting with the conservative state defined as part of myd",
"name": "substep",
"signature": "def substep(self, myd)"
},
{
"docstring": "The timestep function computes the advective timestep (CFL) constraint. The CFL constraint says t... | 3 | null | Implement the Python class `Simulation` described below.
Class description:
The main simulation class for the method of lines compressible hydrodynamics solver
Method signatures and docstrings:
- def substep(self, myd): take a single substep in the RK timestepping starting with the conservative state defined as part ... | Implement the Python class `Simulation` described below.
Class description:
The main simulation class for the method of lines compressible hydrodynamics solver
Method signatures and docstrings:
- def substep(self, myd): take a single substep in the RK timestepping starting with the conservative state defined as part ... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class Simulation:
"""The main simulation class for the method of lines compressible hydrodynamics solver"""
def substep(self, myd):
"""take a single substep in the RK timestepping starting with the conservative state defined as part of myd"""
<|body_0|>
def method_compute_time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Simulation:
"""The main simulation class for the method of lines compressible hydrodynamics solver"""
def substep(self, myd):
"""take a single substep in the RK timestepping starting with the conservative state defined as part of myd"""
myg = myd.grid
grav = self.rp.get_param('com... | the_stack_v2_python_sparse | pyro/compressible_rk/simulation.py | python-hydro/pyro2 | train | 202 |
6e4dd6d26762cba34ad6e2fb47ed8f949045ea48 | [
"factory = APIRequestFactory()\nrequest = factory.get('/api/courses/')\nuser = User.objects.get(username='pnirtep')\nforce_authenticate(request, user=user, token=user.auth_token)\ncourses = CoursesApiListView.as_view({'get': 'list'})\nresponse = courses(request)\nself.assertEqual(response.status_code, status.HTTP_2... | <|body_start_0|>
factory = APIRequestFactory()
request = factory.get('/api/courses/')
user = User.objects.get(username='pnirtep')
force_authenticate(request, user=user, token=user.auth_token)
courses = CoursesApiListView.as_view({'get': 'list'})
response = courses(request... | TestCaseForCourses | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestCaseForCourses:
def test_get_course_all_authenticated(self):
"""Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей"""
<|body_0|>
def test_get_course_all_non_authenticated(self):
"""Проверяем статус-код 401 «не авторизован (не представился)»... | stack_v2_sparse_classes_36k_train_007705 | 6,680 | no_license | [
{
"docstring": "Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей",
"name": "test_get_course_all_authenticated",
"signature": "def test_get_course_all_authenticated(self)"
},
{
"docstring": "Проверяем статус-код 401 «не авторизован (не представился)» на НЕавторизованный G... | 3 | stack_v2_sparse_classes_30k_train_008891 | Implement the Python class `TestCaseForCourses` described below.
Class description:
Implement the TestCaseForCourses class.
Method signatures and docstrings:
- def test_get_course_all_authenticated(self): Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей
- def test_get_course_all_non_authentic... | Implement the Python class `TestCaseForCourses` described below.
Class description:
Implement the TestCaseForCourses class.
Method signatures and docstrings:
- def test_get_course_all_authenticated(self): Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей
- def test_get_course_all_non_authentic... | 4fc053719ba3880190225ebd673e467aa86e0f5c | <|skeleton|>
class TestCaseForCourses:
def test_get_course_all_authenticated(self):
"""Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей"""
<|body_0|>
def test_get_course_all_non_authenticated(self):
"""Проверяем статус-код 401 «не авторизован (не представился)»... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestCaseForCourses:
def test_get_course_all_authenticated(self):
"""Проверяем статус-код 200 ОК на авторизованный GET запрос к списку записей"""
factory = APIRequestFactory()
request = factory.get('/api/courses/')
user = User.objects.get(username='pnirtep')
force_authen... | the_stack_v2_python_sparse | courses_api/tests.py | pnirtep/OTUS_hw_djangoproject | train | 0 | |
723443504ebbcdddd8b61cd95c92823fafd23ea4 | [
"if not board or not board[0]:\n return\nrow = len(board)\ncol = len(board[0])\n\ndef dfs(i, j):\n board[i][j] = 'B'\n for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n tmp_i = i + x\n tmp_j = j + y\n if 1 <= tmp_i < row and 1 <= tmp_j < col and (board[tmp_i][tmp_j] == 'O'):\n ... | <|body_start_0|>
if not board or not board[0]:
return
row = len(board)
col = len(board[0])
def dfs(i, j):
board[i][j] = 'B'
for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
tmp_i = i + x
tmp_j = j + y
if ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def solve(cls, board: List[List[str]]) -> None:
"""DFS"""
<|body_0|>
def solve_v2(cls, board: List[List[str]]) -> None:
"""BFS"""
<|body_1|>
def solve_v3(cls, board: List[List[str]]) -> None:
"""并查集"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_007706 | 4,639 | no_license | [
{
"docstring": "DFS",
"name": "solve",
"signature": "def solve(cls, board: List[List[str]]) -> None"
},
{
"docstring": "BFS",
"name": "solve_v2",
"signature": "def solve_v2(cls, board: List[List[str]]) -> None"
},
{
"docstring": "并查集",
"name": "solve_v3",
"signature": "de... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(cls, board: List[List[str]]) -> None: DFS
- def solve_v2(cls, board: List[List[str]]) -> None: BFS
- def solve_v3(cls, board: List[List[str]]) -> None: 并查集 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def solve(cls, board: List[List[str]]) -> None: DFS
- def solve_v2(cls, board: List[List[str]]) -> None: BFS
- def solve_v3(cls, board: List[List[str]]) -> None: 并查集
<|skeleton|... | 1d1876620a55ff88af7bc390cf1a4fd4350d8d16 | <|skeleton|>
class Solution:
def solve(cls, board: List[List[str]]) -> None:
"""DFS"""
<|body_0|>
def solve_v2(cls, board: List[List[str]]) -> None:
"""BFS"""
<|body_1|>
def solve_v3(cls, board: List[List[str]]) -> None:
"""并查集"""
<|body_2|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def solve(cls, board: List[List[str]]) -> None:
"""DFS"""
if not board or not board[0]:
return
row = len(board)
col = len(board[0])
def dfs(i, j):
board[i][j] = 'B'
for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
... | the_stack_v2_python_sparse | 02-算法思想/并查集/130.被围绕的区域(M).py | jh-lau/leetcode_in_python | train | 0 | |
17bd98122ef2e8d01b9d575deaf7d869cf00ba72 | [
"def driver(s, left, right):\n L = left\n R = right\n while L >= 0 and R < len(s) and (s[L] == s[R]):\n L -= 1\n R += 1\n return R - L - 1\nstart = end = 0\nfor i, _ in enumerate(s):\n len1 = driver(s, i, i)\n len2 = driver(s, i, i + 1)\n len_max = max(len1, len2)\n if len_max ... | <|body_start_0|>
def driver(s, left, right):
L = left
R = right
while L >= 0 and R < len(s) and (s[L] == s[R]):
L -= 1
R += 1
return R - L - 1
start = end = 0
for i, _ in enumerate(s):
len1 = driver(s, i,... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindromeCenterAlgorithm(self, s):
"""We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers. You might be asking why there are 2n - 12n−1 but not nn centers? The reason... | stack_v2_sparse_classes_36k_train_007707 | 2,769 | no_license | [
{
"docstring": "We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers. You might be asking why there are 2n - 12n−1 but not nn centers? The reason is the center of a palindrome can be in between two letters. Such p... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeCenterAlgorithm(self, s): We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeCenterAlgorithm(self, s): We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def longestPalindromeCenterAlgorithm(self, s):
"""We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers. You might be asking why there are 2n - 12n−1 but not nn centers? The reason... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindromeCenterAlgorithm(self, s):
"""We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 1 such centers. You might be asking why there are 2n - 12n−1 but not nn centers? The reason is the center... | the_stack_v2_python_sparse | LeetCodes/Strings/LongestPalindromicSubstring.py | chutianwen/LeetCodes | train | 0 | |
38a5d362d4b4ca1fd7a7edc8165a81a8000fb95f | [
"method = 'visit_' + node.__class__.__name__\nvisitor = getattr(self, method, self.generic_visit)\nreturn visitor(node, *args, **kwargs)",
"for value in node:\n if isinstance(value, list):\n for item in value:\n self.visit(item, *args, **kwargs)\n else:\n self.visit(value, *args, **... | <|body_start_0|>
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
for value in node:
if isinstance(value, list):
for item in value:
... | GrammarVisitor | [
"CAL-1.0-Combined-Work-Exception",
"CAL-1.0",
"MIT",
"CC-BY-SA-4.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GrammarVisitor:
def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any:
"""Visit a node."""
<|body_0|>
def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None:
"""Called if no explicit visitor function exists for a node."""
<|bod... | stack_v2_sparse_classes_36k_train_007708 | 12,792 | permissive | [
{
"docstring": "Visit a node.",
"name": "visit",
"signature": "def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any"
},
{
"docstring": "Called if no explicit visitor function exists for a node.",
"name": "generic_visit",
"signature": "def generic_visit(self, node: Iterable[Any], ... | 2 | null | Implement the Python class `GrammarVisitor` described below.
Class description:
Implement the GrammarVisitor class.
Method signatures and docstrings:
- def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any: Visit a node.
- def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None: Called ... | Implement the Python class `GrammarVisitor` described below.
Class description:
Implement the GrammarVisitor class.
Method signatures and docstrings:
- def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any: Visit a node.
- def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None: Called ... | c50cd2b9154c83c3db5e4a11b9e8874f7fb8afa2 | <|skeleton|>
class GrammarVisitor:
def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any:
"""Visit a node."""
<|body_0|>
def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None:
"""Called if no explicit visitor function exists for a node."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GrammarVisitor:
def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any:
"""Visit a node."""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node, *args, **kwargs)
def generic_visit(self, node: Iterable[An... | the_stack_v2_python_sparse | Δ3/DSL/Python/cpython/Tools/peg_generator/pegen/grammar.py | arXiv-research/DevLab-III-1 | train | 2 | |
d60d4a77f44b3a8cce24c974deac3c20b63bd6d8 | [
"for cube in cubes:\n self._fix_names(cube)\n self._fix_units(cube)\n self._fix_time(cube)\n fix_longitude(cube)\n self._fix_bounds(cube)\nreturn cubes",
"frequency = self.vardef.frequency\nif frequency in ('day', '3hr'):\n fix_time_day(cube)\nelif frequency == 'mon':\n fix_time_month(cube)\n... | <|body_start_0|>
for cube in cubes:
self._fix_names(cube)
self._fix_units(cube)
self._fix_time(cube)
fix_longitude(cube)
self._fix_bounds(cube)
return cubes
<|end_body_0|>
<|body_start_1|>
frequency = self.vardef.frequency
if f... | Fixes for pr. | Pr | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
<|body_0|>
def _fix_time(self, cube):
"""Fix time."""
<|body_1|>
def _fix_units(self, cube):
"""Convert units from mm/[t] to kg m-2 s-1 units."""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_007709 | 3,891 | permissive | [
{
"docstring": "Fix metadata.",
"name": "fix_metadata",
"signature": "def fix_metadata(self, cubes)"
},
{
"docstring": "Fix time.",
"name": "_fix_time",
"signature": "def _fix_time(self, cube)"
},
{
"docstring": "Convert units from mm/[t] to kg m-2 s-1 units.",
"name": "_fix_... | 5 | stack_v2_sparse_classes_30k_train_007102 | Implement the Python class `Pr` described below.
Class description:
Fixes for pr.
Method signatures and docstrings:
- def fix_metadata(self, cubes): Fix metadata.
- def _fix_time(self, cube): Fix time.
- def _fix_units(self, cube): Convert units from mm/[t] to kg m-2 s-1 units.
- def _fix_bounds(self, cube): Add boun... | Implement the Python class `Pr` described below.
Class description:
Fixes for pr.
Method signatures and docstrings:
- def fix_metadata(self, cubes): Fix metadata.
- def _fix_time(self, cube): Fix time.
- def _fix_units(self, cube): Convert units from mm/[t] to kg m-2 s-1 units.
- def _fix_bounds(self, cube): Add boun... | d5187438fea2928644cb53ecb26c6adb1e4cc947 | <|skeleton|>
class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
<|body_0|>
def _fix_time(self, cube):
"""Fix time."""
<|body_1|>
def _fix_units(self, cube):
"""Convert units from mm/[t] to kg m-2 s-1 units."""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pr:
"""Fixes for pr."""
def fix_metadata(self, cubes):
"""Fix metadata."""
for cube in cubes:
self._fix_names(cube)
self._fix_units(cube)
self._fix_time(cube)
fix_longitude(cube)
self._fix_bounds(cube)
return cubes
d... | the_stack_v2_python_sparse | esmvalcore/cmor/_fixes/native6/mswep.py | ESMValGroup/ESMValCore | train | 41 |
7896da76ccdf33988ab7f8cfad7f6bb289d78c7e | [
"if model._meta.app_label == 'whalesdb':\n return 'whalesdb'\nreturn None",
"if model._meta.app_label == 'whalesdb':\n return 'whalesdb'\nreturn None",
"if obj1._meta.app_label == 'whalesdb' and obj2._meta.app_label == 'whalesdb':\n return True\nelif 'whalesdb' not in [obj1._meta.app_label, obj2._meta.... | <|body_start_0|>
if model._meta.app_label == 'whalesdb':
return 'whalesdb'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label == 'whalesdb':
return 'whalesdb'
return None
<|end_body_1|>
<|body_start_2|>
if obj1._meta.app_label == 'whale... | WhaleDatabaseRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhaleDatabaseRouter:
def db_for_read(self, model, **hints):
"""Send all read operations on whalesdb app models to `whalesdb`."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Send all write operations on whalesdb app models to `whalesdb`."""
<|body_1|... | stack_v2_sparse_classes_36k_train_007710 | 1,977 | no_license | [
{
"docstring": "Send all read operations on whalesdb app models to `whalesdb`.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Send all write operations on whalesdb app models to `whalesdb`.",
"name": "db_for_write",
"signature": "def db_f... | 4 | stack_v2_sparse_classes_30k_train_005411 | Implement the Python class `WhaleDatabaseRouter` described below.
Class description:
Implement the WhaleDatabaseRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on whalesdb app models to `whalesdb`.
- def db_for_write(self, model, **hints): Send all wri... | Implement the Python class `WhaleDatabaseRouter` described below.
Class description:
Implement the WhaleDatabaseRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Send all read operations on whalesdb app models to `whalesdb`.
- def db_for_write(self, model, **hints): Send all wri... | 483f855b19876fd60c0017a270df74e076aa0d8b | <|skeleton|>
class WhaleDatabaseRouter:
def db_for_read(self, model, **hints):
"""Send all read operations on whalesdb app models to `whalesdb`."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Send all write operations on whalesdb app models to `whalesdb`."""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhaleDatabaseRouter:
def db_for_read(self, model, **hints):
"""Send all read operations on whalesdb app models to `whalesdb`."""
if model._meta.app_label == 'whalesdb':
return 'whalesdb'
return None
def db_for_write(self, model, **hints):
"""Send all write oper... | the_stack_v2_python_sparse | dm_apps/routers.py | yc-hu/dm_apps | train | 0 | |
6af93c9a4bf7e273647fde1c54d9074754beafda | [
"self.controller = None\nself.ip_addr = ip\nself.rot = rot\nself.theta = theta\nself.orig = orig\nself.calibration = calibration\nself.logger = logger",
"if self.controller is not None and self.controller.isConnected():\n self.Disconnect()\nself.controller = rtde_control.RTDEControlInterface(self.ip_addr)\nsel... | <|body_start_0|>
self.controller = None
self.ip_addr = ip
self.rot = rot
self.theta = theta
self.orig = orig
self.calibration = calibration
self.logger = logger
<|end_body_0|>
<|body_start_1|>
if self.controller is not None and self.controller.isConnected... | Robot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Robot:
def __init__(self, ip, rot, theta, orig, calibration, logger):
"""Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensentation of TCP rotation in radians theta (double): Rotation angle around Z for transformation o... | stack_v2_sparse_classes_36k_train_007711 | 3,876 | no_license | [
{
"docstring": "Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensentation of TCP rotation in radians theta (double): Rotation angle around Z for transformation orig (list<double>): Origin of robot calibration (list<double>): List of offsets t... | 5 | stack_v2_sparse_classes_30k_train_015807 | Implement the Python class `Robot` described below.
Class description:
Implement the Robot class.
Method signatures and docstrings:
- def __init__(self, ip, rot, theta, orig, calibration, logger): Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensen... | Implement the Python class `Robot` described below.
Class description:
Implement the Robot class.
Method signatures and docstrings:
- def __init__(self, ip, rot, theta, orig, calibration, logger): Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensen... | 8f8dba16b65f70c8cb716d7cc74ac06001d4d372 | <|skeleton|>
class Robot:
def __init__(self, ip, rot, theta, orig, calibration, logger):
"""Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensentation of TCP rotation in radians theta (double): Rotation angle around Z for transformation o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Robot:
def __init__(self, ip, rot, theta, orig, calibration, logger):
"""Initialises new robot controller object. Args: ip (string): IPv4 address of robot to manage rot (list<double>): Reprensentation of TCP rotation in radians theta (double): Rotation angle around Z for transformation orig (list<doub... | the_stack_v2_python_sparse | Python/robot_controller.py | Zeltnervonbank/EBI-Thesis-Code | train | 0 | |
d9c3495132f3f935de1c46b188af433fd39bdc21 | [
"n = len(arr)\ninit, missing = (0, 0)\nfor i in range(1, n + 1):\n if arr[i - 1] - i > 0:\n missing = arr[i - 1] - i\n if missing >= k:\n return arr[i - 2] + k - init if i >= 2 else k - init\n init = missing\nreturn arr[-1] + k - missing",
"l, r = (0, len(arr))\nwhile l < r:\n mid = (l +... | <|body_start_0|>
n = len(arr)
init, missing = (0, 0)
for i in range(1, n + 1):
if arr[i - 1] - i > 0:
missing = arr[i - 1] - i
if missing >= k:
return arr[i - 2] + k - init if i >= 2 else k - init
init = missing
return a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthPositive(self, arr, k):
""":type arr: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthPositiveLogN(self, arr, k):
""":type arr: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = l... | stack_v2_sparse_classes_36k_train_007712 | 1,958 | no_license | [
{
"docstring": ":type arr: List[int] :type k: int :rtype: int",
"name": "findKthPositive",
"signature": "def findKthPositive(self, arr, k)"
},
{
"docstring": ":type arr: List[int] :type k: int :rtype: int",
"name": "findKthPositiveLogN",
"signature": "def findKthPositiveLogN(self, arr, k... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int
- def findKthPositiveLogN(self, arr, k): :type arr: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthPositive(self, arr, k): :type arr: List[int] :type k: int :rtype: int
- def findKthPositiveLogN(self, arr, k): :type arr: List[int] :type k: int :rtype: int
<|skeleto... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findKthPositive(self, arr, k):
""":type arr: List[int] :type k: int :rtype: int"""
<|body_0|>
def findKthPositiveLogN(self, arr, k):
""":type arr: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthPositive(self, arr, k):
""":type arr: List[int] :type k: int :rtype: int"""
n = len(arr)
init, missing = (0, 0)
for i in range(1, n + 1):
if arr[i - 1] - i > 0:
missing = arr[i - 1] - i
if missing >= k:
... | the_stack_v2_python_sparse | K/KthMissingPositiveNumber.py | bssrdf/pyleet | train | 2 | |
6c8d308899ed9198378113cba246fcd0d2bb3dac | [
"bytestring = b''\nwhile not parser.is_end():\n field = parser.read_field()\n if field.name == _ARRAY_END_MARKER_NAME:\n break\n bytestring += bytes(field.header)\n bytestring += bytes(parser.read_field_value(field))\n bytestring += _OBJECT_END_MARKER\nbytestring += _ARRAY_END_MARKER\nreturn S... | <|body_start_0|>
bytestring = b''
while not parser.is_end():
field = parser.read_field()
if field.name == _ARRAY_END_MARKER_NAME:
break
bytestring += bytes(field.header)
bytestring += bytes(parser.read_field_value(field))
bytest... | Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_ | SerializedList | [
"ISC",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SerializedList:
"""Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_"""
def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_hint: Optional[None]=None) -> SerializedList:
"""Construct a... | stack_v2_sparse_classes_36k_train_007713 | 3,451 | permissive | [
{
"docstring": "Construct a SerializedList from a BinaryParser. Args: parser: The parser to construct a SerializedList from. Returns: The SerializedList constructed from parser.",
"name": "from_parser",
"signature": "def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_hint: Optional... | 3 | null | Implement the Python class `SerializedList` described below.
Class description:
Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_
Method signatures and docstrings:
- def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_... | Implement the Python class `SerializedList` described below.
Class description:
Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_
Method signatures and docstrings:
- def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_... | e5bbdf458ad83e6670a4ebf3df63e17fed8b099f | <|skeleton|>
class SerializedList:
"""Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_"""
def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_hint: Optional[None]=None) -> SerializedList:
"""Construct a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SerializedList:
"""Class for serializing and deserializing Lists of objects. See `Array Fields <https://xrpl.org/serialization.html#array-fields>`_"""
def from_parser(cls: Type[SerializedList], parser: BinaryParser, _length_hint: Optional[None]=None) -> SerializedList:
"""Construct a SerializedLi... | the_stack_v2_python_sparse | xrpl/core/binarycodec/types/serialized_list.py | yyolk/xrpl-py | train | 1 |
f6226e926b993879c5f3e9d70b938fdff4af76aa | [
"d = {}\nfor i in nums:\n d.setdefault(str(i), 0)\nfor i in nums:\n d[str(i)] += 1\nf = zip(d.values(), d.keys())\nf.sort(key=lambda x: x[0], reverse=True)\nlistt = []\nfor i in range(k):\n listt.append(int(f[i][1]))\nprint(listt)\nreturn listt",
"import collections\nprint(collections.Counter(nums))\npri... | <|body_start_0|>
d = {}
for i in nums:
d.setdefault(str(i), 0)
for i in nums:
d[str(i)] += 1
f = zip(d.values(), d.keys())
f.sort(key=lambda x: x[0], reverse=True)
listt = []
for i in range(k):
listt.append(int(f[i][1]))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007714 | 1,242 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "topKFrequent2",
"signature": "def topKFrequent2(self, nums, k)"... | 2 | stack_v2_sparse_classes_30k_train_004371 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def topKFrequent2(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|... | eb5f6488c875c107743f84a44cbbf55ff7ed3296 | <|skeleton|>
class Solution:
def topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def topKFrequent2(self, nums, k):
""":type nums: 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 topKFrequent(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
d = {}
for i in nums:
d.setdefault(str(i), 0)
for i in nums:
d[str(i)] += 1
f = zip(d.values(), d.keys())
f.sort(key=lambda x: x[0], rev... | the_stack_v2_python_sparse | 347__Top K Frequent Elements.py | chengcheng8632/lovely-nuts | train | 0 | |
70a7f1a0602d48a5278caf03dbcb2a215bd1d01b | [
"super(PreprocessingWorker, self).__init__()\nself.linesForPreprocessing = linesForPreprocessing\nself.fileToRead = fileToRead\nself.sharedCache = sharedCache\nself.args = args\nself.wordsRemover = wordsRemover\nself.lemPosExt = lemPosExt\nself.onlyPos = onlyPos\nself.errorBoard = errorBoard",
"if line == '':\n ... | <|body_start_0|>
super(PreprocessingWorker, self).__init__()
self.linesForPreprocessing = linesForPreprocessing
self.fileToRead = fileToRead
self.sharedCache = sharedCache
self.args = args
self.wordsRemover = wordsRemover
self.lemPosExt = lemPosExt
self.on... | Třída reprezentující jeden pracující proces provádějící předzpracování. | PreprocessingWorker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreprocessingWorker:
"""Třída reprezentující jeden pracující proces provádějící předzpracování."""
def __init__(self, linesForPreprocessing, fileToRead, sharedCache, args, wordsRemover, lemPosExt, onlyPos, errorBoard):
"""Inicializace procesu. :param linesForPreprocessing: Queue obsa... | stack_v2_sparse_classes_36k_train_007715 | 35,729 | no_license | [
{
"docstring": "Inicializace procesu. :param linesForPreprocessing: Queue obsahující řádky pro předzpracování. :param fileToRead: Cesta k souboru, ze kterého získáme řádky pro čtení. Používá se pokud je předán pouze offset. :type sharedCache: SharedDocumentCache :param sharedCache: Sdílená cache pro ukládání řá... | 3 | stack_v2_sparse_classes_30k_train_007213 | Implement the Python class `PreprocessingWorker` described below.
Class description:
Třída reprezentující jeden pracující proces provádějící předzpracování.
Method signatures and docstrings:
- def __init__(self, linesForPreprocessing, fileToRead, sharedCache, args, wordsRemover, lemPosExt, onlyPos, errorBoard): Inici... | Implement the Python class `PreprocessingWorker` described below.
Class description:
Třída reprezentující jeden pracující proces provádějící předzpracování.
Method signatures and docstrings:
- def __init__(self, linesForPreprocessing, fileToRead, sharedCache, args, wordsRemover, lemPosExt, onlyPos, errorBoard): Inici... | 4e5395875d60ed3b138922d1100f6a4e05ac60e7 | <|skeleton|>
class PreprocessingWorker:
"""Třída reprezentující jeden pracující proces provádějící předzpracování."""
def __init__(self, linesForPreprocessing, fileToRead, sharedCache, args, wordsRemover, lemPosExt, onlyPos, errorBoard):
"""Inicializace procesu. :param linesForPreprocessing: Queue obsa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreprocessingWorker:
"""Třída reprezentující jeden pracující proces provádějící předzpracování."""
def __init__(self, linesForPreprocessing, fileToRead, sharedCache, args, wordsRemover, lemPosExt, onlyPos, errorBoard):
"""Inicializace procesu. :param linesForPreprocessing: Queue obsahující řádky ... | the_stack_v2_python_sparse | CPKclassifierPack/preprocessing/Preprocessing.py | KNOT-FIT-BUT/CPKclassifier | train | 1 |
4022a86d614484bafe7548750f4e12f6a51dd300 | [
"try:\n self.key = RSA.import_key(public_key)\n self.cipher = PKCS1_OAEP.new(self.key)\n self.verifier = pkcs1_15.new(self.key)\nexcept (ValueError, TypeError):\n print('导入公钥出错: %s' % public_key)",
"result = self.cipher.encrypt(msg)\ndigest = SHA256.new(msg)\nreturn (result, digest)",
"try:\n sel... | <|body_start_0|>
try:
self.key = RSA.import_key(public_key)
self.cipher = PKCS1_OAEP.new(self.key)
self.verifier = pkcs1_15.new(self.key)
except (ValueError, TypeError):
print('导入公钥出错: %s' % public_key)
<|end_body_0|>
<|body_start_1|>
result = sel... | 这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。 | PublicCipher | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublicCipher:
"""这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。"""
def __init__(self, public_key: bytes):
"""根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥"""
<|body_0|>
def encrypt_message(self, msg: bytes) -> (byt... | stack_v2_sparse_classes_36k_train_007716 | 3,452 | no_license | [
{
"docstring": "根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥",
"name": "__init__",
"signature": "def __init__(self, public_key: bytes)"
},
{
"docstring": "对提供的msg用公钥进行加密。 @param msg: 需要加密的信息。 @return: (加密后的信息,digest校验信息)",
"name": "encrypt_message",
"signature": "def encrypt_m... | 3 | stack_v2_sparse_classes_30k_train_010260 | Implement the Python class `PublicCipher` described below.
Class description:
这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。
Method signatures and docstrings:
- def __init__(self, public_key: bytes): 根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥
- def encrypt_m... | Implement the Python class `PublicCipher` described below.
Class description:
这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。
Method signatures and docstrings:
- def __init__(self, public_key: bytes): 根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥
- def encrypt_m... | 8e012855cce61fb53437758021416e5f6deb02ea | <|skeleton|>
class PublicCipher:
"""这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。"""
def __init__(self, public_key: bytes):
"""根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥"""
<|body_0|>
def encrypt_message(self, msg: bytes) -> (byt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublicCipher:
"""这个类包含对应的公钥创建的cipher,包含用公钥对信息进行加密和用公钥对信息进行验证的功能。 一般来讲,这部分应该是在客户端处调用,生成用公钥加密后的信息和digest用来通信和校验。"""
def __init__(self, public_key: bytes):
"""根据提供的public_key初始化PublicCipher. @param public_key: 客户公钥"""
try:
self.key = RSA.import_key(public_key)
self.ci... | the_stack_v2_python_sparse | DEMO/auth_server/authantication/cipher.py | hanhiver/PythonBasic | train | 0 |
f4390320fd282d7f51a97983600409b69edbea7d | [
"self._cache: dict[str, dict[str, str]] = {}\nself._exact = exact\nself._domain = domain\nif glob is None:\n compiled: dict[re.Pattern[str], Any] | None = None\nelse:\n compiled = OrderedDict()\n for key, value in glob.items():\n compiled[re.compile(fnmatch.translate(key))] = value\nself._glob = com... | <|body_start_0|>
self._cache: dict[str, dict[str, str]] = {}
self._exact = exact
self._domain = domain
if glob is None:
compiled: dict[re.Pattern[str], Any] | None = None
else:
compiled = OrderedDict()
for key, value in glob.items():
... | Class to store entity id based values. | EntityValues | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_007717 | 1,631 | permissive | [
{
"docstring": "Initialize an EntityConfigDict.",
"name": "__init__",
"signature": "def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None"
},
{
"docstring": "Get config for an entity id... | 2 | null | Implement the Python class `EntityValues` described below.
Class description:
Class to store entity id based values.
Method signatures and docstrings:
- def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:... | Implement the Python class `EntityValues` described below.
Class description:
Class to store entity id based values.
Method signatures and docstrings:
- def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityValues:
"""Class to store entity id based values."""
def __init__(self, exact: dict[str, dict[str, str]] | None=None, domain: dict[str, dict[str, str]] | None=None, glob: dict[str, dict[str, str]] | None=None) -> None:
"""Initialize an EntityConfigDict."""
self._cache: dict[str, dic... | the_stack_v2_python_sparse | homeassistant/helpers/entity_values.py | konnected-io/home-assistant | train | 24 |
b313e68fd80438658763cc519ad31869719905e3 | [
"self.filepath = filepath\nself.sheet_name = sheet_name\nself.xls_wb = xlrd.open_workbook(self.filepath)\nself.xls_ws = self.xls_wb.sheet_names()\nself.xls_wl = self.xls_wb.sheet_loaded(self.sheet_name)",
"try:\n xls_ws = self.xls_wb.sheet_by_name(self.sheet_name)\n valid_rows = xls_ws.nrows\n valid_cols... | <|body_start_0|>
self.filepath = filepath
self.sheet_name = sheet_name
self.xls_wb = xlrd.open_workbook(self.filepath)
self.xls_ws = self.xls_wb.sheet_names()
self.xls_wl = self.xls_wb.sheet_loaded(self.sheet_name)
<|end_body_0|>
<|body_start_1|>
try:
xls_ws ... | 工作薄 sheet页 单元格 行 列 | ExcelUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
<|body_0|>
def operate_row(self):
"""行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:"""
... | stack_v2_sparse_classes_36k_train_007718 | 3,336 | no_license | [
{
"docstring": "初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称",
"name": "__init__",
"signature": "def __init__(self, filepath, sheet_name='')"
},
{
"docstring": "行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:",
"name": "operate_row",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_017234 | Implement the Python class `ExcelUtil` described below.
Class description:
工作薄 sheet页 单元格 行 列
Method signatures and docstrings:
- def __init__(self, filepath, sheet_name=''): 初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称
- def operate_row(self): 行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用... | Implement the Python class `ExcelUtil` described below.
Class description:
工作薄 sheet页 单元格 行 列
Method signatures and docstrings:
- def __init__(self, filepath, sheet_name=''): 初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称
- def operate_row(self): 行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用... | d885b520757097c1d984d1cdda5d242ee5c6a5d6 | <|skeleton|>
class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
<|body_0|>
def operate_row(self):
"""行的操作 列的操作相同 xls_ws, valid_rows等都是局部变量,作用域只在该方法内 :return:"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExcelUtil:
"""工作薄 sheet页 单元格 行 列"""
def __init__(self, filepath, sheet_name=''):
"""初始化对象的同时就设置初始值,通过形参传递数据 :param filepath: excel文件路径 :param sheet_name: sheet名称"""
self.filepath = filepath
self.sheet_name = sheet_name
self.xls_wb = xlrd.open_workbook(self.filepath)
... | the_stack_v2_python_sparse | API_AutoTest/Study/y_xlrd.py | yolotester/learngit | train | 0 |
fb8061408c2a9f6eac6a9b5b152971cd028cf0d0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DisplayTemplate()",
"from ..json import Json\nfrom .property_rule import PropertyRule\nfrom ..json import Json\nfrom .property_rule import PropertyRule\nfields: Dict[str, Callable[[Any], None]] = {'id': lambda n: setattr(self, 'id', n.... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DisplayTemplate()
<|end_body_0|>
<|body_start_1|>
from ..json import Json
from .property_rule import PropertyRule
from ..json import Json
from .property_rule import Prope... | DisplayTemplate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisplayTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DisplayTemplate:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k_train_007719 | 3,674 | 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: DisplayTemplate",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `DisplayTemplate` described below.
Class description:
Implement the DisplayTemplate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DisplayTemplate: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `DisplayTemplate` described below.
Class description:
Implement the DisplayTemplate class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DisplayTemplate: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DisplayTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DisplayTemplate:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DisplayTemplate:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DisplayTemplate:
"""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: DisplayT... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/display_template.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
544aa299c7a2e642ee746489450a08472085e568 | [
"self.cached_sums = matrix\nfor i0 in range(len(matrix)):\n for j0 in range(len(matrix[i0])):\n if i0 == 0 and j0 == 0:\n pass\n elif i0 == 0:\n self.cached_sums[i0][j0] = self.cached_sums[i0][j0 - 1] + matrix[i0][j0]\n elif j0 == 0:\n self.cached_sums[i0][j0... | <|body_start_0|>
self.cached_sums = matrix
for i0 in range(len(matrix)):
for j0 in range(len(matrix[i0])):
if i0 == 0 and j0 == 0:
pass
elif i0 == 0:
self.cached_sums[i0][j0] = self.cached_sums[i0][j0 - 1] + matrix[i0][j... | 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_007720 | 1,404 | 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 | stack_v2_sparse_classes_30k_train_010516 | 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:... | 3997b8bfa90a27cf8ccda10cdd34e9db3afebd7a | <|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.cached_sums = matrix
for i0 in range(len(matrix)):
for j0 in range(len(matrix[i0])):
if i0 == 0 and j0 == 0:
pass
elif i0 == 0:
... | the_stack_v2_python_sparse | python/rangeSumQuery2D.py | achyudh/leetcode-solutions | train | 1 | |
6963a41841810b9c803b73446dd64363cf452939 | [
"self.exe = screen_conf['phantom']\nself.load_delay = screen_conf['load_delay']\nself.width = screen_conf['width']\nself.height = screen_conf['height']\nself.timeout = screen_conf['timeout'] / 1000\nself.logger = logging.getLogger('screenshot')\nself.logger.setLevel(logging.INFO)\nif not os.path.exists(self.exe):\n... | <|body_start_0|>
self.exe = screen_conf['phantom']
self.load_delay = screen_conf['load_delay']
self.width = screen_conf['width']
self.height = screen_conf['height']
self.timeout = screen_conf['timeout'] / 1000
self.logger = logging.getLogger('screenshot')
self.log... | Screenshot | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screenshot:
def __init__(self, screen_conf):
"""Init the screenshot service :param screen_conf: A dict with the following keys, "phantom": the path to the phantomjs binary "width", "height": The desired width / height of the viewport "loadDelay": The delay in ms after which the screensho... | stack_v2_sparse_classes_36k_train_007721 | 2,616 | permissive | [
{
"docstring": "Init the screenshot service :param screen_conf: A dict with the following keys, \"phantom\": the path to the phantomjs binary \"width\", \"height\": The desired width / height of the viewport \"loadDelay\": The delay in ms after which the screenshot is taken \"timeout\": The maximum time in ms t... | 2 | stack_v2_sparse_classes_30k_train_008472 | Implement the Python class `Screenshot` described below.
Class description:
Implement the Screenshot class.
Method signatures and docstrings:
- def __init__(self, screen_conf): Init the screenshot service :param screen_conf: A dict with the following keys, "phantom": the path to the phantomjs binary "width", "height"... | Implement the Python class `Screenshot` described below.
Class description:
Implement the Screenshot class.
Method signatures and docstrings:
- def __init__(self, screen_conf): Init the screenshot service :param screen_conf: A dict with the following keys, "phantom": the path to the phantomjs binary "width", "height"... | 1cd1e83902119938ffd412394b09dce92d082500 | <|skeleton|>
class Screenshot:
def __init__(self, screen_conf):
"""Init the screenshot service :param screen_conf: A dict with the following keys, "phantom": the path to the phantomjs binary "width", "height": The desired width / height of the viewport "loadDelay": The delay in ms after which the screensho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Screenshot:
def __init__(self, screen_conf):
"""Init the screenshot service :param screen_conf: A dict with the following keys, "phantom": the path to the phantomjs binary "width", "height": The desired width / height of the viewport "loadDelay": The delay in ms after which the screenshot is taken "ti... | the_stack_v2_python_sparse | plugins/comp_screenshot/comp_screenshot/screenshot.py | reseachalps/Search-Engine | train | 0 | |
e1e2074cd9c8f90baffffb2d96d4f32b5f4b0646 | [
"test_response = self.client.get('/people/')\nself.assertEqual(test_response.status_code, 200)\nself.assertTrue('personnel' in test_response.context)\nself.assertTemplateUsed(test_response, 'personnel_list.html')\nself.assertEqual(test_response.context['personnel_type'], 'current')\nself.assertEqual(test_response.c... | <|body_start_0|>
test_response = self.client.get('/people/')
self.assertEqual(test_response.status_code, 200)
self.assertTrue('personnel' in test_response.context)
self.assertTemplateUsed(test_response, 'personnel_list.html')
self.assertEqual(test_response.context['personnel_type... | Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app. | PersonnelViewTests | [
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
<|body_0|>
def test_personnel_detail(self):
"""This func... | stack_v2_sparse_classes_36k_train_007722 | 5,452 | permissive | [
{
"docstring": "This function tests the laboratory-personnel view.",
"name": "test_laboratory_personnel",
"signature": "def test_laboratory_personnel(self)"
},
{
"docstring": "This function tests the personnel-details view.",
"name": "test_personnel_detail",
"signature": "def test_person... | 2 | stack_v2_sparse_classes_30k_train_000826 | Implement the Python class `PersonnelViewTests` described below.
Class description:
Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_laboratory_personnel(self): This function tests the laboratory-personnel view.
- def test_personnel_de... | Implement the Python class `PersonnelViewTests` described below.
Class description:
Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app.
Method signatures and docstrings:
- def test_laboratory_personnel(self): This function tests the laboratory-personnel view.
- def test_personnel_de... | d6f6c9c068bbf668c253e5943d9514947023e66d | <|skeleton|>
class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
<|body_0|>
def test_personnel_detail(self):
"""This func... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonnelViewTests:
"""Tests the views of ::class:`Personnel` objects contained in the ::mod:`personnel` app."""
def test_laboratory_personnel(self):
"""This function tests the laboratory-personnel view."""
test_response = self.client.get('/people/')
self.assertEqual(test_response... | the_stack_v2_python_sparse | personnel/tests.py | BridgesLab/Lab-Website | train | 0 |
1bc92c5983dcb5bd170820b64dec6d0c62f6ce7a | [
"super().__init__(coordinator)\nself.entity_description = description\nself._ec_data = coordinator.ec_data\nself._attr_attribution = self._ec_data.metadata['attribution']\nself._attr_unique_id = f'{coordinator.config_entry.title}-{description.key}'\nself._attr_device_info = device_info(coordinator.config_entry)",
... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._ec_data = coordinator.ec_data
self._attr_attribution = self._ec_data.metadata['attribution']
self._attr_unique_id = f'{coordinator.config_entry.title}-{description.key}'
self._attr_... | Environment Canada sensor base. | ECBaseSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ECBaseSensor:
"""Environment Canada sensor base."""
def __init__(self, coordinator, description):
"""Initialize the base sensor."""
<|body_0|>
def native_value(self):
"""Return the native value of the sensor."""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_007723 | 12,232 | permissive | [
{
"docstring": "Initialize the base sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator, description)"
},
{
"docstring": "Return the native value of the sensor.",
"name": "native_value",
"signature": "def native_value(self)"
}
] | 2 | null | Implement the Python class `ECBaseSensor` described below.
Class description:
Environment Canada sensor base.
Method signatures and docstrings:
- def __init__(self, coordinator, description): Initialize the base sensor.
- def native_value(self): Return the native value of the sensor. | Implement the Python class `ECBaseSensor` described below.
Class description:
Environment Canada sensor base.
Method signatures and docstrings:
- def __init__(self, coordinator, description): Initialize the base sensor.
- def native_value(self): Return the native value of the sensor.
<|skeleton|>
class ECBaseSensor:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class ECBaseSensor:
"""Environment Canada sensor base."""
def __init__(self, coordinator, description):
"""Initialize the base sensor."""
<|body_0|>
def native_value(self):
"""Return the native value of the sensor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ECBaseSensor:
"""Environment Canada sensor base."""
def __init__(self, coordinator, description):
"""Initialize the base sensor."""
super().__init__(coordinator)
self.entity_description = description
self._ec_data = coordinator.ec_data
self._attr_attribution = self... | the_stack_v2_python_sparse | homeassistant/components/environment_canada/sensor.py | home-assistant/core | train | 35,501 |
9e0e45d46a3d8009059101e433f45d7038fedd31 | [
"modules_data = data[src]\nif modules_data.shape[1] == self._module_shape[1]:\n return np.transpose(modules_data, (3, 0, 2, 1))\nreturn modules_data",
"modules_data = stack_detector_data(data[src], src.split(' ')[1], real_array=False)\ndtype = modules_data.dtype\nif dtype == _IMAGE_DTYPE:\n return modules_d... | <|body_start_0|>
modules_data = data[src]
if modules_data.shape[1] == self._module_shape[1]:
return np.transpose(modules_data, (3, 0, 2, 1))
return modules_data
<|end_body_0|>
<|body_start_1|>
modules_data = stack_detector_data(data[src], src.split(' ')[1], real_array=False)... | AgipdImageAssembler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgipdImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, "image.data", (modules, x, y, memory cells) - raw, "image.data", (modules, x, y, memory cells) -> (memory cells, modules, y,... | stack_v2_sparse_classes_36k_train_007724 | 23,340 | permissive | [
{
"docstring": "Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, \"image.data\", (modules, x, y, memory cells) - raw, \"image.data\", (modules, x, y, memory cells) -> (memory cells, modules, y, x)",
"name": "_get_modules_bridge",
"signature": "def _get_modules_bri... | 2 | stack_v2_sparse_classes_30k_train_010406 | Implement the Python class `AgipdImageAssembler` described below.
Class description:
Implement the AgipdImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, "image.data", (m... | Implement the Python class `AgipdImageAssembler` described below.
Class description:
Implement the AgipdImageAssembler class.
Method signatures and docstrings:
- def _get_modules_bridge(self, data, src, modules): Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, "image.data", (m... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class AgipdImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, "image.data", (modules, x, y, memory cells) - raw, "image.data", (modules, x, y, memory cells) -> (memory cells, modules, y,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgipdImageAssembler:
def _get_modules_bridge(self, data, src, modules):
"""Override. Should work for both raw and calibrated data, according to DSSC. - calibrated, "image.data", (modules, x, y, memory cells) - raw, "image.data", (modules, x, y, memory cells) -> (memory cells, modules, y, x)"""
... | the_stack_v2_python_sparse | extra_foam/pipeline/processors/image_assembler.py | European-XFEL/EXtra-foam | train | 8 | |
4fb64ad4d5d473502454b57645aa395e2a3cb497 | [
"self._dataset_dir = dataset_dir\nself._tfrecords_dir = ops.join(dataset_dir, 'tfrecords')\nif not ops.exists(self._tfrecords_dir):\n raise ValueError('{:s} not exist, please check again'.format(self._tfrecords_dir))\nself._dataset_flags = flags.lower()\nif self._dataset_flags not in ['train', 'test', 'val']:\n ... | <|body_start_0|>
self._dataset_dir = dataset_dir
self._tfrecords_dir = ops.join(dataset_dir, 'tfrecords')
if not ops.exists(self._tfrecords_dir):
raise ValueError('{:s} not exist, please check again'.format(self._tfrecords_dir))
self._dataset_flags = flags.lower()
if ... | Read training examples from tfrecords for nsfw model | LaneNetDataFeeder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaneNetDataFeeder:
"""Read training examples from tfrecords for nsfw model"""
def __init__(self, dataset_dir, flags='train'):
""":param dataset_dir: :param flags:"""
<|body_0|>
def inputs(self, batch_size, num_epochs=None):
""":param batch_size: :param num_epochs... | stack_v2_sparse_classes_36k_train_007725 | 16,475 | permissive | [
{
"docstring": ":param dataset_dir: :param flags:",
"name": "__init__",
"signature": "def __init__(self, dataset_dir, flags='train')"
},
{
"docstring": ":param batch_size: :param num_epochs: :return: A tuple (images, labels), where: * images is a float tensor with shape [N, H, W, C] in the range... | 2 | stack_v2_sparse_classes_30k_train_012434 | Implement the Python class `LaneNetDataFeeder` described below.
Class description:
Read training examples from tfrecords for nsfw model
Method signatures and docstrings:
- def __init__(self, dataset_dir, flags='train'): :param dataset_dir: :param flags:
- def inputs(self, batch_size, num_epochs=None): :param batch_si... | Implement the Python class `LaneNetDataFeeder` described below.
Class description:
Read training examples from tfrecords for nsfw model
Method signatures and docstrings:
- def __init__(self, dataset_dir, flags='train'): :param dataset_dir: :param flags:
- def inputs(self, batch_size, num_epochs=None): :param batch_si... | b4e9eeb3b25597ce7a393771d3f324d64ec1348b | <|skeleton|>
class LaneNetDataFeeder:
"""Read training examples from tfrecords for nsfw model"""
def __init__(self, dataset_dir, flags='train'):
""":param dataset_dir: :param flags:"""
<|body_0|>
def inputs(self, batch_size, num_epochs=None):
""":param batch_size: :param num_epochs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaneNetDataFeeder:
"""Read training examples from tfrecords for nsfw model"""
def __init__(self, dataset_dir, flags='train'):
""":param dataset_dir: :param flags:"""
self._dataset_dir = dataset_dir
self._tfrecords_dir = ops.join(dataset_dir, 'tfrecords')
if not ops.exists(... | the_stack_v2_python_sparse | data_provider/lanenet_data_feed_pipline.py | xuanyuyt/lanenet-lane-detection | train | 8 |
9b3cb5f9ed083599534f3d4a073815d643880cc1 | [
"self.create_new_group = create_new_group\nself.ms_groups_vec = ms_groups_vec\nself.restore_original_owners_members = restore_original_owners_members\nself.restore_to_original = restore_to_original\nself.target_group = target_group\nself.target_group_name = target_group_name\nself.target_group_owner = target_group_... | <|body_start_0|>
self.create_new_group = create_new_group
self.ms_groups_vec = ms_groups_vec
self.restore_original_owners_members = restore_original_owners_members
self.restore_to_original = restore_to_original
self.target_group = target_group
self.target_group_name = tar... | Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO365GroupsParams_MSGroupInfo): List of groups getting restored. restore_original_owners_membe... | RestoreO365GroupsParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365GroupsParams:
"""Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO365GroupsParams_MSGroupInfo): List of gro... | stack_v2_sparse_classes_36k_train_007726 | 4,068 | permissive | [
{
"docstring": "Constructor for the RestoreO365GroupsParams class",
"name": "__init__",
"signature": "def __init__(self, create_new_group=None, ms_groups_vec=None, restore_original_owners_members=None, restore_to_original=None, target_group=None, target_group_name=None, target_group_owner=None)"
},
... | 2 | stack_v2_sparse_classes_30k_train_007316 | Implement the Python class `RestoreO365GroupsParams` described below.
Class description:
Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO36... | Implement the Python class `RestoreO365GroupsParams` described below.
Class description:
Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO36... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365GroupsParams:
"""Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO365GroupsParams_MSGroupInfo): List of gro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreO365GroupsParams:
"""Implementation of the 'RestoreO365GroupsParams' model. TODO: type description here. Attributes: create_new_group (bool): Bool which specifies, if we have to create a new group if it doesn't exist. ms_groups_vec (list of RestoreO365GroupsParams_MSGroupInfo): List of groups getting r... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_groups_params.py | cohesity/management-sdk-python | train | 24 |
f18f3cfc4abc6dec6f740b7fc0eae25cde99245f | [
"copied = copy.deepcopy(dish_configuration)\ncopied.receiver_band = dish_configuration.receiver_band.value\nreturn copied",
"receiver_band = data['receiver_band']\nenum_obj = configure_msgs.ReceiverBand(receiver_band)\nreturn configure_msgs.DishConfiguration(enum_obj)"
] | <|body_start_0|>
copied = copy.deepcopy(dish_configuration)
copied.receiver_band = dish_configuration.receiver_band.value
return copied
<|end_body_0|>
<|body_start_1|>
receiver_band = data['receiver_band']
enum_obj = configure_msgs.ReceiverBand(receiver_band)
return conf... | Marshmallow schema for the subarray_node.DishConfiguration class. | DishConfigurationSchema | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DishConfigurationSchema:
"""Marshmallow schema for the subarray_node.DishConfiguration class."""
def convert(self, dish_configuration: configure_msgs.DishConfiguration, **_):
"""Process DishConfiguration instance so that it is ready for conversion to JSON. :param dish_configuration: ... | stack_v2_sparse_classes_36k_train_007727 | 6,676 | permissive | [
{
"docstring": "Process DishConfiguration instance so that it is ready for conversion to JSON. :param dish_configuration: the dish configuration :param _: kwargs passed by Marshmallow :return: DishConfiguration instance populated to match JSON",
"name": "convert",
"signature": "def convert(self, dish_co... | 2 | stack_v2_sparse_classes_30k_train_002107 | Implement the Python class `DishConfigurationSchema` described below.
Class description:
Marshmallow schema for the subarray_node.DishConfiguration class.
Method signatures and docstrings:
- def convert(self, dish_configuration: configure_msgs.DishConfiguration, **_): Process DishConfiguration instance so that it is ... | Implement the Python class `DishConfigurationSchema` described below.
Class description:
Marshmallow schema for the subarray_node.DishConfiguration class.
Method signatures and docstrings:
- def convert(self, dish_configuration: configure_msgs.DishConfiguration, **_): Process DishConfiguration instance so that it is ... | 87083655aca8f8f53a26dba253a0189d8519714b | <|skeleton|>
class DishConfigurationSchema:
"""Marshmallow schema for the subarray_node.DishConfiguration class."""
def convert(self, dish_configuration: configure_msgs.DishConfiguration, **_):
"""Process DishConfiguration instance so that it is ready for conversion to JSON. :param dish_configuration: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DishConfigurationSchema:
"""Marshmallow schema for the subarray_node.DishConfiguration class."""
def convert(self, dish_configuration: configure_msgs.DishConfiguration, **_):
"""Process DishConfiguration instance so that it is ready for conversion to JSON. :param dish_configuration: the dish conf... | the_stack_v2_python_sparse | src/ska_tmc_cdm/schemas/subarray_node/configure/core.py | ska-telescope/cdm-shared-library | train | 0 |
879c247b73b1abf367c0e2ae2016d3dcdc21d7f8 | [
"active = bot_update.check_valid_host(master, builder, slave) or force\noutput = {'did_run': active, 'patch_failure': False}\nif active:\n properties = {property_name: self.gen_revision(project_name, git_mode) for project_name, property_name in revision_mapping.iteritems()}\n if not git_mode:\n propert... | <|body_start_0|>
active = bot_update.check_valid_host(master, builder, slave) or force
output = {'did_run': active, 'patch_failure': False}
if active:
properties = {property_name: self.gen_revision(project_name, git_mode) for project_name, property_name in revision_mapping.iteritems(... | BotUpdateTestApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
<|body_0|>
def gen_revision(project, GIT_... | stack_v2_sparse_classes_36k_train_007728 | 1,905 | no_license | [
{
"docstring": "Deterministically synthesize json.output test data for gclient's --output-json option.",
"name": "output_json",
"signature": "def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False)"
},
{
"docstring": "Hash project... | 2 | null | Implement the Python class `BotUpdateTestApi` described below.
Class description:
Implement the BotUpdateTestApi class.
Method signatures and docstrings:
- def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False): Deterministically synthesize json.outpu... | Implement the Python class `BotUpdateTestApi` described below.
Class description:
Implement the BotUpdateTestApi class.
Method signatures and docstrings:
- def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False): Deterministically synthesize json.outpu... | 237c7e2c8fd3cf632f3bcdc9cc5da2d47ea7f153 | <|skeleton|>
class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
<|body_0|>
def gen_revision(project, GIT_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BotUpdateTestApi:
def output_json(self, master, builder, slave, root, first_sln, revision_mapping, git_mode, force=False, fail_patch=False):
"""Deterministically synthesize json.output test data for gclient's --output-json option."""
active = bot_update.check_valid_host(master, builder, slave)... | the_stack_v2_python_sparse | scripts/slave/recipe_modules/bot_update/test_api.py | bopopescu/build_internal | train | 0 | |
3a9492317c2cbd0cda515731be12781491f48c79 | [
"self.device = device\nself.alpha = alpha\nself.model = model.to(self.device)\nself.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad}\nself._means = {}\nself._precision_matrices = {}\nfor n, p in deepcopy(self.params).items():\n p.data.zero_()\n self._precision_matrices[n] = p.data.... | <|body_start_0|>
self.device = device
self.alpha = alpha
self.model = model.to(self.device)
self.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad}
self._means = {}
self._precision_matrices = {}
for n, p in deepcopy(self.params).items():
... | MAS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MAS:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5, n_slices=50):
"""MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrbach, M. and Tuytelaars, T., 2018. Memory aware synapses: Learning what (not) to forget. In P... | stack_v2_sparse_classes_36k_train_007729 | 3,545 | no_license | [
{
"docstring": "MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrbach, M. and Tuytelaars, T., 2018. Memory aware synapses: Learning what (not) to forget. In Proceedings of the European Conference on Computer Vision (ECCV) (pp. 139-154). Inputs: model : ... | 3 | stack_v2_sparse_classes_30k_train_010452 | Implement the Python class `MAS` described below.
Class description:
Implement the MAS class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5, n_slices=50): MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrb... | Implement the Python class `MAS` described below.
Class description:
Implement the MAS class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5, n_slices=50): MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrb... | f1f9e9f4f85c7eb076e3c15e2390c9d612adabdf | <|skeleton|>
class MAS:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5, n_slices=50):
"""MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrbach, M. and Tuytelaars, T., 2018. Memory aware synapses: Learning what (not) to forget. In P... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MAS:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5, n_slices=50):
"""MAS is the class for implementing the Memory-Aware-Synapses * Aljundi, R., Babiloni, F., Elhoseiny, M., Rohrbach, M. and Tuytelaars, T., 2018. Memory aware synapses: Learning what (not) to forget. In Proceedings of ... | the_stack_v2_python_sparse | utils/mas_utils/mas.py | lihr04/corel2m | train | 0 | |
f612d9de6520e811538ca6a8c3196fb44c807788 | [
"assert da.getDim() == 1\nself.da = da\nself.params = params\nself.factor = factor\nself.localX = da.createLocalVec()",
"self.da.globalToLocal(X, self.localX)\nx = self.da.getVecArray(self.localX)\nf = self.da.getVecArray(F)\nmx = self.da.getSizes()[0]\nxs, xe = self.da.getRanges()[0]\nfor i in range(xs, xe):\n ... | <|body_start_0|>
assert da.getDim() == 1
self.da = da
self.params = params
self.factor = factor
self.localX = da.createLocalVec()
<|end_body_0|>
<|body_start_1|>
self.da.globalToLocal(X, self.localX)
x = self.da.getVecArray(self.localX)
f = self.da.getVec... | Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES | Fisher_reaction | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, params, factor):
"""Initialization routine Args: da: DMDA object params: problem parameters factor: temporal factor (dt*Qd) dx: grid spacing in x dire... | stack_v2_sparse_classes_36k_train_007730 | 18,877 | permissive | [
{
"docstring": "Initialization routine Args: da: DMDA object params: problem parameters factor: temporal factor (dt*Qd) dx: grid spacing in x direction",
"name": "__init__",
"signature": "def __init__(self, da, params, factor)"
},
{
"docstring": "Function to evaluate the residual for the Newton ... | 3 | stack_v2_sparse_classes_30k_train_020576 | Implement the Python class `Fisher_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, params, factor): Initialization routine Args: da: DMDA object params: problem parameters f... | Implement the Python class `Fisher_reaction` described below.
Class description:
Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES
Method signatures and docstrings:
- def __init__(self, da, params, factor): Initialization routine Args: da: DMDA object params: problem parameters f... | de2cd523411276083355389d7e7993106cedf93d | <|skeleton|>
class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, params, factor):
"""Initialization routine Args: da: DMDA object params: problem parameters factor: temporal factor (dt*Qd) dx: grid spacing in x dire... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fisher_reaction:
"""Helper class to generate residual and Jacobian matrix for PETSc's nonlinear solver SNES"""
def __init__(self, da, params, factor):
"""Initialization routine Args: da: DMDA object params: problem parameters factor: temporal factor (dt*Qd) dx: grid spacing in x direction"""
... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/GeneralizedFisher_1D_PETSc.py | ruthschoebel/pySDC | train | 0 |
2a75b94e95bab6a40f675beb210a45e024bbb728 | [
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n n1 = pre.next\n n2 = n1.next\n tmp = n2.next\n pre.next = n2\n n2.next = n1\n n1.next = tmp\n pre = n1",
"dummy = ListNode(0)\ndummy.next = head\npre = dummy\nwhile pre.next and pre.next.next:\n first... | <|body_start_0|>
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
n2.next = n1
n1.next = tmp
pre = n1
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dummy = ListNode(0)
dummy.next ... | stack_v2_sparse_classes_36k_train_007731 | 1,460 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs",
"signature": "def swapPairs(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "swapPairs_2",
"signature": "def swapPairs_2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019985 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def swapPairs(self, head): :type head: ListNode :rtype: ListNode
- def swapPairs_2(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
def swapP... | a42098599bac4188eccb447de146434bc236a70a | <|skeleton|>
class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def swapPairs_2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def swapPairs(self, head):
""":type head: ListNode :rtype: ListNode"""
dummy = ListNode(0)
dummy.next = head
pre = dummy
while pre.next and pre.next.next:
n1 = pre.next
n2 = n1.next
tmp = n2.next
pre.next = n2
... | the_stack_v2_python_sparse | 力扣/z_03_两两交换链表中的节点.py | Pysuper/LetCODE | train | 1 | |
7f5f225373cd8cc6e8eec0bfc549a5c5ad6c6b9e | [
"self.list = nums\nself.map = {}\nfor i in nums:\n self.map[i] = self.map.get(i, 0) + 1",
"while self.list != [] and self.map[self.list[0]] > 1:\n self.list.pop(0)\nif self.list == []:\n return -1\nreturn self.list[0]",
"self.map[value] = self.map.get(value, 0) + 1\nif self.map[value] == 1:\n self.l... | <|body_start_0|>
self.list = nums
self.map = {}
for i in nums:
self.map[i] = self.map.get(i, 0) + 1
<|end_body_0|>
<|body_start_1|>
while self.list != [] and self.map[self.list[0]] > 1:
self.list.pop(0)
if self.list == []:
return -1
re... | Using dictionary to record the occurance of each element. Using list to return the first unique element | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
"""Using dictionary to record the occurance of each element. Using list to return the first unique element"""
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def ad... | stack_v2_sparse_classes_36k_train_007732 | 1,136 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":rtype: int",
"name": "showFirstUnique",
"signature": "def showFirstUnique(self)"
},
{
"docstring": ":type value: int :rtype: None",
"name": "add",
"sign... | 3 | stack_v2_sparse_classes_30k_train_001044 | Implement the Python class `FirstUnique` described below.
Class description:
Using dictionary to record the occurance of each element. Using list to return the first unique element
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(se... | Implement the Python class `FirstUnique` described below.
Class description:
Using dictionary to record the occurance of each element. Using list to return the first unique element
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(se... | 5de62902bee08a1b76259839dc797e305d1c3898 | <|skeleton|>
class FirstUnique:
"""Using dictionary to record the occurance of each element. Using list to return the first unique element"""
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def ad... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirstUnique:
"""Using dictionary to record the occurance of each element. Using list to return the first unique element"""
def __init__(self, nums):
""":type nums: List[int]"""
self.list = nums
self.map = {}
for i in nums:
self.map[i] = self.map.get(i, 0) + 1
... | the_stack_v2_python_sparse | 20200429_firstUniqueElement.py | hanggun/leetcode | train | 0 |
350e8ec366777d5ad0c8c027118375ae433887f0 | [
"if not strs:\n return ''\nseparate_length = '-'.join([str(len(s)) for s in strs])\ntotal_length = str(len(separate_length))\nreturn total_length + ' ' + separate_length + ' ' + ''.join(strs)",
"if not s:\n return []\nind = s.index(' ')\ntotal_length = int(s[:ind])\nseparate_length = [int(i) for i in s[ind ... | <|body_start_0|>
if not strs:
return ''
separate_length = '-'.join([str(len(s)) for s in strs])
total_length = str(len(separate_length))
return total_length + ' ' + separate_length + ' ' + ''.join(strs)
<|end_body_0|>
<|body_start_1|>
if not s:
return []
... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_007733 | 1,145 | permissive | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 975d7e3b8cb9b6be9e80e07febf4bcf6414acd46 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
if not strs:
return ''
separate_length = '-'.join([str(len(s)) for s in strs])
total_length = str(len(separate_length))
return total_length +... | the_stack_v2_python_sparse | Python/leetcode.271.encode-and-decode-strings.py | tedye/leetcode | train | 4 | |
a08244c3161a96d8fa01d155431f726be7e357c9 | [
"if PR2CMClient.pr2cm_client_instance == None:\n rospy.loginfo('instantiating a new pr2 controller manager client')\n PR2CMClient.pr2cm_client_instance = PR2CMClient()\nelse:\n rospy.loginfo('returning existing instance of client ' + str(PR2CMClient.pr2cm_client_instance))\nreturn PR2CMClient.pr2cm_client_... | <|body_start_0|>
if PR2CMClient.pr2cm_client_instance == None:
rospy.loginfo('instantiating a new pr2 controller manager client')
PR2CMClient.pr2cm_client_instance = PR2CMClient()
else:
rospy.loginfo('returning existing instance of client ' + str(PR2CMClient.pr2cm_cli... | This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (albeit stopped). | PR2CMClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PR2CMClient:
"""This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (albeit stopped)."""
def get_pr2cm_... | stack_v2_sparse_classes_36k_train_007734 | 5,234 | no_license | [
{
"docstring": "use this static factory method instead of the constructor to enforce singleton",
"name": "get_pr2cm_client",
"signature": "def get_pr2cm_client()"
},
{
"docstring": "do not call this constructor, call the static factory method instead",
"name": "__init__",
"signature": "d... | 4 | null | Implement the Python class `PR2CMClient` described below.
Class description:
This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (... | Implement the Python class `PR2CMClient` described below.
Class description:
This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (... | 05508bb956819eeff71c26ac9ecf62d3d3aab5db | <|skeleton|>
class PR2CMClient:
"""This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (albeit stopped)."""
def get_pr2cm_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PR2CMClient:
"""This class switches between the ee_cart_imped controller and the standard move_arm suite of controllers on the PR2 arms. When invoked, the methods stop one controller and start the other. They require that the controllers are already loaded (albeit stopped)."""
def get_pr2cm_client():
... | the_stack_v2_python_sparse | branches/sandbox/bakebot/src/clients/pr2cm_client.py | yutakage/mit-ros-pkg | train | 0 |
4c55b67c7884e1406e3bc9158c8e6848de2b910a | [
"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 Geo target constant service. Service to fetch geo target constants. | GeoTargetConstantServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoTargetConstantServiceServicer:
"""Proto file describing the Geo target constant service. Service to fetch geo target constants."""
def GetGeoTargetConstant(self, request, context):
"""Returns the requested geo target constant in full detail."""
<|body_0|>
def SuggestG... | stack_v2_sparse_classes_36k_train_007735 | 3,645 | permissive | [
{
"docstring": "Returns the requested geo target constant in full detail.",
"name": "GetGeoTargetConstant",
"signature": "def GetGeoTargetConstant(self, request, context)"
},
{
"docstring": "Returns GeoTargetConstant suggestions by location name or by resource name.",
"name": "SuggestGeoTarg... | 2 | stack_v2_sparse_classes_30k_train_015314 | Implement the Python class `GeoTargetConstantServiceServicer` described below.
Class description:
Proto file describing the Geo target constant service. Service to fetch geo target constants.
Method signatures and docstrings:
- def GetGeoTargetConstant(self, request, context): Returns the requested geo target constan... | Implement the Python class `GeoTargetConstantServiceServicer` described below.
Class description:
Proto file describing the Geo target constant service. Service to fetch geo target constants.
Method signatures and docstrings:
- def GetGeoTargetConstant(self, request, context): Returns the requested geo target constan... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class GeoTargetConstantServiceServicer:
"""Proto file describing the Geo target constant service. Service to fetch geo target constants."""
def GetGeoTargetConstant(self, request, context):
"""Returns the requested geo target constant in full detail."""
<|body_0|>
def SuggestG... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeoTargetConstantServiceServicer:
"""Proto file describing the Geo target constant service. Service to fetch geo target constants."""
def GetGeoTargetConstant(self, request, context):
"""Returns the requested geo target constant in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEM... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/geo_target_constant_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
d787b2ff925a978567c06c2a8174a2d3dfb9b541 | [
"super(LineEditIconButton, self).__init__(*args, **kw)\nself.setCursor(QtCore.Qt.ArrowCursor)\nself.setFocusPolicy(QtCore.Qt.NoFocus)",
"painter = QtWidgets.QPainter(self)\nstate = QtGui.QIcon.Disabled\nif self.isEnabled():\n state = QtGui.QIcon.Normal\n if self.isDown():\n state = QtGui.QIcon.Select... | <|body_start_0|>
super(LineEditIconButton, self).__init__(*args, **kw)
self.setCursor(QtCore.Qt.ArrowCursor)
self.setFocusPolicy(QtCore.Qt.NoFocus)
<|end_body_0|>
<|body_start_1|>
painter = QtWidgets.QPainter(self)
state = QtGui.QIcon.Disabled
if self.isEnabled():
... | Icon button for use in a :py:class:`LineEdit` widget. | LineEditIconButton | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineEditIconButton:
"""Icon button for use in a :py:class:`LineEdit` widget."""
def __init__(self, *args, **kw):
"""Initialise button."""
<|body_0|>
def paintEvent(self, event):
"""Handle paint *event*."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_007736 | 3,683 | permissive | [
{
"docstring": "Initialise button.",
"name": "__init__",
"signature": "def __init__(self, *args, **kw)"
},
{
"docstring": "Handle paint *event*.",
"name": "paintEvent",
"signature": "def paintEvent(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011451 | Implement the Python class `LineEditIconButton` described below.
Class description:
Icon button for use in a :py:class:`LineEdit` widget.
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialise button.
- def paintEvent(self, event): Handle paint *event*. | Implement the Python class `LineEditIconButton` described below.
Class description:
Icon button for use in a :py:class:`LineEdit` widget.
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialise button.
- def paintEvent(self, event): Handle paint *event*.
<|skeleton|>
class LineEditIconButton:... | f55f52787484fcf931c4653e7e241791f052c04f | <|skeleton|>
class LineEditIconButton:
"""Icon button for use in a :py:class:`LineEdit` widget."""
def __init__(self, *args, **kw):
"""Initialise button."""
<|body_0|>
def paintEvent(self, event):
"""Handle paint *event*."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineEditIconButton:
"""Icon button for use in a :py:class:`LineEdit` widget."""
def __init__(self, *args, **kw):
"""Initialise button."""
super(LineEditIconButton, self).__init__(*args, **kw)
self.setCursor(QtCore.Qt.ArrowCursor)
self.setFocusPolicy(QtCore.Qt.NoFocus)
... | the_stack_v2_python_sparse | source/ftrack_connect/ui/widget/line_edit.py | IngenuityEngine/ftrack-connect | train | 0 |
b23e049df3b28271e6a7589fe9e1f5592fd2a179 | [
"datastore.Entity.__init__(self, kind)\nif not isinstance(title, types.StringTypes):\n raise datastore_errors.BadValueError('Expected a string for title; received %s (a %s).' % (title, datastore_types.typename(title)))\nself['title'] = title\nself['content'] = ''\nself._contact_properties = set(contact_propertie... | <|body_start_0|>
datastore.Entity.__init__(self, kind)
if not isinstance(title, types.StringTypes):
raise datastore_errors.BadValueError('Expected a string for title; received %s (a %s).' % (title, datastore_types.typename(title)))
self['title'] = title
self['content'] = ''
... | A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags. | GdKind | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GdKind:
"""A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags."""
def __init__(self, kind, title, kind_properties, contact_pro... | stack_v2_sparse_classes_36k_train_007737 | 11,633 | permissive | [
{
"docstring": "Ctor. title is the name of this particular entity, e.g. Bob Jones or Mom's Birthday Party. kind_properties is a list of property names that should be included in this entity's XML encoding as first-class XML elements, instead of <property> elements. 'title' and 'content' are added to kind_proper... | 5 | null | Implement the Python class `GdKind` described below.
Class description:
A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags.
Method signatures and docstr... | Implement the Python class `GdKind` described below.
Class description:
A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags.
Method signatures and docstr... | 989d62b77ca70d239ae3cf99149c5215f6e6119e | <|skeleton|>
class GdKind:
"""A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags."""
def __init__(self, kind, title, kind_properties, contact_pro... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GdKind:
"""A base class for gd namespace kinds. This class contains common logic for all gd namespace kinds. For example, this class translates datastore (app id, kind, key) tuples to tag: URIs appropriate for use in <key> tags."""
def __init__(self, kind, title, kind_properties, contact_properties=[]):
... | the_stack_v2_python_sparse | Projects/GAE/src/google/appengine/api/datastore_entities.py | sethc23/BD_Scripts | train | 2 |
a8f42492704f03e605202324ac1ef9fc5dcbb7c9 | [
"if not cls.__values:\n cls.__values = [getattr(cls, v) for v in dir(cls) if not callable(getattr(cls, v)) and (not v.startswith('_'))]\nreturn cls.__values",
"if not cls.__choices:\n cls.__choices = [(getattr(cls, v), v) for v in dir(cls) if not callable(getattr(cls, v)) and (not v.startswith('_'))]\nretur... | <|body_start_0|>
if not cls.__values:
cls.__values = [getattr(cls, v) for v in dir(cls) if not callable(getattr(cls, v)) and (not v.startswith('_'))]
return cls.__values
<|end_body_0|>
<|body_start_1|>
if not cls.__choices:
cls.__choices = [(getattr(cls, v), v) for v in ... | A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the actual string value, which is prone to typos. | Enum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Enum:
"""A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the actual string value, which is prone to typ... | stack_v2_sparse_classes_36k_train_007738 | 1,271 | no_license | [
{
"docstring": "Returns a list of all the values, e.g.: ('choice1', 'choice2')",
"name": "values",
"signature": "def values(cls)"
},
{
"docstring": "Returns a list of choice tuples, e.g.: [('value1', 'Choice1'), ('value2', 'Choice2')]",
"name": "choices",
"signature": "def choices(cls)"
... | 2 | stack_v2_sparse_classes_30k_train_003415 | Implement the Python class `Enum` described below.
Class description:
A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the act... | Implement the Python class `Enum` described below.
Class description:
A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the act... | a3893e9f2bc1801d7e8557aef3f3e3f26811d398 | <|skeleton|>
class Enum:
"""A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the actual string value, which is prone to typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Enum:
"""A list of constants that can be defined in a declarative way. Example usage: class MyEnum(Enum): Choice1 = 'value1' Choice2 = 'value2' In this case, we can refer to the choices as MyEnum.Choice1 or MyEnum.Choice2, and don't have to reference the actual string value, which is prone to typos."""
d... | the_stack_v2_python_sparse | flask_common/enum.py | meilie389/flask-common | train | 0 |
e860f5df8048966c084ccd5ea49f35e384ec9baf | [
"super(TransformerRegressionModel, self).__init__()\nself.transformer = AutoModel.from_pretrained(transformer)\nself.tr_output_size = self.transformer.config.hidden_size\nself.num_labels = num_labels\nself.cls_token = cls_token\nself.dense = Linear(self.tr_output_size, self.tr_output_size)\nself.dropout = Dropout(p... | <|body_start_0|>
super(TransformerRegressionModel, self).__init__()
self.transformer = AutoModel.from_pretrained(transformer)
self.tr_output_size = self.transformer.config.hidden_size
self.num_labels = num_labels
self.cls_token = cls_token
self.dense = Linear(self.tr_outp... | TransformerRegressionModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerRegressionModel:
def __init__(self, transformer, dropout, num_labels, cls_token=0, activation='relu'):
"""Setup the modules in the model - a transformer, followed by a GRU for the CLS hidden states/taking the mean of all tokens, followed by Linear layers that outputs one numbe... | stack_v2_sparse_classes_36k_train_007739 | 3,122 | no_license | [
{
"docstring": "Setup the modules in the model - a transformer, followed by a GRU for the CLS hidden states/taking the mean of all tokens, followed by Linear layers that outputs one number, followed by softmax",
"name": "__init__",
"signature": "def __init__(self, transformer, dropout, num_labels, cls_t... | 3 | stack_v2_sparse_classes_30k_train_010883 | Implement the Python class `TransformerRegressionModel` described below.
Class description:
Implement the TransformerRegressionModel class.
Method signatures and docstrings:
- def __init__(self, transformer, dropout, num_labels, cls_token=0, activation='relu'): Setup the modules in the model - a transformer, followed... | Implement the Python class `TransformerRegressionModel` described below.
Class description:
Implement the TransformerRegressionModel class.
Method signatures and docstrings:
- def __init__(self, transformer, dropout, num_labels, cls_token=0, activation='relu'): Setup the modules in the model - a transformer, followed... | 460945baa4aa5a40354f9cd610d330cb73ca0625 | <|skeleton|>
class TransformerRegressionModel:
def __init__(self, transformer, dropout, num_labels, cls_token=0, activation='relu'):
"""Setup the modules in the model - a transformer, followed by a GRU for the CLS hidden states/taking the mean of all tokens, followed by Linear layers that outputs one numbe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerRegressionModel:
def __init__(self, transformer, dropout, num_labels, cls_token=0, activation='relu'):
"""Setup the modules in the model - a transformer, followed by a GRU for the CLS hidden states/taking the mean of all tokens, followed by Linear layers that outputs one number, followed by... | the_stack_v2_python_sparse | component/Duration/scripts/src/factslab/factslab/pytorch/transformer_regression.py | VincentWei2021/EventPlus | train | 0 | |
1ce293c027e0874e51eda846921d2fd265d647b2 | [
"self.n = 0\nself._head = Node(None)\nself._tail = Node(None)\nself._head.next = self._tail\nself._tail.prev = self._head",
"if 0 <= index < self.n:\n dummy = self._head.next\n while index > 0:\n dummy = dummy.next\n index -= 1\n return dummy.val\nreturn -1",
"old_first = self._head.next\... | <|body_start_0|>
self.n = 0
self._head = Node(None)
self._tail = Node(None)
self._head.next = self._tail
self._tail.prev = self._head
<|end_body_0|>
<|body_start_1|>
if 0 <= index < self.n:
dummy = self._head.next
while index > 0:
... | MyLinkedList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1."""
<|body_1|>
def addAtHead(self, val:... | stack_v2_sparse_classes_36k_train_007740 | 6,150 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get the value of the index-th node in the linked list. If the index is invalid, return -1.",
"name": "get",
"signature": "def get(self, index: int) -> int"
},... | 6 | null | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali... | Implement the Python class `MyLinkedList` described below.
Class description:
Implement the MyLinkedList class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def get(self, index: int) -> int: Get the value of the index-th node in the linked list. If the index is invali... | 551cd3b4616c16a6562eb7c577ce671b419f0616 | <|skeleton|>
class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def get(self, index: int) -> int:
"""Get the value of the index-th node in the linked list. If the index is invalid, return -1."""
<|body_1|>
def addAtHead(self, val:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyLinkedList:
def __init__(self):
"""Initialize your data structure here."""
self.n = 0
self._head = Node(None)
self._tail = Node(None)
self._head.next = self._tail
self._tail.prev = self._head
def get(self, index: int) -> int:
"""Get the value of t... | the_stack_v2_python_sparse | python/design/0707_Design_Linked_List.py | lizzzcai/leetcode | train | 1 | |
ad3e822a848fb09cb289c5f4a5df3359ac7a962e | [
"if self.request.method == 'GET':\n return (IsInPubliclyVisibleCommunity(),)\nelif self.request.method in ('POST', 'DELETE'):\n return (permissions.IsAuthenticated(), IsAbleToCreateAndDeleteAdvisory())\nreturn tuple()",
"queryset = self.get_queryset()\nqueryset = filter_queryset_permission(queryset, request... | <|body_start_0|>
if self.request.method == 'GET':
return (IsInPubliclyVisibleCommunity(),)
elif self.request.method in ('POST', 'DELETE'):
return (permissions.IsAuthenticated(), IsAbleToCreateAndDeleteAdvisory())
return tuple()
<|end_body_0|>
<|body_start_1|>
que... | Advisory view set | AdvisoryViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvisoryViewSet:
"""Advisory view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List advisories"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if self.request.method == 'GET':
... | stack_v2_sparse_classes_36k_train_007741 | 27,778 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "List advisories",
"name": "list",
"signature": "def list(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001700 | Implement the Python class `AdvisoryViewSet` described below.
Class description:
Advisory view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def list(self, request, *args, **kwargs): List advisories | Implement the Python class `AdvisoryViewSet` described below.
Class description:
Advisory view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def list(self, request, *args, **kwargs): List advisories
<|skeleton|>
class AdvisoryViewSet:
"""Advisory view set"""
def get_pe... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class AdvisoryViewSet:
"""Advisory view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def list(self, request, *args, **kwargs):
"""List advisories"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdvisoryViewSet:
"""Advisory view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method == 'GET':
return (IsInPubliclyVisibleCommunity(),)
elif self.request.method in ('POST', 'DELETE'):
return (permissions.IsAuthenticated(), IsAble... | the_stack_v2_python_sparse | membership/views.py | 810Teams/clubs-and-events-backend | train | 3 |
1576d3284bef4d840d5a03fd6ef83b2eb3600ec5 | [
"assert isinstance(gf, callflow.GraphFrame)\nassert 'group_path' in gf.df.columns\nentry_functions_map = self.module_entry_functions_map(gf.nxg)\nreveal_callsites = entry_functions_map[reveal_module]\npaths = self.callsitePathInformation(reveal_callsites)\nfor path in paths:\n component_edges = self.create_sourc... | <|body_start_0|>
assert isinstance(gf, callflow.GraphFrame)
assert 'group_path' in gf.df.columns
entry_functions_map = self.module_entry_functions_map(gf.nxg)
reveal_callsites = entry_functions_map[reveal_module]
paths = self.callsitePathInformation(reveal_callsites)
for ... | Split by entry function | SplitEntry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SplitEntry:
"""Split by entry function"""
def __init__(self, gf, reveal_module):
""":param gf: :param reveal_module:"""
<|body_0|>
def module_entry_functions_map(self, graph):
""":param graph: :return:"""
<|body_1|>
def create_source_targets(self, pa... | stack_v2_sparse_classes_36k_train_007742 | 5,782 | permissive | [
{
"docstring": ":param gf: :param reveal_module:",
"name": "__init__",
"signature": "def __init__(self, gf, reveal_module)"
},
{
"docstring": ":param graph: :return:",
"name": "module_entry_functions_map",
"signature": "def module_entry_functions_map(self, graph)"
},
{
"docstring... | 5 | stack_v2_sparse_classes_30k_train_005421 | Implement the Python class `SplitEntry` described below.
Class description:
Split by entry function
Method signatures and docstrings:
- def __init__(self, gf, reveal_module): :param gf: :param reveal_module:
- def module_entry_functions_map(self, graph): :param graph: :return:
- def create_source_targets(self, path):... | Implement the Python class `SplitEntry` described below.
Class description:
Split by entry function
Method signatures and docstrings:
- def __init__(self, gf, reveal_module): :param gf: :param reveal_module:
- def module_entry_functions_map(self, graph): :param graph: :return:
- def create_source_targets(self, path):... | 6bbdabe4b71be369e616e3136d7f0120531c9fc8 | <|skeleton|>
class SplitEntry:
"""Split by entry function"""
def __init__(self, gf, reveal_module):
""":param gf: :param reveal_module:"""
<|body_0|>
def module_entry_functions_map(self, graph):
""":param graph: :return:"""
<|body_1|>
def create_source_targets(self, pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SplitEntry:
"""Split by entry function"""
def __init__(self, gf, reveal_module):
""":param gf: :param reveal_module:"""
assert isinstance(gf, callflow.GraphFrame)
assert 'group_path' in gf.df.columns
entry_functions_map = self.module_entry_functions_map(gf.nxg)
rev... | the_stack_v2_python_sparse | callflow/operations/split_entry.py | LLNL/CallFlow | train | 32 |
fa6d606cd33e967df12b90335c47859ac2393bdb | [
"if isinstance(v, str):\n return v\nreturn PostgresDsn.build(scheme='postgresql', user=values.get('POSTGRES_USER'), password=values.get('POSTGRES_PASSWORD'), host=values.get('POSTGRES_SERVER'), port=values.get('POSTGRES_PORT'), path=f\"/{values.get('POSTGRES_DB') or ''}\")",
"env = os.getenv('PYTHON_ENV', 'dev... | <|body_start_0|>
if isinstance(v, str):
return v
return PostgresDsn.build(scheme='postgresql', user=values.get('POSTGRES_USER'), password=values.get('POSTGRES_PASSWORD'), host=values.get('POSTGRES_SERVER'), port=values.get('POSTGRES_PORT'), path=f"/{values.get('POSTGRES_DB') or ''}")
<|end_b... | Global Settings. | Settings | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url conn... | stack_v2_sparse_classes_36k_train_007743 | 2,572 | no_license | [
{
"docstring": "PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url connection.",
"name": "assemble_db_connection",
"signature": "def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[s... | 2 | stack_v2_sparse_classes_30k_train_009184 | Implement the Python class `Settings` described below.
Class description:
Global Settings.
Method signatures and docstrings:
- def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]: PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others ... | Implement the Python class `Settings` described below.
Class description:
Global Settings.
Method signatures and docstrings:
- def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]: PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others ... | 8082d3ce9c999c79228a36aa160b4171140440cb | <|skeleton|>
class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url conn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Settings:
"""Global Settings."""
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Union[str, PostgresDsn]:
"""PostgreSQL Url. Args: v (Optional[str]): Value received. values (Dict[str, Any]): Others values. Returns: Union[str, PostgresDsn]: Return url connection."""
... | the_stack_v2_python_sparse | app/config.py | douglaspands/api-server-py | train | 2 |
fedbe2bccf489f778cba98d6ebc58fa8915e9ab3 | [
"if not points:\n return 0\npoints.sort()\nres = 1\nl, r = points[0]\nfor i in range(1, len(points)):\n ll, rr = points[i]\n if ll > r:\n res += 1\n r = rr\n else:\n r = min(r, rr)\nreturn res",
"if not points:\n return 0\npoints.sort(key=lambda x: x[1])\nres = 1\nl, r = points... | <|body_start_0|>
if not points:
return 0
points.sort()
res = 1
l, r = points[0]
for i in range(1, len(points)):
ll, rr = points[i]
if ll > r:
res += 1
r = rr
else:
r = min(r, rr)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
"""思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:"""
<|body_0|>
def findMinArrowShots2(self, po... | stack_v2_sparse_classes_36k_train_007744 | 2,714 | no_license | [
{
"docstring": "思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points: List[List[int]]) -> int"
},
{
"docstring": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points: List[List[int]]) -> int: 思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points: List[List[int]]) -> int: 思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
"""思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:"""
<|body_0|>
def findMinArrowShots2(self, po... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
"""思路:贪心算法 1. 按照起点从小到大排序,如果新的区间的起点ll小于当前区间的终点r,就缩小区间r = min(r, rr),令r等于当前区间和新区间终点的最小值 2. 如果新区间的起点ll大于当前区间的终点,则需要新的箭,res+1,同时设置新的区间的终点r @param points: @return:"""
if not points:
return 0
points.sort()
... | the_stack_v2_python_sparse | LeetCode/贪心算法/452. 用最少数量的箭引爆气球.py | yiming1012/MyLeetCode | train | 2 | |
0cf1cb9a338cd5383b6517e138ec2ae033a02419 | [
"cube = set_up_variable_cube(278.0 * np.ones((4, 3, 3), dtype=np.float32))\nplugin = WeightAndBlend('realization', 'linear', y0val=1, ynval=1)\nweights = plugin._calculate_blending_weights(cube)\nself.assertIsInstance(weights, iris.cube.Cube)\nweights_dims = [coord.name() for coord in weights.coords(dim_coords=True... | <|body_start_0|>
cube = set_up_variable_cube(278.0 * np.ones((4, 3, 3), dtype=np.float32))
plugin = WeightAndBlend('realization', 'linear', y0val=1, ynval=1)
weights = plugin._calculate_blending_weights(cube)
self.assertIsInstance(weights, iris.cube.Cube)
weights_dims = [coord.na... | Test the _calculate_blending_weights method | Test__calculate_blending_weights | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__calculate_blending_weights:
"""Test the _calculate_blending_weights method"""
def test_default_linear(self):
"""Test linear weighting over realizations"""
<|body_0|>
def test_default_nonlinear(self):
"""Test non-linear weighting over forecast reference time... | stack_v2_sparse_classes_36k_train_007745 | 30,096 | permissive | [
{
"docstring": "Test linear weighting over realizations",
"name": "test_default_linear",
"signature": "def test_default_linear(self)"
},
{
"docstring": "Test non-linear weighting over forecast reference time, where the earlier cycle has a higher weighting",
"name": "test_default_nonlinear",
... | 4 | null | Implement the Python class `Test__calculate_blending_weights` described below.
Class description:
Test the _calculate_blending_weights method
Method signatures and docstrings:
- def test_default_linear(self): Test linear weighting over realizations
- def test_default_nonlinear(self): Test non-linear weighting over fo... | Implement the Python class `Test__calculate_blending_weights` described below.
Class description:
Test the _calculate_blending_weights method
Method signatures and docstrings:
- def test_default_linear(self): Test linear weighting over realizations
- def test_default_nonlinear(self): Test non-linear weighting over fo... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__calculate_blending_weights:
"""Test the _calculate_blending_weights method"""
def test_default_linear(self):
"""Test linear weighting over realizations"""
<|body_0|>
def test_default_nonlinear(self):
"""Test non-linear weighting over forecast reference time... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__calculate_blending_weights:
"""Test the _calculate_blending_weights method"""
def test_default_linear(self):
"""Test linear weighting over realizations"""
cube = set_up_variable_cube(278.0 * np.ones((4, 3, 3), dtype=np.float32))
plugin = WeightAndBlend('realization', 'linear... | the_stack_v2_python_sparse | improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py | metoppv/improver | train | 101 |
a42013644efa98225bd0fcc117f367acbd409d27 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(username=username, email=ema... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name)
user.set_password(password)
user.save(using=self._db)
return user
<|... | MyUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
<|body_0|>
def create_superuser(self, username, email, password):
... | stack_v2_sparse_classes_36k_train_007746 | 3,190 | no_license | [
{
"docstring": "Creates and saves a User with the given email, first name, last name and password.",
"name": "create_user",
"signature": "def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None)"
},
{
"docstring": "Creates and saves a superuser with the gi... | 2 | stack_v2_sparse_classes_30k_train_020025 | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, first name, last name a... | Implement the Python class `MyUserManager` described below.
Class description:
Implement the MyUserManager class.
Method signatures and docstrings:
- def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None): Creates and saves a User with the given email, first name, last name a... | d73d61e46b96561521a35777be363d2276617fc0 | <|skeleton|>
class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
<|body_0|>
def create_superuser(self, username, email, password):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyUserManager:
def create_user(self, username=None, email=None, first_name=None, last_name=None, password=None):
"""Creates and saves a User with the given email, first name, last name and password."""
if not email:
raise ValueError('Users must have an email address')
user ... | the_stack_v2_python_sparse | src/accounts/models.py | rcmiskin10/university-social-network | train | 0 | |
e0e51d08ab022c7939580c37b0a1c132d5988a7f | [
"if column_filter == 'All':\n pass\nelif column_filter:\n query = query.filter(self.get_filter(trans, user, column_filter))\nreturn query",
"if isinstance(column_filter, string_types):\n return self.get_single_filter(user, column_filter)\nelif isinstance(column_filter, list):\n clause_list = []\n f... | <|body_start_0|>
if column_filter == 'All':
pass
elif column_filter:
query = query.filter(self.get_filter(trans, user, column_filter))
return query
<|end_body_0|>
<|body_start_1|>
if isinstance(column_filter, string_types):
return self.get_single_filt... | Generic column that employs freetext and, hence, supports freetext, case-independent filtering. | TextColumn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextColumn:
"""Generic column that employs freetext and, hence, supports freetext, case-independent filtering."""
def filter(self, trans, user, query, column_filter):
"""Modify query to filter using free text, case independence."""
<|body_0|>
def get_filter(self, trans, ... | stack_v2_sparse_classes_36k_train_007747 | 38,546 | permissive | [
{
"docstring": "Modify query to filter using free text, case independence.",
"name": "filter",
"signature": "def filter(self, trans, user, query, column_filter)"
},
{
"docstring": "Returns a SQLAlchemy criterion derived from column_filter.",
"name": "get_filter",
"signature": "def get_fi... | 4 | null | Implement the Python class `TextColumn` described below.
Class description:
Generic column that employs freetext and, hence, supports freetext, case-independent filtering.
Method signatures and docstrings:
- def filter(self, trans, user, query, column_filter): Modify query to filter using free text, case independence... | Implement the Python class `TextColumn` described below.
Class description:
Generic column that employs freetext and, hence, supports freetext, case-independent filtering.
Method signatures and docstrings:
- def filter(self, trans, user, query, column_filter): Modify query to filter using free text, case independence... | e9edd90c95f0d12da19f45d4d11b374f87149550 | <|skeleton|>
class TextColumn:
"""Generic column that employs freetext and, hence, supports freetext, case-independent filtering."""
def filter(self, trans, user, query, column_filter):
"""Modify query to filter using free text, case independence."""
<|body_0|>
def get_filter(self, trans, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextColumn:
"""Generic column that employs freetext and, hence, supports freetext, case-independent filtering."""
def filter(self, trans, user, query, column_filter):
"""Modify query to filter using free text, case independence."""
if column_filter == 'All':
pass
elif ... | the_stack_v2_python_sparse | galaxy/coralsnp_reports/lib/galaxy/webapps/coralsnp_reports/framework/grids.py | gregvonkuster/galaxy_tools | train | 4 |
bea53f239bec18e6712a642e62da2a2be538149a | [
"if self.sprite:\n self.sprite._focus_exit()\npygame.sprite.GroupSingle.add(self, *sprites)\nself.sprite._focus_enter(focus)",
"if self.sprite:\n self.sprite._focus_exit()\npygame.sprite.GroupSingle.empty(self)"
] | <|body_start_0|>
if self.sprite:
self.sprite._focus_exit()
pygame.sprite.GroupSingle.add(self, *sprites)
self.sprite._focus_enter(focus)
<|end_body_0|>
<|body_start_1|>
if self.sprite:
self.sprite._focus_exit()
pygame.sprite.GroupSingle.empty(self)
<|end_... | Contains currently focused widget. | Focus | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Focus:
"""Contains currently focused widget."""
def add(self, focus=0, *sprites):
"""Extend add to call _focus_exit and _focus_enter methods."""
<|body_0|>
def empty(self):
"""Extend empty to call _focus_exit method."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_007748 | 13,593 | permissive | [
{
"docstring": "Extend add to call _focus_exit and _focus_enter methods.",
"name": "add",
"signature": "def add(self, focus=0, *sprites)"
},
{
"docstring": "Extend empty to call _focus_exit method.",
"name": "empty",
"signature": "def empty(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014416 | Implement the Python class `Focus` described below.
Class description:
Contains currently focused widget.
Method signatures and docstrings:
- def add(self, focus=0, *sprites): Extend add to call _focus_exit and _focus_enter methods.
- def empty(self): Extend empty to call _focus_exit method. | Implement the Python class `Focus` described below.
Class description:
Contains currently focused widget.
Method signatures and docstrings:
- def add(self, focus=0, *sprites): Extend add to call _focus_exit and _focus_enter methods.
- def empty(self): Extend empty to call _focus_exit method.
<|skeleton|>
class Focus... | 95cb53b664f312e0830f010c0c96be94d4a4db90 | <|skeleton|>
class Focus:
"""Contains currently focused widget."""
def add(self, focus=0, *sprites):
"""Extend add to call _focus_exit and _focus_enter methods."""
<|body_0|>
def empty(self):
"""Extend empty to call _focus_exit method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Focus:
"""Contains currently focused widget."""
def add(self, focus=0, *sprites):
"""Extend add to call _focus_exit and _focus_enter methods."""
if self.sprite:
self.sprite._focus_exit()
pygame.sprite.GroupSingle.add(self, *sprites)
self.sprite._focus_enter(foc... | the_stack_v2_python_sparse | pygame/GUI- widgets-SGC/sgc3/widgets/_locals.py | furas/python-examples | train | 176 |
2cef9d989626e270eba5443a89a1c16e79bca357 | [
"url = host + '/api/accusation/create'\ndata = {'object_type': object_type, 'object_id': object_id, 'memo': memo, 'reported': reported, 'category_id': category_id}\nr = requests.post(url=url, headers=header, data=data).json()\nout_format('添加举报:', r)\nreturn r",
"url = host + '/api/accusation/types/'\nr = requests... | <|body_start_0|>
url = host + '/api/accusation/create'
data = {'object_type': object_type, 'object_id': object_id, 'memo': memo, 'reported': reported, 'category_id': category_id}
r = requests.post(url=url, headers=header, data=data).json()
out_format('添加举报:', r)
return r
<|end_bo... | 定义一个举报的测试类 | Accusation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Accusation:
"""定义一个举报的测试类"""
def accusation_add(self):
"""添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型"""
<|body_0|>
def accusation_type(self):
"""举报类型 :param:token:用户授权token... | stack_v2_sparse_classes_36k_train_007749 | 3,606 | no_license | [
{
"docstring": "添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型",
"name": "accusation_add",
"signature": "def accusation_add(self)"
},
{
"docstring": "举报类型 :param:token:用户授权token",
"name": "accusation_type"... | 4 | null | Implement the Python class `Accusation` described below.
Class description:
定义一个举报的测试类
Method signatures and docstrings:
- def accusation_add(self): 添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型
- def accusation_type(self): 举报类型 :... | Implement the Python class `Accusation` described below.
Class description:
定义一个举报的测试类
Method signatures and docstrings:
- def accusation_add(self): 添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型
- def accusation_type(self): 举报类型 :... | 0ebaae335de2f1633e31c4fc3f60e556220a8bfb | <|skeleton|>
class Accusation:
"""定义一个举报的测试类"""
def accusation_add(self):
"""添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型"""
<|body_0|>
def accusation_type(self):
"""举报类型 :param:token:用户授权token... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Accusation:
"""定义一个举报的测试类"""
def accusation_add(self):
"""添加举报 :param:token:用户授权token :param:object_type:对象类型 :param:object_id:对象号 :param:memo:备注 :param:reported:被举报用户 :param:category_id:举报类型"""
url = host + '/api/accusation/create'
data = {'object_type': object_type, 'object_id':... | the_stack_v2_python_sparse | Atle/interface/framework/base/Accusation.py | shiqi0128/My_scripts | train | 0 |
91926f8d33018011014d4f998f1dad7f45bfdd16 | [
"super(FeatureExtractor, self).__init__()\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.num_embeddings, self.embedding_dim = pretrained_mtx.shape\nself.token2idx_dict = token2idx_dict\nself.embedding = nn.Embedding.from_pretrained(torch.from_numpy(pretrained_mtx).float(), freeze=freeze_embeddi... | <|body_start_0|>
super(FeatureExtractor, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.num_embeddings, self.embedding_dim = pretrained_mtx.shape
self.token2idx_dict = token2idx_dict
self.embedding = nn.Embedding.from_pretrained(torch.fr... | Feature extracter for each node in the graph. | FeatureExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExtractor:
"""Feature extracter for each node in the graph."""
def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True):
"""Args: -token2idx_dict: token_to_index dictionary. -pretrained_mtx: pretrained word representation matrix. -hi... | stack_v2_sparse_classes_36k_train_007750 | 4,830 | no_license | [
{
"docstring": "Args: -token2idx_dict: token_to_index dictionary. -pretrained_mtx: pretrained word representation matrix. -hidden_size: size of hidden state of LSTM, which is also the dim for each graph node. -num_layers: the number of LSTM layers for each step. -freeze_embedding: whether to continue to train t... | 2 | stack_v2_sparse_classes_30k_train_006667 | Implement the Python class `FeatureExtractor` described below.
Class description:
Feature extracter for each node in the graph.
Method signatures and docstrings:
- def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True): Args: -token2idx_dict: token_to_index dictionary. -p... | Implement the Python class `FeatureExtractor` described below.
Class description:
Feature extracter for each node in the graph.
Method signatures and docstrings:
- def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True): Args: -token2idx_dict: token_to_index dictionary. -p... | bcef404ad1976706fffe08ea066f8fd1c2405f3b | <|skeleton|>
class FeatureExtractor:
"""Feature extracter for each node in the graph."""
def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True):
"""Args: -token2idx_dict: token_to_index dictionary. -pretrained_mtx: pretrained word representation matrix. -hi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureExtractor:
"""Feature extracter for each node in the graph."""
def __init__(self, token2idx_dict, pretrained_mtx, hidden_size, num_layers=1, freeze_embedding=True):
"""Args: -token2idx_dict: token_to_index dictionary. -pretrained_mtx: pretrained word representation matrix. -hidden_size: si... | the_stack_v2_python_sparse | models/feature_extractor.py | wll199566/KG2 | train | 5 |
20239d74b7bf130ec089b9d12ba6bea5ed1c85a9 | [
"if '/' not in value:\n if ';' in value:\n raise errors.DeserializationError('Unexpected semi-colon')\n return cls.PREFIX + value\nreturn value",
"if ';' not in value:\n assert value.startswith(cls.PREFIX)\n return value[len(cls.PREFIX):]\nreturn value"
] | <|body_start_0|>
if '/' not in value:
if ';' in value:
raise errors.DeserializationError('Unexpected semi-colon')
return cls.PREFIX + value
return value
<|end_body_0|>
<|body_start_1|>
if ';' not in value:
assert value.startswith(cls.PREFIX)
... | MediaType field encoder/decoder. | MediaType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MediaType:
"""MediaType field encoder/decoder."""
def decode(cls, value):
"""Decoder."""
<|body_0|>
def encode(cls, value):
"""Encoder."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if '/' not in value:
if ';' in value:
... | stack_v2_sparse_classes_36k_train_007751 | 14,260 | permissive | [
{
"docstring": "Decoder.",
"name": "decode",
"signature": "def decode(cls, value)"
},
{
"docstring": "Encoder.",
"name": "encode",
"signature": "def encode(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008961 | Implement the Python class `MediaType` described below.
Class description:
MediaType field encoder/decoder.
Method signatures and docstrings:
- def decode(cls, value): Decoder.
- def encode(cls, value): Encoder. | Implement the Python class `MediaType` described below.
Class description:
MediaType field encoder/decoder.
Method signatures and docstrings:
- def decode(cls, value): Decoder.
- def encode(cls, value): Encoder.
<|skeleton|>
class MediaType:
"""MediaType field encoder/decoder."""
def decode(cls, value):
... | 4082346ef8d5e6a8365b05752be41186840dc868 | <|skeleton|>
class MediaType:
"""MediaType field encoder/decoder."""
def decode(cls, value):
"""Decoder."""
<|body_0|>
def encode(cls, value):
"""Encoder."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MediaType:
"""MediaType field encoder/decoder."""
def decode(cls, value):
"""Decoder."""
if '/' not in value:
if ';' in value:
raise errors.DeserializationError('Unexpected semi-colon')
return cls.PREFIX + value
return value
def encode(... | the_stack_v2_python_sparse | desktop/core/ext-py/josepy-1.1.0/src/josepy/jws.py | oyorooms/hue | train | 4 |
447406ea253c0a274e249a50a4d6e0d0cd354b44 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.brand = brand\nself.voltage = voltage",
"output_dict = Inventory.return_as_dictionary(self)\noutput_dict['brand'] = self.brand\noutput_dict['voltage'] = self.voltage\nreturn output_dict"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.brand = brand
self.voltage = voltage
<|end_body_0|>
<|body_start_1|>
output_dict = Inventory.return_as_dictionary(self)
output_dict['brand'] = self.brand
output_dict['vo... | An object representing Electric Appliances | ElectricAppliances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElectricAppliances:
"""An object representing Electric Appliances"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Initializes the Electric Appliance class object. :self: The Class :product_code: The product code of the appliance :descr... | stack_v2_sparse_classes_36k_train_007752 | 1,550 | no_license | [
{
"docstring": "Initializes the Electric Appliance class object. :self: The Class :product_code: The product code of the appliance :description: The appliance description :market_price: The market cost of the appliance :rental_price: The rental price of the appliance :brand: The brand name of the appliance :vol... | 2 | null | Implement the Python class `ElectricAppliances` described below.
Class description:
An object representing Electric Appliances
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Initializes the Electric Appliance class object. :self: The Clas... | Implement the Python class `ElectricAppliances` described below.
Class description:
An object representing Electric Appliances
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, brand, voltage): Initializes the Electric Appliance class object. :self: The Clas... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class ElectricAppliances:
"""An object representing Electric Appliances"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Initializes the Electric Appliance class object. :self: The Class :product_code: The product code of the appliance :descr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElectricAppliances:
"""An object representing Electric Appliances"""
def __init__(self, product_code, description, market_price, rental_price, brand, voltage):
"""Initializes the Electric Appliance class object. :self: The Class :product_code: The product code of the appliance :description: The a... | the_stack_v2_python_sparse | students/anthony_mckeever/lesson_1/assignment_1/inventory_management/electric_appliances_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
3cba2bf9ffce1867df66c8754f9632e64a29af04 | [
"time_elements_structure = self._GetValueFromStructure(structure, 'date_time')\nhttp_request = self._GetValueFromStructure(structure, 'http_request')\nif http_request:\n http_request = ' '.join(http_request)\nremote_name = self._GetValueFromStructure(structure, 'remote_name')\nif remote_name == '-':\n remote_... | <|body_start_0|>
time_elements_structure = self._GetValueFromStructure(structure, 'date_time')
http_request = self._GetValueFromStructure(structure, 'http_request')
if http_request:
http_request = ' '.join(http_request)
remote_name = self._GetValueFromStructure(structure, 're... | Text parser plugin for Apache access log (access.log) files. | ApacheAccessLogTextPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApacheAccessLogTextPlugin:
"""Text parser plugin for Apache access log (access.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, ... | stack_v2_sparse_classes_36k_train_007753 | 10,452 | permissive | [
{
"docstring": "Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. key (str): name of the parsed structure. structure (pyparsing.ParseResults): tokens from a parsed log line. Raises: ParseError: if the stru... | 3 | stack_v2_sparse_classes_30k_test_000655 | Implement the Python class `ApacheAccessLogTextPlugin` described below.
Class description:
Text parser plugin for Apache access log (access.log) files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): med... | Implement the Python class `ApacheAccessLogTextPlugin` described below.
Class description:
Text parser plugin for Apache access log (access.log) files.
Method signatures and docstrings:
- def _ParseRecord(self, parser_mediator, key, structure): Parses a pyparsing structure. Args: parser_mediator (ParserMediator): med... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class ApacheAccessLogTextPlugin:
"""Text parser plugin for Apache access log (access.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApacheAccessLogTextPlugin:
"""Text parser plugin for Apache access log (access.log) files."""
def _ParseRecord(self, parser_mediator, key, structure):
"""Parses a pyparsing structure. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as stora... | the_stack_v2_python_sparse | plaso/parsers/text_plugins/apache_access.py | log2timeline/plaso | train | 1,506 |
3fd3b852acbe5ee3037505e920100f84172b2840 | [
"super(PostnormDecoderLayer, self).__init__(name=name)\nwith tf.compat.v1.variable_scope(name):\n attention_head_size = hidden_size // num_attention_heads\n with tf.compat.v1.variable_scope('attention'):\n self.self_attn_layer = attention.MultiHeadedAttentionLayer('original_full', max_seq_length=max_se... | <|body_start_0|>
super(PostnormDecoderLayer, self).__init__(name=name)
with tf.compat.v1.variable_scope(name):
attention_head_size = hidden_size // num_attention_heads
with tf.compat.v1.variable_scope('attention'):
self.self_attn_layer = attention.MultiHeadedAtten... | Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention. | PostnormDecoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostnormDecoderLayer:
"""Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.1,... | stack_v2_sparse_classes_36k_train_007754 | 26,836 | permissive | [
{
"docstring": "Constructor of a decoder layer of a transformer in BERT style. Args: hidden_size: (optional) int. Size of hidden dimension. intermediate_size: (optional) int. Size of intermediate dimension. intermediate_act_fn: optional) Activation function for intermediate layer. attention_probs_dropout_prob: ... | 2 | stack_v2_sparse_classes_30k_train_014524 | Implement the Python class `PostnormDecoderLayer` described below.
Class description:
Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention.
Method signatures and docstrings:
- def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=ut... | Implement the Python class `PostnormDecoderLayer` described below.
Class description:
Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention.
Method signatures and docstrings:
- def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=ut... | dc64e0aa3661e2f135e02794b979c2f6af4f3c9a | <|skeleton|>
class PostnormDecoderLayer:
"""Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.1,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostnormDecoderLayer:
"""Decoder layer of a transformer in BERT style. The layer_norm is taken before self-attention."""
def __init__(self, max_seq_length=4096, hidden_size=768, intermediate_size=3072, intermediate_act_fn=utils.gelu, attention_probs_dropout_prob=0.0, hidden_dropout_prob=0.1, initializer_... | the_stack_v2_python_sparse | pretrain/kobigbird/decoder.py | monologg/KoBigBird | train | 208 |
5e44e4bb4f408e9ac67762d7583adbb6c023bf31 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DomainDnsSrvRecord()",
"from .domain_dns_record import DomainDnsRecord\nfrom .domain_dns_record import DomainDnsRecord\nfields: Dict[str, Callable[[Any], None]] = {'nameTarget': lambda n: setattr(self, 'name_target', n.get_str_value())... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DomainDnsSrvRecord()
<|end_body_0|>
<|body_start_1|>
from .domain_dns_record import DomainDnsRecord
from .domain_dns_record import DomainDnsRecord
fields: Dict[str, Callable[[Any... | DomainDnsSrvRecord | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainDnsSrvRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DomainDnsSrvRecord:
"""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 obje... | stack_v2_sparse_classes_36k_train_007755 | 3,417 | 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: DomainDnsSrvRecord",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_018900 | Implement the Python class `DomainDnsSrvRecord` described below.
Class description:
Implement the DomainDnsSrvRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DomainDnsSrvRecord: Creates a new instance of the appropriate class based on disc... | Implement the Python class `DomainDnsSrvRecord` described below.
Class description:
Implement the DomainDnsSrvRecord class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DomainDnsSrvRecord: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DomainDnsSrvRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DomainDnsSrvRecord:
"""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 obje... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DomainDnsSrvRecord:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DomainDnsSrvRecord:
"""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: Do... | the_stack_v2_python_sparse | msgraph/generated/models/domain_dns_srv_record.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
687c2a9ce6d6e85c7ec828cfd17ddaee1e8c5e94 | [
"req_dict = api.payload\ndata_id = req_dict.get('data_id')\nmodel_url = req_dict.get('model_url')\ntry:\n data = Data.query.filter_by(id=data_id).first()\nexcept Exception as e:\n logging.error(e)\n return abort(500, 'Database error.')\nfilepath = Config.UPLOADED_DATA_DEST + data.data_info[1:-1]\ntask = an... | <|body_start_0|>
req_dict = api.payload
data_id = req_dict.get('data_id')
model_url = req_dict.get('model_url')
try:
data = Data.query.filter_by(id=data_id).first()
except Exception as e:
logging.error(e)
return abort(500, 'Database error.')
... | Commit the task of project and get the status of it | ProjectTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectTask:
"""Commit the task of project and get the status of it"""
def post(self, id):
"""Commit the task"""
<|body_0|>
def get(self, id):
"""Fetch the status of task"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
req_dict = api.payload
... | stack_v2_sparse_classes_36k_train_007756 | 5,767 | permissive | [
{
"docstring": "Commit the task",
"name": "post",
"signature": "def post(self, id)"
},
{
"docstring": "Fetch the status of task",
"name": "get",
"signature": "def get(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010138 | Implement the Python class `ProjectTask` described below.
Class description:
Commit the task of project and get the status of it
Method signatures and docstrings:
- def post(self, id): Commit the task
- def get(self, id): Fetch the status of task | Implement the Python class `ProjectTask` described below.
Class description:
Commit the task of project and get the status of it
Method signatures and docstrings:
- def post(self, id): Commit the task
- def get(self, id): Fetch the status of task
<|skeleton|>
class ProjectTask:
"""Commit the task of project and ... | 953c2916c38906b0941c015136f80b2e64dd94f3 | <|skeleton|>
class ProjectTask:
"""Commit the task of project and get the status of it"""
def post(self, id):
"""Commit the task"""
<|body_0|>
def get(self, id):
"""Fetch the status of task"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectTask:
"""Commit the task of project and get the status of it"""
def post(self, id):
"""Commit the task"""
req_dict = api.payload
data_id = req_dict.get('data_id')
model_url = req_dict.get('model_url')
try:
data = Data.query.filter_by(id=data_id).... | the_stack_v2_python_sparse | kgeditor/api_1_0/project.py | LaiXinyi823/KGEditor | train | 0 |
662203d75d6da0584a5876c07637177f7b35232e | [
"if not preorder or not inorder:\n return None\nroot = TreeNode(preorder[0])\nindex = inorder.index(preorder[0])\nroot.left = self.buildTree(preorder[1:index + 1], inorder[:index])\nroot.right = self.buildTree(preorder[index + 1:], inorder[index + 1:])\nreturn root",
"if inorder:\n ind = inorder.index(preor... | <|body_start_0|>
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1:index + 1], inorder[:index])
root.right = self.buildTree(preorder[index + 1:], inorder[index + 1:])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
"""https://discuss.leetcode.com/topic/21287/python-short-recursive-solution :param preorder... | stack_v2_sparse_classes_36k_train_007757 | 2,553 | no_license | [
{
"docstring": ":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, preorder, inorder)"
},
{
"docstring": "https://discuss.leetcode.com/topic/21287/python-short-recursive-solution :param preorder: :param inorder:",
"nam... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree2(self, preorder, inorder): https://discuss.leetcode.co... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, preorder, inorder): :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode
- def buildTree2(self, preorder, inorder): https://discuss.leetcode.co... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
<|body_0|>
def buildTree2(self, preorder, inorder):
"""https://discuss.leetcode.com/topic/21287/python-short-recursive-solution :param preorder... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, preorder, inorder):
""":type preorder: List[int] :type inorder: List[int] :rtype: TreeNode"""
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
index = inorder.index(preorder[0])
root.left = self.buildTree... | the_stack_v2_python_sparse | 105. Construct Binary Tree from Preorder and Inorder Traversal.py | zhangpengGenedock/leetcode_python | train | 1 | |
3e1ab187a213428d58c8204fc6d1b67e0d8e851a | [
"self.app_uid = app_uid\nself.app_version = app_version\nself.creation_uid = creation_uid\nself.deployment_parameters = deployment_parameters\nself.description = description\nself.settings = settings",
"if dictionary is None:\n return None\napp_uid = dictionary.get('appUid')\napp_version = dictionary.get('appV... | <|body_start_0|>
self.app_uid = app_uid
self.app_version = app_version
self.creation_uid = creation_uid
self.deployment_parameters = deployment_parameters
self.description = description
self.settings = settings
<|end_body_0|>
<|body_start_1|>
if dictionary is Non... | Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identifier generated by the client to let the backend distinguish retries of the creation o... | LaunchAppInstance | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LaunchAppInstance:
"""Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identifier generated by the client to let the ... | stack_v2_sparse_classes_36k_train_007758 | 3,007 | permissive | [
{
"docstring": "Constructor for the LaunchAppInstance class",
"name": "__init__",
"signature": "def __init__(self, app_uid=None, app_version=None, creation_uid=None, deployment_parameters=None, description=None, settings=None)"
},
{
"docstring": "Creates an instance of this model from a dictiona... | 2 | stack_v2_sparse_classes_30k_train_004145 | Implement the Python class `LaunchAppInstance` described below.
Class description:
Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identif... | Implement the Python class `LaunchAppInstance` described below.
Class description:
Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identif... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class LaunchAppInstance:
"""Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identifier generated by the client to let the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LaunchAppInstance:
"""Implementation of the 'LaunchAppInstance' model. Specifies app instance parameters. Attributes: app_uid (long|int): Specifies the app Id. app_version (long|int): Specifies the app version. creation_uid (string): Specifies unique identifier generated by the client to let the backend disti... | the_stack_v2_python_sparse | cohesity_management_sdk/models/launch_app_instance.py | cohesity/management-sdk-python | train | 24 |
06af3706dd607e263ea8dc08687ab7042e83da08 | [
"filename = os.path.join(os.path.dirname(__file__), 'data', first_names_file)\nwith open(filename, 'r') as fh:\n self.first_names = [l.strip() for l in fh.readlines()]",
"for first_name in self.first_names:\n if name == first_name:\n return True\nreturn False",
"count = 0\nfor name in name_list:\n ... | <|body_start_0|>
filename = os.path.join(os.path.dirname(__file__), 'data', first_names_file)
with open(filename, 'r') as fh:
self.first_names = [l.strip() for l in fh.readlines()]
<|end_body_0|>
<|body_start_1|>
for first_name in self.first_names:
if name == first_name:... | SlowClass | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlowClass:
def __init__(self, first_names_file):
"""Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this program"""
<|body_0|>
def known_name(self, name):
"""Determine whether a name exist... | stack_v2_sparse_classes_36k_train_007759 | 2,312 | no_license | [
{
"docstring": "Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this program",
"name": "__init__",
"signature": "def __init__(self, first_names_file)"
},
{
"docstring": "Determine whether a name exists in the list of ... | 3 | stack_v2_sparse_classes_30k_train_021162 | Implement the Python class `SlowClass` described below.
Class description:
Implement the SlowClass class.
Method signatures and docstrings:
- def __init__(self, first_names_file): Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this progra... | Implement the Python class `SlowClass` described below.
Class description:
Implement the SlowClass class.
Method signatures and docstrings:
- def __init__(self, first_names_file): Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this progra... | 2722d9f1e0785b36ac00ccc576c2e6da8d6280cb | <|skeleton|>
class SlowClass:
def __init__(self, first_names_file):
"""Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this program"""
<|body_0|>
def known_name(self, name):
"""Determine whether a name exist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlowClass:
def __init__(self, first_names_file):
"""Initialize a `SlowClass` Args: first_names_file (:obj:`str`): the name of a file in the `data` subdir of the directory storing this program"""
filename = os.path.join(os.path.dirname(__file__), 'data', first_names_file)
with open(file... | the_stack_v2_python_sparse | assignments/BMI2002_SP_20/assignment_7/slow_code.py | kxu68/BMSE | train | 0 | |
fdcf715eacac445ab7cfbdd36c65211457703327 | [
"if fast:\n return self.sameSumArrayFast(array1, array2)\n_sum_array1 = sum(array1)\n_sum_array2 = sum(array2)\nfor i in array1:\n for j in array2:\n if _sum_array1 - i + j == _sum_array2 - j + i:\n return (i, j)\nreturn -1",
"_sum_array1 = sum(array1)\n_sum_array2 = sum(array2)\ntarget = ... | <|body_start_0|>
if fast:
return self.sameSumArrayFast(array1, array2)
_sum_array1 = sum(array1)
_sum_array2 = sum(array2)
for i in array1:
for j in array2:
if _sum_array1 - i + j == _sum_array2 - j + i:
return (i, j)
re... | Class which implements algorithm | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Class which implements algorithm"""
def sameSumArray(self, array1, array2, fast=True):
"""Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)"""
<|body_0|>
def sameSumArrayFast(self, array1, array2):
"""Time co... | stack_v2_sparse_classes_36k_train_007760 | 1,989 | no_license | [
{
"docstring": "Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)",
"name": "sameSumArray",
"signature": "def sameSumArray(self, array1, array2, fast=True)"
},
{
"docstring": "Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n) - finding pair O(3... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Class which implements algorithm
Method signatures and docstrings:
- def sameSumArray(self, array1, array2, fast=True): Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)
- def sameSumArrayFast(self, arr... | Implement the Python class `Solution` described below.
Class description:
Class which implements algorithm
Method signatures and docstrings:
- def sameSumArray(self, array1, array2, fast=True): Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)
- def sameSumArrayFast(self, arr... | 546cbce06fcd4bc34e16d42b5d5eb68fb25e16a9 | <|skeleton|>
class Solution:
"""Class which implements algorithm"""
def sameSumArray(self, array1, array2, fast=True):
"""Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)"""
<|body_0|>
def sameSumArrayFast(self, array1, array2):
"""Time co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Class which implements algorithm"""
def sameSumArray(self, array1, array2, fast=True):
"""Time complexity: O(n) - sum(array1) O(n) - sum(array2) O(n^2) - finding pair O(n^2) + O(2n)"""
if fast:
return self.sameSumArrayFast(array1, array2)
_sum_array1 = sum... | the_stack_v2_python_sparse | sameSumArray.py | eselyavka/python | train | 0 |
db34fbd364648cb4e292bd5102c6d58ee6b52fc0 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn RiskyUserHistoryItem()",
"from .risk_user_activity import RiskUserActivity\nfrom .risky_user import RiskyUser\nfrom .risk_user_activity import RiskUserActivity\nfrom .risky_user import RiskyUser\nfields: Dict[str, Callable[[Any], None]... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return RiskyUserHistoryItem()
<|end_body_0|>
<|body_start_1|>
from .risk_user_activity import RiskUserActivity
from .risky_user import RiskyUser
from .risk_user_activity import RiskUser... | RiskyUserHistoryItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RiskyUserHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyUserHistoryItem:
"""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 ... | stack_v2_sparse_classes_36k_train_007761 | 2,658 | 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: RiskyUserHistoryItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminato... | 3 | stack_v2_sparse_classes_30k_train_011020 | Implement the Python class `RiskyUserHistoryItem` described below.
Class description:
Implement the RiskyUserHistoryItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyUserHistoryItem: Creates a new instance of the appropriate class based o... | Implement the Python class `RiskyUserHistoryItem` described below.
Class description:
Implement the RiskyUserHistoryItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyUserHistoryItem: Creates a new instance of the appropriate class based o... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class RiskyUserHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyUserHistoryItem:
"""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 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RiskyUserHistoryItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> RiskyUserHistoryItem:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | the_stack_v2_python_sparse | msgraph/generated/models/risky_user_history_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
6ef710fee16714eafdda3be83d6fa3c6d02fa4ee | [
"self.log = get_logger(__name__)\nself._filename = filename or tempfile.mktemp(SUFFIX, PREFIX)\nif not filename:\n with os.fdopen(os.open(self._filename, os.O_WRONLY | os.O_CREAT, 384), 'wb') as tmp_fh:\n tmp_fh.write(sugar.utils.stringutils.to_bytes(hashlib.sha256(os.urandom(4095)).hexdigest()))\nelif no... | <|body_start_0|>
self.log = get_logger(__name__)
self._filename = filename or tempfile.mktemp(SUFFIX, PREFIX)
if not filename:
with os.fdopen(os.open(self._filename, os.O_WRONLY | os.O_CREAT, 384), 'wb') as tmp_fh:
tmp_fh.write(sugar.utils.stringutils.to_bytes(hashlib... | Master token for local connections. | MasterLocalToken | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MasterLocalToken:
"""Master token for local connections."""
def __init__(self, filename=None):
"""Creates master local token. :param filename: filename, default to None"""
<|body_0|>
def get_token(self):
"""Get token from the disk. :return: Token string"""
... | stack_v2_sparse_classes_36k_train_007762 | 2,126 | permissive | [
{
"docstring": "Creates master local token. :param filename: filename, default to None",
"name": "__init__",
"signature": "def __init__(self, filename=None)"
},
{
"docstring": "Get token from the disk. :return: Token string",
"name": "get_token",
"signature": "def get_token(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_008805 | Implement the Python class `MasterLocalToken` described below.
Class description:
Master token for local connections.
Method signatures and docstrings:
- def __init__(self, filename=None): Creates master local token. :param filename: filename, default to None
- def get_token(self): Get token from the disk. :return: T... | Implement the Python class `MasterLocalToken` described below.
Class description:
Master token for local connections.
Method signatures and docstrings:
- def __init__(self, filename=None): Creates master local token. :param filename: filename, default to None
- def get_token(self): Get token from the disk. :return: T... | f9e2e84ab4dbdbb36c7a5eb07123505abce9ec2c | <|skeleton|>
class MasterLocalToken:
"""Master token for local connections."""
def __init__(self, filename=None):
"""Creates master local token. :param filename: filename, default to None"""
<|body_0|>
def get_token(self):
"""Get token from the disk. :return: Token string"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MasterLocalToken:
"""Master token for local connections."""
def __init__(self, filename=None):
"""Creates master local token. :param filename: filename, default to None"""
self.log = get_logger(__name__)
self._filename = filename or tempfile.mktemp(SUFFIX, PREFIX)
if not f... | the_stack_v2_python_sparse | sugar/utils/tokens.py | sugarsack/sugar | train | 13 |
48270e87fc9bebd7e8143175cb2304f3471e5c46 | [
"super().__init__(properties=properties, source=source, copy=copy)\nself._initialise_netcdf(source)\nself._initialise_original_filenames(source)",
"if _create_title and _title is None:\n _title = 'Node Count: ' + self.identity(default='')\nreturn super().dump(display=display, _key=_key, _omit_properties=_omit_... | <|body_start_0|>
super().__init__(properties=properties, source=source, copy=copy)
self._initialise_netcdf(source)
self._initialise_original_filenames(source)
<|end_body_0|>
<|body_start_1|>
if _create_title and _title is None:
_title = 'Node Count: ' + self.identity(default... | Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0 | NodeCountProperties | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeCountProperties:
"""Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0"""
def __init__(self, properties=None, source=None, copy=True):
"""**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Param... | stack_v2_sparse_classes_36k_train_007763 | 1,833 | permissive | [
{
"docstring": "**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:* ``properties={'long_name': 'number of nodes for each geometry'}`` {{init source: optional}} {{init copy: `bool`, optional}}",
"name": "__init__",
"signature": "def __init__(self, properties=None, s... | 2 | null | Implement the Python class `NodeCountProperties` described below.
Class description:
Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0
Method signatures and docstrings:
- def __init__(self, properties=None, source=None, copy=True): **Initialisation** ... | Implement the Python class `NodeCountProperties` described below.
Class description:
Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0
Method signatures and docstrings:
- def __init__(self, properties=None, source=None, copy=True): **Initialisation** ... | 142accf27fbbc052473b4eee47daf0e81c88df3a | <|skeleton|>
class NodeCountProperties:
"""Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0"""
def __init__(self, properties=None, source=None, copy=True):
"""**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeCountProperties:
"""Properties for a netCDF node count variable. **NetCDF interface** {{netCDF variable}} .. versionadded:: (cfdm) 1.8.0"""
def __init__(self, properties=None, source=None, copy=True):
"""**Initialisation** :Parameters: {{init properties: `dict`, optional}} *Parameter example:... | the_stack_v2_python_sparse | cfdm/nodecountproperties.py | NCAS-CMS/cfdm | train | 29 |
6eb657ab3d0c83d6898e4d28ec079766ca21858c | [
"super().__init__()\nself.bot = bot\nself.data = UserTracking()\nif min_mentions_per_message > total_mentions_before_punishment:\n raise ValueError('Expected `min_mentions_per_message` to be less then or equal to `total_mentions_before_punishment`')\nif time_period < 1:\n raise ValueError('Expected `time_peri... | <|body_start_0|>
super().__init__()
self.bot = bot
self.data = UserTracking()
if min_mentions_per_message > total_mentions_before_punishment:
raise ValueError('Expected `min_mentions_per_message` to be less then or equal to `total_mentions_before_punishment`')
if time... | A simple class used to track mentions | AntiMassMention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AntiMassMention:
"""A simple class used to track mentions"""
def __init__(self, bot, *, total_mentions_before_punishment: int=10, time_period: int=15000, min_mentions_per_message: int=5):
"""Parameters ---------- bot : commands.Bot or commands.AutoShardedBot or discord.Client or disc... | stack_v2_sparse_classes_36k_train_007764 | 6,305 | permissive | [
{
"docstring": "Parameters ---------- bot : commands.Bot or commands.AutoShardedBot or discord.Client or discord.AutoShardedClient Our bot instance total_mentions_before_punishment : int How many mentions within the time period before we punish the user *Inclusive* time_period : int The time period valid for me... | 3 | stack_v2_sparse_classes_30k_train_016167 | Implement the Python class `AntiMassMention` described below.
Class description:
A simple class used to track mentions
Method signatures and docstrings:
- def __init__(self, bot, *, total_mentions_before_punishment: int=10, time_period: int=15000, min_mentions_per_message: int=5): Parameters ---------- bot : commands... | Implement the Python class `AntiMassMention` described below.
Class description:
A simple class used to track mentions
Method signatures and docstrings:
- def __init__(self, bot, *, total_mentions_before_punishment: int=10, time_period: int=15000, min_mentions_per_message: int=5): Parameters ---------- bot : commands... | 2c969cf5b0a9f15aac48c057b125c22be74eb6cc | <|skeleton|>
class AntiMassMention:
"""A simple class used to track mentions"""
def __init__(self, bot, *, total_mentions_before_punishment: int=10, time_period: int=15000, min_mentions_per_message: int=5):
"""Parameters ---------- bot : commands.Bot or commands.AutoShardedBot or discord.Client or disc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AntiMassMention:
"""A simple class used to track mentions"""
def __init__(self, bot, *, total_mentions_before_punishment: int=10, time_period: int=15000, min_mentions_per_message: int=5):
"""Parameters ---------- bot : commands.Bot or commands.AutoShardedBot or discord.Client or discord.AutoShard... | the_stack_v2_python_sparse | antispam/ext/anti_mass_mention.py | Jiternos/DPY-Anti-Spam | train | 0 |
5c2a3b25b02a161bfab58229dfe2a003b2c9cc3f | [
"inv.LOGGER.info('--- Start Test add_furniture() ---')\nif os.path.exists('rented_items.csv'):\n os.remove('rented_items.csv')\ninv.add_furniture('rented_items.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25.0)\ninv.add_furniture('rented_items.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10.0)\ninv.add_furnitur... | <|body_start_0|>
inv.LOGGER.info('--- Start Test add_furniture() ---')
if os.path.exists('rented_items.csv'):
os.remove('rented_items.csv')
inv.add_furniture('rented_items.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25.0)
inv.add_furniture('rented_items.csv', 'Edward Data', ... | This class defines unit test fuctions for invetory.py | inventory_Tests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
<|body_0|>
def test_single_customer(self):
"""Test single_customer function"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_36k_train_007765 | 1,728 | no_license | [
{
"docstring": "Test add_furniture function",
"name": "test_add_furniture",
"signature": "def test_add_furniture(self)"
},
{
"docstring": "Test single_customer function",
"name": "test_single_customer",
"signature": "def test_single_customer(self)"
}
] | 2 | null | Implement the Python class `inventory_Tests` described below.
Class description:
This class defines unit test fuctions for invetory.py
Method signatures and docstrings:
- def test_add_furniture(self): Test add_furniture function
- def test_single_customer(self): Test single_customer function | Implement the Python class `inventory_Tests` described below.
Class description:
This class defines unit test fuctions for invetory.py
Method signatures and docstrings:
- def test_add_furniture(self): Test add_furniture function
- def test_single_customer(self): Test single_customer function
<|skeleton|>
class inven... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
<|body_0|>
def test_single_customer(self):
"""Test single_customer function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class inventory_Tests:
"""This class defines unit test fuctions for invetory.py"""
def test_add_furniture(self):
"""Test add_furniture function"""
inv.LOGGER.info('--- Start Test add_furniture() ---')
if os.path.exists('rented_items.csv'):
os.remove('rented_items.csv')
... | the_stack_v2_python_sparse | students/zhen_yang/lesson08/assignment/test_inventory.py | JavaRod/SP_Python220B_2019 | train | 1 |
699ee7c085ae75873aad30a4a81c344c6e758275 | [
"super().__init__()\nif nn_embedding is not None:\n self.embedding = nn.Embedding.from_pretrained(nn_embedding)\nelif sum(field_sizes) is not None and embed_size is not None:\n self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs)\nelse:\n raise ValueError('missing required arguments')\nsel... | <|body_start_0|>
super().__init__()
if nn_embedding is not None:
self.embedding = nn.Embedding.from_pretrained(nn_embedding)
elif sum(field_sizes) is not None and embed_size is not None:
self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs)
else:
... | Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding. | MultiIndicesEmbedding | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par... | stack_v2_sparse_classes_36k_train_007766 | 4,009 | permissive | [
{
"docstring": "Initialize MultiIndicesEmbedding. Args: embed_size (int): size of embedding tensor. Defaults to None field_sizes (List[int]): list of inputs fields' sizes. Defaults to None nn_embedding (nn.Parameter, optional): pretrained embedding values. Defaults to None device (str): device of torch. Default... | 4 | stack_v2_sparse_classes_30k_train_006898 | Implement the Python class `MultiIndicesEmbedding` described below.
Class description:
Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, ... | Implement the Python class `MultiIndicesEmbedding` described below.
Class description:
Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.
Method signatures and docstrings:
- def __init__(self, embed_size: Optional[int]=None, ... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiIndicesEmbedding:
"""Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding."""
def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Parameter]=None,... | the_stack_v2_python_sparse | torecsys/inputs/base/multi_indices_emb.py | p768lwy3/torecsys | train | 98 |
e9c78fa9e4f7c7e0ba608c3c29c8a5c956c74f6b | [
"super().__init__()\nself.attention_dim = attention_dim\nself.emb = torch.nn.Embedding(vocabs, attention_dim)\ntorch.nn.init.normal_(self.emb.weight, 0.0, attention_dim ** (-0.5))\nself.encoder = Encoder(idim=-1, input_layer=None, attention_dim=attention_dim, attention_heads=attention_heads, linear_units=linear_uni... | <|body_start_0|>
super().__init__()
self.attention_dim = attention_dim
self.emb = torch.nn.Embedding(vocabs, attention_dim)
torch.nn.init.normal_(self.emb.weight, 0.0, attention_dim ** (-0.5))
self.encoder = Encoder(idim=-1, input_layer=None, attention_dim=attention_dim, attentio... | Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer architecture as the encoder module, which contains additional convolution layers. ..... | TextEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextEncoder:
"""Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer architecture as the encoder module, which con... | stack_v2_sparse_classes_36k_train_007767 | 5,385 | permissive | [
{
"docstring": "Initialize TextEncoder module. Args: vocabs (int): Vocabulary size. attention_dim (int): Attention dimension. attention_heads (int): Number of attention heads. linear_units (int): Number of linear units of positionwise layers. blocks (int): Number of encoder blocks. positionwise_layer_type (str)... | 2 | null | Implement the Python class `TextEncoder` described below.
Class description:
Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer archit... | Implement the Python class `TextEncoder` described below.
Class description:
Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer archit... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class TextEncoder:
"""Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer architecture as the encoder module, which con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextEncoder:
"""Text encoder module in VITS. This is a module of text encoder described in `Conditional Variational Autoencoder with Adversarial Learning for End-to-End Text-to-Speech`_. Instead of the relative positional Transformer, we use conformer architecture as the encoder module, which contains additio... | the_stack_v2_python_sparse | espnet2/gan_tts/vits/text_encoder.py | espnet/espnet | train | 7,242 |
2fa417d4d0364590e2fedc09ccc1400d746d34ad | [
"super().__init__()\nself.enc_hidden_size = enc_hidden_size\nself.dec_hidden_size = dec_hidden_size\nself.W = nn.Linear(enc_hidden_size + dec_hidden_size, 1)\nself.sigmoid = nn.Sigmoid()",
"p = self.W(torch.cat([decoder_state, context], dim=1))\np = self.sigmoid(p)\nreturn p"
] | <|body_start_0|>
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hidden_size = dec_hidden_size
self.W = nn.Linear(enc_hidden_size + dec_hidden_size, 1)
self.sigmoid = nn.Sigmoid()
<|end_body_0|>
<|body_start_1|>
p = self.W(torch.cat([decoder_state, con... | CopySwitch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopySwitch:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256):
"""Pointing the Unknown Words (ACL 2016)"""
<|body_0|>
def forward(self, decoder_state, context):
"""Args: decoder_state [B, hidden_size] context [B, hidden_size] Return: p [B, 1] p = sigmoid(W... | stack_v2_sparse_classes_36k_train_007768 | 49,575 | no_license | [
{
"docstring": "Pointing the Unknown Words (ACL 2016)",
"name": "__init__",
"signature": "def __init__(self, enc_hidden_size=512, dec_hidden_size=256)"
},
{
"docstring": "Args: decoder_state [B, hidden_size] context [B, hidden_size] Return: p [B, 1] p = sigmoid(W @ s + U @ c + b)",
"name": "... | 2 | null | Implement the Python class `CopySwitch` described below.
Class description:
Implement the CopySwitch class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256): Pointing the Unknown Words (ACL 2016)
- def forward(self, decoder_state, context): Args: decoder_state [B, hidde... | Implement the Python class `CopySwitch` described below.
Class description:
Implement the CopySwitch class.
Method signatures and docstrings:
- def __init__(self, enc_hidden_size=512, dec_hidden_size=256): Pointing the Unknown Words (ACL 2016)
- def forward(self, decoder_state, context): Args: decoder_state [B, hidde... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class CopySwitch:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256):
"""Pointing the Unknown Words (ACL 2016)"""
<|body_0|>
def forward(self, decoder_state, context):
"""Args: decoder_state [B, hidden_size] context [B, hidden_size] Return: p [B, 1] p = sigmoid(W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopySwitch:
def __init__(self, enc_hidden_size=512, dec_hidden_size=256):
"""Pointing the Unknown Words (ACL 2016)"""
super().__init__()
self.enc_hidden_size = enc_hidden_size
self.dec_hidden_size = dec_hidden_size
self.W = nn.Linear(enc_hidden_size + dec_hidden_size, 1... | the_stack_v2_python_sparse | generated/test_clovaai_FocusSeq2Seq.py | jansel/pytorch-jit-paritybench | train | 35 | |
0d62d5e599c354881dec58608c9f0396c62d545f | [
"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 Ad Group Ad service. Service to manage ads in an ad group. | AdGroupAdServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAdGroupAds(self, request, context):
... | stack_v2_sparse_classes_36k_train_007769 | 3,304 | permissive | [
{
"docstring": "Returns the requested ad in full detail.",
"name": "GetAdGroupAd",
"signature": "def GetAdGroupAd(self, request, context)"
},
{
"docstring": "Creates, updates, or removes ads. Operation statuses are returned.",
"name": "MutateAdGroupAds",
"signature": "def MutateAdGroupAd... | 2 | stack_v2_sparse_classes_30k_train_019011 | Implement the Python class `AdGroupAdServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad service. Service to manage ads in an ad group.
Method signatures and docstrings:
- def GetAdGroupAd(self, request, context): Returns the requested ad in full detail.
- def MutateAdGroupAds(s... | Implement the Python class `AdGroupAdServiceServicer` described below.
Class description:
Proto file describing the Ad Group Ad service. Service to manage ads in an ad group.
Method signatures and docstrings:
- def GetAdGroupAd(self, request, context): Returns the requested ad in full detail.
- def MutateAdGroupAds(s... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
<|body_0|>
def MutateAdGroupAds(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdGroupAdServiceServicer:
"""Proto file describing the Ad Group Ad service. Service to manage ads in an ad group."""
def GetAdGroupAd(self, request, context):
"""Returns the requested ad in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/ad_group_ad_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
385e6c0fd733bb2146de322917e44fc635480985 | [
"manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)\nrepresentation_manager = manager.get_representation_manager()\ndocument_type = type(manager.context).documents.model_class\nreturn representation_manager.represent_listing(implementedBy(document_type))",
"manager = self.re... | <|body_start_0|>
manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)
representation_manager = manager.get_representation_manager()
document_type = type(manager.context).documents.model_class
return representation_manager.represent_listing(implemented... | AuctionCancellationDocumentResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuctionCancellationDocumentResource:
def collection_get(self):
"""Auction Cancellation Documents List"""
<|body_0|>
def collection_post(self):
"""Auction Cancellation Document Post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
manager = self.reque... | stack_v2_sparse_classes_36k_train_007770 | 2,068 | permissive | [
{
"docstring": "Auction Cancellation Documents List",
"name": "collection_get",
"signature": "def collection_get(self)"
},
{
"docstring": "Auction Cancellation Document Post",
"name": "collection_post",
"signature": "def collection_post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006870 | Implement the Python class `AuctionCancellationDocumentResource` described below.
Class description:
Implement the AuctionCancellationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Auction Cancellation Documents List
- def collection_post(self): Auction Cancellation Document Pos... | Implement the Python class `AuctionCancellationDocumentResource` described below.
Class description:
Implement the AuctionCancellationDocumentResource class.
Method signatures and docstrings:
- def collection_get(self): Auction Cancellation Documents List
- def collection_post(self): Auction Cancellation Document Pos... | 05c9ea3db1b1d290521b1430286ff2e5064819cd | <|skeleton|>
class AuctionCancellationDocumentResource:
def collection_get(self):
"""Auction Cancellation Documents List"""
<|body_0|>
def collection_post(self):
"""Auction Cancellation Document Post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuctionCancellationDocumentResource:
def collection_get(self):
"""Auction Cancellation Documents List"""
manager = self.request.registry.queryMultiAdapter((self.request, self.context), IManager)
representation_manager = manager.get_representation_manager()
document_type = type(... | the_stack_v2_python_sparse | openprocurement/auctions/geb/views/cancellation_document.py | andrey484/openprocurement.auctions.geb | train | 0 | |
91bc824fbc850b3a8d04607956fc21673b175379 | [
"self.entity_description = description\nself.dht_client = dht_client\nself.temperature_offset = temperature_offset\nself.humidity_offset = humidity_offset\nself._attr_name = f'{name} {description.name}'",
"self.dht_client.update()\ntemperature_offset = self.temperature_offset\nhumidity_offset = self.humidity_offs... | <|body_start_0|>
self.entity_description = description
self.dht_client = dht_client
self.temperature_offset = temperature_offset
self.humidity_offset = humidity_offset
self._attr_name = f'{name} {description.name}'
<|end_body_0|>
<|body_start_1|>
self.dht_client.update()... | Implementation of the DHT sensor. | DHTSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from the DHT and u... | stack_v2_sparse_classes_36k_train_007771 | 5,733 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription)"
},
{
"docstring": "Get the latest data from the DHT and updates the states.",
"name": "update",
"sig... | 2 | stack_v2_sparse_classes_30k_train_004704 | Implement the Python class `DHTSensor` described below.
Class description:
Implementation of the DHT sensor.
Method signatures and docstrings:
- def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription): Initialize the sensor.
- def update(self): Get the latest da... | Implement the Python class `DHTSensor` described below.
Class description:
Implementation of the DHT sensor.
Method signatures and docstrings:
- def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription): Initialize the sensor.
- def update(self): Get the latest da... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
<|body_0|>
def update(self):
"""Get the latest data from the DHT and u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DHTSensor:
"""Implementation of the DHT sensor."""
def __init__(self, dht_client, name, temperature_offset, humidity_offset, description: SensorEntityDescription):
"""Initialize the sensor."""
self.entity_description = description
self.dht_client = dht_client
self.temperat... | the_stack_v2_python_sparse | homeassistant/components/dht/sensor.py | AlexxIT/home-assistant | train | 9 |
6d8d3afc2e4fa1d5ad9fdf6540663047b434c6ec | [
"x = y = predecessor = pred = None\nwhile root:\n if root.left:\n predecessor = root.left\n while predecessor.right and predecessor.right != root:\n predecessor = predecessor.right\n if not predecessor.right:\n predecessor.right = root\n root = root.left\n ... | <|body_start_0|>
x = y = predecessor = pred = None
while root:
if root.left:
predecessor = root.left
while predecessor.right and predecessor.right != root:
predecessor = predecessor.right
if not predecessor.right:
... | RecoverBST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecoverBST:
def recover_bst(self, root: TreeNode):
"""Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def recover_bst__(self, root: TreeNode):
"""Approach: Recursive in-order with two_swapped with-in Time Complexity: ... | stack_v2_sparse_classes_36k_train_007772 | 3,687 | no_license | [
{
"docstring": "Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:",
"name": "recover_bst",
"signature": "def recover_bst(self, root: TreeNode)"
},
{
"docstring": "Approach: Recursive in-order with two_swapped with-in Time Complexity: O(N) Space Complexity: O(H) ... | 4 | stack_v2_sparse_classes_30k_train_006132 | Implement the Python class `RecoverBST` described below.
Class description:
Implement the RecoverBST class.
Method signatures and docstrings:
- def recover_bst(self, root: TreeNode): Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def recover_bst__(self, root: TreeNode): Approach... | Implement the Python class `RecoverBST` described below.
Class description:
Implement the RecoverBST class.
Method signatures and docstrings:
- def recover_bst(self, root: TreeNode): Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:
- def recover_bst__(self, root: TreeNode): Approach... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class RecoverBST:
def recover_bst(self, root: TreeNode):
"""Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
<|body_0|>
def recover_bst__(self, root: TreeNode):
"""Approach: Recursive in-order with two_swapped with-in Time Complexity: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecoverBST:
def recover_bst(self, root: TreeNode):
"""Approach: Morris Time Complexity: O(N) Space Complexity: O(1) :param root: :return:"""
x = y = predecessor = pred = None
while root:
if root.left:
predecessor = root.left
while predecessor... | the_stack_v2_python_sparse | data_structures/tree_node/bst_recover.py | Shiv2157k/leet_code | train | 1 | |
3d253f2c18f28956acc91f103fa970ccf1a9e4b8 | [
"self.sess = tf.Session()\nvocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)\nself.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)\nself.model = model_utils.create_model(self.sess, True)\nself.model.batch_size = 1",
"token_ids = data_utils.sentence_to_token_ids(sentenc... | <|body_start_0|>
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
self.vocab, self.rev_vocab = data_utils.initialize_vocabulary(vocab_path)
self.model = model_utils.create_model(self.sess, True)
self.model.batch_size = 1
<|end_bod... | ChatBot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_36k_train_007773 | 2,435 | no_license | [
{
"docstring": "Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Talk with the chatbot! Args: sentence: Sentence to be... | 2 | stack_v2_sparse_classes_30k_train_012920 | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | Implement the Python class `ChatBot` described below.
Class description:
Implement the ChatBot class.
Method signatures and docstrings:
- def __init__(self): Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time.
- def re... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
<|body_0|>
def respond(self, sentence):
"""Talk with the chatbot! Args: sentence... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ChatBot:
def __init__(self):
"""Create the chatbot Initializes a tensorflow session, initialzes vocabulary and builds a model with a batch size of 1 for decoding 1 sentence at a time."""
self.sess = tf.Session()
vocab_path = os.path.join(params.data_dir, 'vocab%d' % params.vocab_size)
... | the_stack_v2_python_sparse | python/gelsto_SpeakEasy-AI/SpeakEasy-AI-master/model/chat_bot.py | LiuFang816/SALSTM_py_data | train | 10 | |
1a1150c5274a00d3e24a627785a48abb3fced4a5 | [
"model = QtGui.QStandardItemModel()\nparameters = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\nfor index, parameter in enumerate(parameters):\n model.setData(model.index(0, index), parameter)\nw = BoxSum(None, model=model)\nyield w\n'Destroy the GUI'\nw.close()",
"assert isinstance(widget.mapper.mappedWidget... | <|body_start_0|>
model = QtGui.QStandardItemModel()
parameters = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
for index, parameter in enumerate(parameters):
model.setData(model.index(0, index), parameter)
w = BoxSum(None, model=model)
yield w
'Destroy the GUI... | Test the BoxSum | BoxSumTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoxSumTest:
"""Test the BoxSum"""
def widget(self, qapp):
"""Create/Destroy the BoxSum"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
model = QtGui.QStandardItem... | stack_v2_sparse_classes_36k_train_007774 | 1,434 | permissive | [
{
"docstring": "Create/Destroy the BoxSum",
"name": "widget",
"signature": "def widget(self, qapp)"
},
{
"docstring": "Test the GUI in its default state",
"name": "testDefaults",
"signature": "def testDefaults(self, widget)"
}
] | 2 | null | Implement the Python class `BoxSumTest` described below.
Class description:
Test the BoxSum
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the BoxSum
- def testDefaults(self, widget): Test the GUI in its default state | Implement the Python class `BoxSumTest` described below.
Class description:
Test the BoxSum
Method signatures and docstrings:
- def widget(self, qapp): Create/Destroy the BoxSum
- def testDefaults(self, widget): Test the GUI in its default state
<|skeleton|>
class BoxSumTest:
"""Test the BoxSum"""
def widge... | 55b1e9f6db58e33729f2a93b7dd1d8bf255b46f7 | <|skeleton|>
class BoxSumTest:
"""Test the BoxSum"""
def widget(self, qapp):
"""Create/Destroy the BoxSum"""
<|body_0|>
def testDefaults(self, widget):
"""Test the GUI in its default state"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BoxSumTest:
"""Test the BoxSum"""
def widget(self, qapp):
"""Create/Destroy the BoxSum"""
model = QtGui.QStandardItemModel()
parameters = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
for index, parameter in enumerate(parameters):
model.setData(model.index(0, i... | the_stack_v2_python_sparse | src/sas/qtgui/Plotting/UnitTesting/BoxSumTest.py | SasView/sasview | train | 48 |
3d77feeded1cca4f00c66a8f76426ec111fce146 | [
"self.config_dirs: List[Path] = []\nself.user_config: bool = False\nself.working_dir: Path = DEFAULT_WORKING_DIR\nself.spack_path: Union[None, Path] = None\nself.disable_plugins: List[str] = []\nself.shared_group: Union[None, str] = None\nself.umask: str = '2'\nself.build_threads: int = 4\nself.max_threads: int = 8... | <|body_start_0|>
self.config_dirs: List[Path] = []
self.user_config: bool = False
self.working_dir: Path = DEFAULT_WORKING_DIR
self.spack_path: Union[None, Path] = None
self.disable_plugins: List[str] = []
self.shared_group: Union[None, str] = None
self.umask: str... | Define types and attributes for Pavilion config options. | PavConfig | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PavConfig:
"""Define types and attributes for Pavilion config options."""
def __init__(self, set_attrs=None):
"""Predefine all the pav_config keys and their types."""
<|body_0|>
def find_file(self, file: Path, sub_dir: Union[str, Path]=None) -> Union[Path, None]:
... | stack_v2_sparse_classes_36k_train_007775 | 27,643 | permissive | [
{
"docstring": "Predefine all the pav_config keys and their types.",
"name": "__init__",
"signature": "def __init__(self, set_attrs=None)"
},
{
"docstring": "Look for the given file and return a full path to it. Relative paths are searched for in all config directories under 'sub_dir', if it exi... | 2 | null | Implement the Python class `PavConfig` described below.
Class description:
Define types and attributes for Pavilion config options.
Method signatures and docstrings:
- def __init__(self, set_attrs=None): Predefine all the pav_config keys and their types.
- def find_file(self, file: Path, sub_dir: Union[str, Path]=Non... | Implement the Python class `PavConfig` described below.
Class description:
Define types and attributes for Pavilion config options.
Method signatures and docstrings:
- def __init__(self, set_attrs=None): Predefine all the pav_config keys and their types.
- def find_file(self, file: Path, sub_dir: Union[str, Path]=Non... | c5c2b475deb8350b433d4af59ec1be67957bc903 | <|skeleton|>
class PavConfig:
"""Define types and attributes for Pavilion config options."""
def __init__(self, set_attrs=None):
"""Predefine all the pav_config keys and their types."""
<|body_0|>
def find_file(self, file: Path, sub_dir: Union[str, Path]=None) -> Union[Path, None]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PavConfig:
"""Define types and attributes for Pavilion config options."""
def __init__(self, set_attrs=None):
"""Predefine all the pav_config keys and their types."""
self.config_dirs: List[Path] = []
self.user_config: bool = False
self.working_dir: Path = DEFAULT_WORKING_... | the_stack_v2_python_sparse | lib/pavilion/config.py | hpc/pavilion2 | train | 43 |
cc83fad44131fd7bb429e95776932135cdb3d132 | [
"self.loc = cast(split[0])\nself.vel = cast(split[1])\nself.acc = cast(split[2])",
"self.vel += self.acc\nself.loc += self.vel\nreturn self.loc"
] | <|body_start_0|>
self.loc = cast(split[0])
self.vel = cast(split[1])
self.acc = cast(split[2])
<|end_body_0|>
<|body_start_1|>
self.vel += self.acc
self.loc += self.vel
return self.loc
<|end_body_1|>
| Point | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Point:
def __init__(self, split):
"""initalize"""
<|body_0|>
def move(self):
"""move the point"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.loc = cast(split[0])
self.vel = cast(split[1])
self.acc = cast(split[2])
<|end_body_0... | stack_v2_sparse_classes_36k_train_007776 | 1,461 | no_license | [
{
"docstring": "initalize",
"name": "__init__",
"signature": "def __init__(self, split)"
},
{
"docstring": "move the point",
"name": "move",
"signature": "def move(self)"
}
] | 2 | null | Implement the Python class `Point` described below.
Class description:
Implement the Point class.
Method signatures and docstrings:
- def __init__(self, split): initalize
- def move(self): move the point | Implement the Python class `Point` described below.
Class description:
Implement the Point class.
Method signatures and docstrings:
- def __init__(self, split): initalize
- def move(self): move the point
<|skeleton|>
class Point:
def __init__(self, split):
"""initalize"""
<|body_0|>
def mov... | b1688431de1c5ab60659bc632c1a7131c3c7aad5 | <|skeleton|>
class Point:
def __init__(self, split):
"""initalize"""
<|body_0|>
def move(self):
"""move the point"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Point:
def __init__(self, split):
"""initalize"""
self.loc = cast(split[0])
self.vel = cast(split[1])
self.acc = cast(split[2])
def move(self):
"""move the point"""
self.vel += self.acc
self.loc += self.vel
return self.loc
| the_stack_v2_python_sparse | 2017/20_02.py | yknot/adventOfCode | train | 0 | |
2363ea0624994509c0db45eb0750b4349b05baff | [
"assert not isinstance(model, Iterable), 'interleaving schedule is not supported for inference'\nmodel.eval()\nself.model = model\nself.inference_params = InferenceParams(max_batch_size, max_sequence_length)\nargs = get_args()\nself.pipeline_size_larger_than_one = args.pipeline_model_parallel_size > 1\nself.pipelin... | <|body_start_0|>
assert not isinstance(model, Iterable), 'interleaving schedule is not supported for inference'
model.eval()
self.model = model
self.inference_params = InferenceParams(max_batch_size, max_sequence_length)
args = get_args()
self.pipeline_size_larger_than_on... | Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller. | ForwardStep | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
<|bod... | stack_v2_sparse_classes_36k_train_007777 | 6,677 | permissive | [
{
"docstring": "Set values so we don't need to do it multiple times.",
"name": "__init__",
"signature": "def __init__(self, model, max_batch_size, max_sequence_length)"
},
{
"docstring": "Invocation of the forward methods. Note that self.inference_params is being modified by the forward step.",
... | 2 | stack_v2_sparse_classes_30k_train_005726 | Implement the Python class `ForwardStep` described below.
Class description:
Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller.
Method signatures and docstrings:
- def __init__(self, model, max_batch_size, max_sequence_length): Set values s... | Implement the Python class `ForwardStep` described below.
Class description:
Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller.
Method signatures and docstrings:
- def __init__(self, model, max_batch_size, max_sequence_length): Set values s... | 99b044bff07f8e5d48b45223ed4bb11bd4e884e6 | <|skeleton|>
class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
assert not isinsta... | the_stack_v2_python_sparse | megatron/text_generation/forward_step.py | NVIDIA/Megatron-LM | train | 6,315 |
fac5cb7fec6bd3148cabcc36b2632d410ff9a1a2 | [
"indy_config = IndyWalletConfig(config)\nopened = await indy_config.create_wallet()\nreturn IndySdkProfile(opened, context)",
"warnings.warn('Indy wallet type is deprecated, use Askar instead; see: https://aca-py.org/main/deploying/IndySDKtoAskarMigration/', DeprecationWarning)\nLOGGER.warning('Indy wallet type i... | <|body_start_0|>
indy_config = IndyWalletConfig(config)
opened = await indy_config.create_wallet()
return IndySdkProfile(opened, context)
<|end_body_0|>
<|body_start_1|>
warnings.warn('Indy wallet type is deprecated, use Askar instead; see: https://aca-py.org/main/deploying/IndySDKtoAsk... | Manager for Indy-SDK wallets. | IndySdkProfileManager | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
<|body_0|>
async def open(self, context: InjectionContext, config: Map... | stack_v2_sparse_classes_36k_train_007778 | 8,718 | permissive | [
{
"docstring": "Provision a new instance of a profile.",
"name": "provision",
"signature": "async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile"
},
{
"docstring": "Open an instance of an existing profile.",
"name": "open",
"signature": "async d... | 2 | stack_v2_sparse_classes_30k_train_004809 | Implement the Python class `IndySdkProfileManager` described below.
Class description:
Manager for Indy-SDK wallets.
Method signatures and docstrings:
- async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile: Provision a new instance of a profile.
- async def open(self, contex... | Implement the Python class `IndySdkProfileManager` described below.
Class description:
Manager for Indy-SDK wallets.
Method signatures and docstrings:
- async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile: Provision a new instance of a profile.
- async def open(self, contex... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
<|body_0|>
async def open(self, context: InjectionContext, config: Map... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndySdkProfileManager:
"""Manager for Indy-SDK wallets."""
async def provision(self, context: InjectionContext, config: Mapping[str, Any]=None) -> Profile:
"""Provision a new instance of a profile."""
indy_config = IndyWalletConfig(config)
opened = await indy_config.create_wallet(... | the_stack_v2_python_sparse | aries_cloudagent/indy/sdk/profile.py | hyperledger/aries-cloudagent-python | train | 370 |
9443f8c7ad9593f1f2fce563a79c8adec00f1d91 | [
"log.info('方法:[{}] 获取到参数:[{}]'.format('jyztUpload', params))\ntry:\n param = check_params(params, 'PARAMS')\n log.info('开始进行入库操作...')\n insert_lis_following(param['PARAMS'])\n return make_response('回传成功')\nexcept Exception as e:\n log.error('方法[{}]产生错误,'.format('jyztUpload'))\n log.error(e)\n ... | <|body_start_0|>
log.info('方法:[{}] 获取到参数:[{}]'.format('jyztUpload', params))
try:
param = check_params(params, 'PARAMS')
log.info('开始进行入库操作...')
insert_lis_following(param['PARAMS'])
return make_response('回传成功')
except Exception as e:
... | 对外实现WebSerice服务 | WebService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WebService:
"""对外实现WebSerice服务"""
def jyztUpload(self, params):
"""检验状态回传接口 :param params: :return:"""
<|body_0|>
def jyxmDictionary(self, params):
"""检验中心推送检查项目字典表给his :param params: :return:"""
<|body_1|>
def lisWjz(self, params):
"""检验危急值 ... | stack_v2_sparse_classes_36k_train_007779 | 5,446 | no_license | [
{
"docstring": "检验状态回传接口 :param params: :return:",
"name": "jyztUpload",
"signature": "def jyztUpload(self, params)"
},
{
"docstring": "检验中心推送检查项目字典表给his :param params: :return:",
"name": "jyxmDictionary",
"signature": "def jyxmDictionary(self, params)"
},
{
"docstring": "检验危急值 :... | 6 | stack_v2_sparse_classes_30k_train_001782 | Implement the Python class `WebService` described below.
Class description:
对外实现WebSerice服务
Method signatures and docstrings:
- def jyztUpload(self, params): 检验状态回传接口 :param params: :return:
- def jyxmDictionary(self, params): 检验中心推送检查项目字典表给his :param params: :return:
- def lisWjz(self, params): 检验危急值 :param params: ... | Implement the Python class `WebService` described below.
Class description:
对外实现WebSerice服务
Method signatures and docstrings:
- def jyztUpload(self, params): 检验状态回传接口 :param params: :return:
- def jyxmDictionary(self, params): 检验中心推送检查项目字典表给his :param params: :return:
- def lisWjz(self, params): 检验危急值 :param params: ... | a768c1c161dfed6eda74ecd7e9c01b106848497b | <|skeleton|>
class WebService:
"""对外实现WebSerice服务"""
def jyztUpload(self, params):
"""检验状态回传接口 :param params: :return:"""
<|body_0|>
def jyxmDictionary(self, params):
"""检验中心推送检查项目字典表给his :param params: :return:"""
<|body_1|>
def lisWjz(self, params):
"""检验危急值 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WebService:
"""对外实现WebSerice服务"""
def jyztUpload(self, params):
"""检验状态回传接口 :param params: :return:"""
log.info('方法:[{}] 获取到参数:[{}]'.format('jyztUpload', params))
try:
param = check_params(params, 'PARAMS')
log.info('开始进行入库操作...')
insert_lis_fo... | the_stack_v2_python_sparse | app/websrv.py | mymousecat/jk-hongqiao-docking | train | 1 |
fef27cd72b16850aa12729c390e3c1b70364db94 | [
"site = coupon.get_site()\ntry:\n twitter_account = TwitterAccount.objects.get(site=site)\n twitter_name = twitter_account.twitter_name\nexcept TwitterAccount.DoesNotExist:\n twitter_name = None\nqualifier = coupon.offer.qualifier\nif add_url and len(qualifier) > 31:\n qualifier = qualifier[:31] + '...'... | <|body_start_0|>
site = coupon.get_site()
try:
twitter_account = TwitterAccount.objects.get(site=site)
twitter_name = twitter_account.twitter_name
except TwitterAccount.DoesNotExist:
twitter_name = None
qualifier = coupon.offer.qualifier
if add... | Class that helps deal with single coupon instances and things related to a single coupon. | TwitterService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterService:
"""Class that helps deal with single coupon instances and things related to a single coupon."""
def build_tweet_message(coupon, add_url=False):
"""Create Tweet (Twitter Status) for this coupon."""
<|body_0|>
def twitter_connect(coupon, message=None):
... | stack_v2_sparse_classes_36k_train_007780 | 3,319 | no_license | [
{
"docstring": "Create Tweet (Twitter Status) for this coupon.",
"name": "build_tweet_message",
"signature": "def build_tweet_message(coupon, add_url=False)"
},
{
"docstring": "Connect to Twitter then either update or return latest status.",
"name": "twitter_connect",
"signature": "def t... | 2 | stack_v2_sparse_classes_30k_train_012773 | Implement the Python class `TwitterService` described below.
Class description:
Class that helps deal with single coupon instances and things related to a single coupon.
Method signatures and docstrings:
- def build_tweet_message(coupon, add_url=False): Create Tweet (Twitter Status) for this coupon.
- def twitter_con... | Implement the Python class `TwitterService` described below.
Class description:
Class that helps deal with single coupon instances and things related to a single coupon.
Method signatures and docstrings:
- def build_tweet_message(coupon, add_url=False): Create Tweet (Twitter Status) for this coupon.
- def twitter_con... | a780ccdc3350d4b5c7990c65d1af8d71060c62cc | <|skeleton|>
class TwitterService:
"""Class that helps deal with single coupon instances and things related to a single coupon."""
def build_tweet_message(coupon, add_url=False):
"""Create Tweet (Twitter Status) for this coupon."""
<|body_0|>
def twitter_connect(coupon, message=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwitterService:
"""Class that helps deal with single coupon instances and things related to a single coupon."""
def build_tweet_message(coupon, add_url=False):
"""Create Tweet (Twitter Status) for this coupon."""
site = coupon.get_site()
try:
twitter_account = TwitterA... | the_stack_v2_python_sparse | coupon/service/twitter_service.py | wcirillo/ten | train | 0 |
cc6fe645a4065c6fc305b3c0898d6400183470fb | [
"super(SBMLReaction, self).__init__(unique_id=unique_id, reversible=reversible, substrates=substrates, products=products, **kw_args)\nself.name = name\nself.synonyms = misc.convert(synonyms, list, list())\nself.rate_constant = misc.convert(rate_constant, float)\nself.lower_bound = misc.convert(lower_bound, float)\n... | <|body_start_0|>
super(SBMLReaction, self).__init__(unique_id=unique_id, reversible=reversible, substrates=substrates, products=products, **kw_args)
self.name = name
self.synonyms = misc.convert(synonyms, list, list())
self.rate_constant = misc.convert(rate_constant, float)
self.... | A biochemical reaction as defined per SBML standard. | SBMLReaction | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SBMLReaction:
"""A biochemical reaction as defined per SBML standard."""
def __init__(self, unique_id='', reversible=False, substrates=None, products=None, name='', synonyms=None, rate_constant=None, lower_bound=None, upper_bound=None, objective_coefficient=None, flux_value=None, reduced_cos... | stack_v2_sparse_classes_36k_train_007781 | 18,790 | permissive | [
{
"docstring": "Parameters ---------- unique_id: str (optional) A string uniquely identifying the reaction among its class. reversible: bool (optional) Whether this reaction is known to occur in both directions in an organism. substrates: dict (optional) A map from the reaction educts to the absolute value of t... | 2 | null | Implement the Python class `SBMLReaction` described below.
Class description:
A biochemical reaction as defined per SBML standard.
Method signatures and docstrings:
- def __init__(self, unique_id='', reversible=False, substrates=None, products=None, name='', synonyms=None, rate_constant=None, lower_bound=None, upper_... | Implement the Python class `SBMLReaction` described below.
Class description:
A biochemical reaction as defined per SBML standard.
Method signatures and docstrings:
- def __init__(self, unique_id='', reversible=False, substrates=None, products=None, name='', synonyms=None, rate_constant=None, lower_bound=None, upper_... | 9459b51bb6f33c7d3c644cd95a9d72a0862470e6 | <|skeleton|>
class SBMLReaction:
"""A biochemical reaction as defined per SBML standard."""
def __init__(self, unique_id='', reversible=False, substrates=None, products=None, name='', synonyms=None, rate_constant=None, lower_bound=None, upper_bound=None, objective_coefficient=None, flux_value=None, reduced_cos... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SBMLReaction:
"""A biochemical reaction as defined per SBML standard."""
def __init__(self, unique_id='', reversible=False, substrates=None, products=None, name='', synonyms=None, rate_constant=None, lower_bound=None, upper_bound=None, objective_coefficient=None, flux_value=None, reduced_cost=None, notes... | the_stack_v2_python_sparse | pyorganism/metabolism/elements.py | Midnighter/pyorganism | train | 2 |
614db3036f2f7ed0a3f09ba39e0b907fe1057a86 | [
"self.attr_dict = {}\nfor key, val in attr_dict.iteritems():\n self.attr_dict[key] = list(val)",
"try:\n newlist = [x for x in self.attr_dict[attr]]\n return newlist\nexcept KeyError:\n return []",
"try:\n self.attr_dict[attr].remove(user)\nexcept ValueError:\n pass\nexcept KeyError:\n pass... | <|body_start_0|>
self.attr_dict = {}
for key, val in attr_dict.iteritems():
self.attr_dict[key] = list(val)
<|end_body_0|>
<|body_start_1|>
try:
newlist = [x for x in self.attr_dict[attr]]
return newlist
except KeyError:
return []
<|end_bo... | Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users. | LocalAttrUserMap | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalAttrUserMap:
"""Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users."""
def __init__(self, attr_dict):
"""Initialize the attribute-to-user map ... | stack_v2_sparse_classes_36k_train_007782 | 3,573 | permissive | [
{
"docstring": "Initialize the attribute-to-user map with a provided dictionary.",
"name": "__init__",
"signature": "def __init__(self, attr_dict)"
},
{
"docstring": "Return the list of all users who are currently authorized to read data with the given attribute. Arguments: attr : string - the a... | 3 | stack_v2_sparse_classes_30k_train_011344 | Implement the Python class `LocalAttrUserMap` described below.
Class description:
Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users.
Method signatures and docstrings:
- def __init_... | Implement the Python class `LocalAttrUserMap` described below.
Class description:
Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users.
Method signatures and docstrings:
- def __init_... | eb61250886e51647bd1edb6d8f4fa7f83eb0bc81 | <|skeleton|>
class LocalAttrUserMap:
"""Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users."""
def __init__(self, attr_dict):
"""Initialize the attribute-to-user map ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LocalAttrUserMap:
"""Simple attribute store that references a static dictionary passed in at initialization. Fields: attr_dict : {string -> [string]} - a dictionary mapping attribute strings to lists of users."""
def __init__(self, attr_dict):
"""Initialize the attribute-to-user map with a provid... | the_stack_v2_python_sparse | pace/pki/attrusermap.py | Global-localhost/PACE-python | train | 0 |
ea22e5dcf772edf9721a2cfcb7d8610375330fcb | [
"if not email:\n raise ValueError('User must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = True\nuser.save(using=self.... | <|body_start_0|>
if not email:
raise ValueError('User must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.cr... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a user with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_007783 | 3,621 | no_license | [
{
"docstring": "Creates and saves a user with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | stack_v2_sparse_classes_30k_train_001711 | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a user with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a user with the given email, date of birth and password.
- def create_superuser(self, ema... | aad0fe4180493bdde8d926254a33ca8c00e6cf62 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a user with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a user with the given email, date of birth and password."""
if not email:
raise ValueError('User must have an email address')
user = self.model(email=self.normalize_email(email), nam... | the_stack_v2_python_sparse | backend/users/models.py | fengdetiankong6/training_system_for_bs | train | 0 | |
be80a7b25e4be366c606dfc7ad20633f5ec5d3ba | [
"if self._context is None:\n self._context = {}\nactive_id = self._context and self._context.get('active_id', False) or False\nif not active_id:\n return False\nlead_brw = self.env['crm.lead'].browse(active_id)\nlead = lead_brw.read(['partner_id'])[0]\nreturn lead['partner_id'][0] if lead['partner_id'] else F... | <|body_start_0|>
if self._context is None:
self._context = {}
active_id = self._context and self._context.get('active_id', False) or False
if not active_id:
return False
lead_brw = self.env['crm.lead'].browse(active_id)
lead = lead_brw.read(['partner_id'])... | CrmMakeContract | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrmMakeContract:
def _selectPartner(self):
"""This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field."""
<|body_0|>
def makecontract(self):
"""This function create Quotation on given case. @pa... | stack_v2_sparse_classes_36k_train_007784 | 7,573 | no_license | [
{
"docstring": "This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field.",
"name": "_selectPartner",
"signature": "def _selectPartner(self)"
},
{
"docstring": "This function create Quotation on given case. @param self: The... | 2 | null | Implement the Python class `CrmMakeContract` described below.
Class description:
Implement the CrmMakeContract class.
Method signatures and docstrings:
- def _selectPartner(self): This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field.
- def m... | Implement the Python class `CrmMakeContract` described below.
Class description:
Implement the CrmMakeContract class.
Method signatures and docstrings:
- def _selectPartner(self): This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field.
- def m... | 163136f382faa8607db8fb6cda42a5ba07c4076b | <|skeleton|>
class CrmMakeContract:
def _selectPartner(self):
"""This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field."""
<|body_0|>
def makecontract(self):
"""This function create Quotation on given case. @pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrmMakeContract:
def _selectPartner(self):
"""This function gets default value for partner_id field. @param self: The object pointer @return: default value of partner_id field."""
if self._context is None:
self._context = {}
active_id = self._context and self._context.get('... | the_stack_v2_python_sparse | property_management_ee/models/crm_lead.py | maarejsys/Roya | train | 0 | |
4d078befe570d6124c37f52c6aed5d2cc561fab6 | [
"wordsets = set(words)\nfor word in words:\n for i in range(1, len(word) + 1):\n if word[i:] in wordsets:\n wordsets.remove(word[i:])\nLens = sum([len(word) + 1 for word in wordsets])\nreturn Lens",
"root = TrieNode(0)\nfor word in words:\n node = root\n for w in word[::-1]:\n if... | <|body_start_0|>
wordsets = set(words)
for word in words:
for i in range(1, len(word) + 1):
if word[i:] in wordsets:
wordsets.remove(word[i:])
Lens = sum([len(word) + 1 for word in wordsets])
return Lens
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words) -> int:
"""查找,没有后缀的单词 :param list[str] words: :return:"""
<|body_0|>
def minimumLengthEncoding2(self, words) -> int:
"""字典树,Trie :param list[str] words: :return:"""
<|body_1|>
def minimumLengthEncoding3(se... | stack_v2_sparse_classes_36k_train_007785 | 3,061 | no_license | [
{
"docstring": "查找,没有后缀的单词 :param list[str] words: :return:",
"name": "minimumLengthEncoding",
"signature": "def minimumLengthEncoding(self, words) -> int"
},
{
"docstring": "字典树,Trie :param list[str] words: :return:",
"name": "minimumLengthEncoding2",
"signature": "def minimumLengthEnco... | 3 | stack_v2_sparse_classes_30k_train_008900 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words) -> int: 查找,没有后缀的单词 :param list[str] words: :return:
- def minimumLengthEncoding2(self, words) -> int: 字典树,Trie :param list[str] words: :ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minimumLengthEncoding(self, words) -> int: 查找,没有后缀的单词 :param list[str] words: :return:
- def minimumLengthEncoding2(self, words) -> int: 字典树,Trie :param list[str] words: :ret... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def minimumLengthEncoding(self, words) -> int:
"""查找,没有后缀的单词 :param list[str] words: :return:"""
<|body_0|>
def minimumLengthEncoding2(self, words) -> int:
"""字典树,Trie :param list[str] words: :return:"""
<|body_1|>
def minimumLengthEncoding3(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minimumLengthEncoding(self, words) -> int:
"""查找,没有后缀的单词 :param list[str] words: :return:"""
wordsets = set(words)
for word in words:
for i in range(1, len(word) + 1):
if word[i:] in wordsets:
wordsets.remove(word[i:])
... | the_stack_v2_python_sparse | 华为题库/单词压缩编码.py | 2226171237/Algorithmpractice | train | 0 | |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\noffset = read_fmt('I', fp)[0]\nreturn cls(name, classID, offset)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_fmt(fp, 'I', self.value)\nreturn written"
] | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, classID, offset)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
written += write_length_and_key(fp, self.classI... | Offset structure. .. py:attribute:: value | Offset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_36k_train_007786 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001030 | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | Implement the Python class `Offset` described below.
Class description:
Offset structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-like object. :param fp: file... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp: file-like object"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Offset:
"""Offset structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
offset = read_fmt('I', fp)[0]
return cls(name, cl... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
4a41e1e5d6910fce1cb570b677cc579664eef7b8 | [
"sockfd = await process.make_afd(await process.socket(AF.UNIX, SOCK.STREAM | SOCK.NONBLOCK))\naddr = await process.task.ptr(await SockaddrUn.from_path(process, path))\nawait sockfd.handle.bind(addr)\nawait sockfd.handle.listen(10)\nreturn StubServer(sockfd, process)",
"import rsyscall._nixdeps.librsyscall\nrsysca... | <|body_start_0|>
sockfd = await process.make_afd(await process.socket(AF.UNIX, SOCK.STREAM | SOCK.NONBLOCK))
addr = await process.task.ptr(await SockaddrUn.from_path(process, path))
await sockfd.handle.bind(addr)
await sockfd.handle.listen(10)
return StubServer(sockfd, process)
<... | A server which can be connected back to by rsyscall-unix-stub. | StubServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StubServer:
"""A server which can be connected back to by rsyscall-unix-stub."""
async def listen_on(cls, process: Process, path: Path) -> StubServer:
"""Start listening on the passed-in path for stub connections."""
<|body_0|>
async def make(cls, process: Process, dir: ... | stack_v2_sparse_classes_36k_train_007787 | 8,556 | no_license | [
{
"docstring": "Start listening on the passed-in path for stub connections.",
"name": "listen_on",
"signature": "async def listen_on(cls, process: Process, path: Path) -> StubServer"
},
{
"docstring": "In the passed-in dir, make a listening stub server and an executable to connect to it.",
"... | 3 | stack_v2_sparse_classes_30k_train_010845 | Implement the Python class `StubServer` described below.
Class description:
A server which can be connected back to by rsyscall-unix-stub.
Method signatures and docstrings:
- async def listen_on(cls, process: Process, path: Path) -> StubServer: Start listening on the passed-in path for stub connections.
- async def m... | Implement the Python class `StubServer` described below.
Class description:
A server which can be connected back to by rsyscall-unix-stub.
Method signatures and docstrings:
- async def listen_on(cls, process: Process, path: Path) -> StubServer: Start listening on the passed-in path for stub connections.
- async def m... | 2a362099610a664caeb7f06dd805e5a0fb80cd08 | <|skeleton|>
class StubServer:
"""A server which can be connected back to by rsyscall-unix-stub."""
async def listen_on(cls, process: Process, path: Path) -> StubServer:
"""Start listening on the passed-in path for stub connections."""
<|body_0|>
async def make(cls, process: Process, dir: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StubServer:
"""A server which can be connected back to by rsyscall-unix-stub."""
async def listen_on(cls, process: Process, path: Path) -> StubServer:
"""Start listening on the passed-in path for stub connections."""
sockfd = await process.make_afd(await process.socket(AF.UNIX, SOCK.STREA... | the_stack_v2_python_sparse | python/rsyscall/tasks/stub.py | catern/rsyscall | train | 68 |
23e2a299748a1cf646df67bb51a7af0c59f79fe1 | [
"for subkey in notify_subkey.GetSubkeys():\n for value_name in self._TRIGGER_VALUE_NAMES:\n handler_value = subkey.GetValueByName(value_name)\n if not handler_value:\n continue\n event_data = WinlogonEventData()\n event_data.application = subkey.name\n event_data.com... | <|body_start_0|>
for subkey in notify_subkey.GetSubkeys():
for value_name in self._TRIGGER_VALUE_NAMES:
handler_value = subkey.GetValueByName(value_name)
if not handler_value:
continue
event_data = WinlogonEventData()
... | Windows Registry plugin for parsing the Winlogon key. | WinlogonPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WinlogonPlugin:
"""Windows Registry plugin for parsing the Winlogon key."""
def _ParseRegisteredDLLs(self, parser_mediator, notify_subkey):
"""Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers an... | stack_v2_sparse_classes_36k_train_007788 | 4,434 | permissive | [
{
"docstring": "Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfVFS. notify_subkey (dfwinreg.WinRegistryKey): Notify Windows Registry subkey.",
"name": "_ParseRegisteredDLLs... | 3 | null | Implement the Python class `WinlogonPlugin` described below.
Class description:
Windows Registry plugin for parsing the Winlogon key.
Method signatures and docstrings:
- def _ParseRegisteredDLLs(self, parser_mediator, notify_subkey): Parses the registered DLLs that receive event notifications. Args: parser_mediator (... | Implement the Python class `WinlogonPlugin` described below.
Class description:
Windows Registry plugin for parsing the Winlogon key.
Method signatures and docstrings:
- def _ParseRegisteredDLLs(self, parser_mediator, notify_subkey): Parses the registered DLLs that receive event notifications. Args: parser_mediator (... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class WinlogonPlugin:
"""Windows Registry plugin for parsing the Winlogon key."""
def _ParseRegisteredDLLs(self, parser_mediator, notify_subkey):
"""Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers an... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WinlogonPlugin:
"""Windows Registry plugin for parsing the Winlogon key."""
def _ParseRegisteredDLLs(self, parser_mediator, notify_subkey):
"""Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other compo... | the_stack_v2_python_sparse | plaso/parsers/winreg_plugins/winlogon.py | log2timeline/plaso | train | 1,506 |
b3107d9f37245b9800def315c79ee9d9df4fa0fa | [
"http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\nif http_x_forwarded_for:\n ip = http_x_forwarded_for.split(',')[-1].strip()\nelse:\n ip = request.META.get('REMOTE_ADDR')\nreturn ip",
"try:\n profile = request.user.profile\nexcept cls.DoesNotExist:\n profile = cls.objects.create(user=... | <|body_start_0|>
http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if http_x_forwarded_for:
ip = http_x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
<|end_body_0|>
<|body_start_1|>
try:
... | This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0 | Profile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_36k_train_007789 | 3,000 | permissive | [
{
"docstring": "Return user IP from request. :param request: django request :return: IP",
"name": "get_user_ip",
"signature": "def get_user_ip(request)"
},
{
"docstring": "Check if self.timezone is empty - get timezone from pygeoip and store it there. :param request: django request :return: noth... | 2 | stack_v2_sparse_classes_30k_test_000406 | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | Implement the Python class `Profile` described below.
Class description:
This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0
Method signatures and docstrings:
- def get_user_ip(request):... | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | <|skeleton|>
class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django requ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Profile:
"""This class represents user profile to store additional data, needed in application. Provides following fields: - `user` - one to one rel to User model - `timezone` - offset from UTC-0"""
def get_user_ip(request):
"""Return user IP from request. :param request: django request :return: ... | the_stack_v2_python_sparse | mysite/accounts/models.py | cjlee112/socraticqs2 | train | 8 |
6e1a3d39d264faa433393fac090468446e888bfe | [
"request = urllib2.Request(api_url + '/compliance/compliance_detail')\nresponse = urllib2.urlopen(request)\njson_object = json.load(response)\nreturn json_object",
"request = urllib2.Request(api_url + '/compliance/compliance_detail?&sort=requirement.name:asc')\nresponse = urllib2.urlopen(request)\njson_object = j... | <|body_start_0|>
request = urllib2.Request(api_url + '/compliance/compliance_detail')
response = urllib2.urlopen(request)
json_object = json.load(response)
return json_object
<|end_body_0|>
<|body_start_1|>
request = urllib2.Request(api_url + '/compliance/compliance_detail?&sort... | MockComplianceApiUtils | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockComplianceApiUtils:
def grab_compliance_json(self, api_url):
"""Return the json grabbed from api :return:"""
<|body_0|>
def grab_sorted_ascending_compliance_json(self, api_url):
"""Return the json grabbed from api :return:"""
<|body_1|>
def grab_sort... | stack_v2_sparse_classes_36k_train_007790 | 1,145 | no_license | [
{
"docstring": "Return the json grabbed from api :return:",
"name": "grab_compliance_json",
"signature": "def grab_compliance_json(self, api_url)"
},
{
"docstring": "Return the json grabbed from api :return:",
"name": "grab_sorted_ascending_compliance_json",
"signature": "def grab_sorted... | 3 | stack_v2_sparse_classes_30k_train_003668 | Implement the Python class `MockComplianceApiUtils` described below.
Class description:
Implement the MockComplianceApiUtils class.
Method signatures and docstrings:
- def grab_compliance_json(self, api_url): Return the json grabbed from api :return:
- def grab_sorted_ascending_compliance_json(self, api_url): Return ... | Implement the Python class `MockComplianceApiUtils` described below.
Class description:
Implement the MockComplianceApiUtils class.
Method signatures and docstrings:
- def grab_compliance_json(self, api_url): Return the json grabbed from api :return:
- def grab_sorted_ascending_compliance_json(self, api_url): Return ... | 0a846753fea9773661bc4651001fcd151dd07fa9 | <|skeleton|>
class MockComplianceApiUtils:
def grab_compliance_json(self, api_url):
"""Return the json grabbed from api :return:"""
<|body_0|>
def grab_sorted_ascending_compliance_json(self, api_url):
"""Return the json grabbed from api :return:"""
<|body_1|>
def grab_sort... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MockComplianceApiUtils:
def grab_compliance_json(self, api_url):
"""Return the json grabbed from api :return:"""
request = urllib2.Request(api_url + '/compliance/compliance_detail')
response = urllib2.urlopen(request)
json_object = json.load(response)
return json_object... | the_stack_v2_python_sparse | tools/api/mock/MockComplianceApiUtils.py | cmarchis/TukTuk | train | 0 | |
4aa490d340e3821af39bf090a34af3fd9203a470 | [
"if file is None:\n file = sys.stdout\nmessage: str = self.format_usage()\nself._print_message(message[0].upper() + message[1:], file, self.__COLOR_DICT['YELLOW'])",
"if file is None:\n file = sys.stdout\nmessage: str = self.format_help()\nself._print_message(message[0].upper() + message[1:], file, self.__C... | <|body_start_0|>
if file is None:
file = sys.stdout
message: str = self.format_usage()
self._print_message(message[0].upper() + message[1:], file, self.__COLOR_DICT['YELLOW'])
<|end_body_0|>
<|body_start_1|>
if file is None:
file = sys.stdout
message: str... | We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the program usage (default: generated from arguments added to parser) - description: Text... | _ArgumentParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ArgumentParser:
"""We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the program usage (default: generated from arg... | stack_v2_sparse_classes_36k_train_007791 | 6,692 | permissive | [
{
"docstring": "Method print_usage() is an overrided version of the parent's print_usage() method. This method provides text formatting as well. :Args: - self: {_ArgumentParser} self. - file: {TextIO} file to send the output to. :Returns: - {None}",
"name": "print_usage",
"signature": "def print_usage(s... | 5 | stack_v2_sparse_classes_30k_train_010288 | Implement the Python class `_ArgumentParser` described below.
Class description:
We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the pro... | Implement the Python class `_ArgumentParser` described below.
Class description:
We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the pro... | 69b10dbcf1769d38636413594029dd515c052756 | <|skeleton|>
class _ArgumentParser:
"""We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the program usage (default: generated from arg... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _ArgumentParser:
"""We don't want any compatibility issue so we don't overwrite the constructor! The parent constructor method takes the following arguments: :Args: - prog: The name of the program (default: sys.argv[0]) - usage: The string describing the program usage (default: generated from arguments added ... | the_stack_v2_python_sparse | inb/helpers/parser/parser.py | Nadeera3784/inb | train | 0 |
5261e883b73df4a9b003c44ed556a04af7a1f1ef | [
"if not matrix:\n return False\ni = 0\nmatrix_m = len(matrix) - 1\nmatrix_n = len(matrix[0]) - 1\nj = matrix_n\nwhile j >= 0 and i <= matrix_m:\n if matrix[i][j] == target:\n return True\n elif matrix[i][j] < target:\n i += 1\n else:\n j -= 1\nreturn False",
"if not matrix or not ... | <|body_start_0|>
if not matrix:
return False
i = 0
matrix_m = len(matrix) - 1
matrix_n = len(matrix[0]) - 1
j = matrix_n
while j >= 0 and i <= matrix_m:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchMatrix_0(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_007792 | 2,048 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix_0",
"signature": "def searchMatrix_0(self, matrix, target)"
},
{
"docstring": ":type matrix: List[List[int]] :type target: int :rtype: bool",
"name": "searchMatrix",
"signature": "def sea... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix_0(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :ty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchMatrix_0(self, matrix, target): :type matrix: List[List[int]] :type target: int :rtype: bool
- def searchMatrix(self, matrix, target): :type matrix: List[List[int]] :ty... | b0f498ebe84e46b7e17e94759dd462891dcc8f85 | <|skeleton|>
class Solution:
def searchMatrix_0(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_0|>
def searchMatrix(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchMatrix_0(self, matrix, target):
""":type matrix: List[List[int]] :type target: int :rtype: bool"""
if not matrix:
return False
i = 0
matrix_m = len(matrix) - 1
matrix_n = len(matrix[0]) - 1
j = matrix_n
while j >= 0 and i ... | the_stack_v2_python_sparse | 中级算法/sorting-and-searching_8.py | wulinlw/leetcode_cn | train | 0 | |
1b4dcc9272ae814d2d2b8fb2dedb9efc9af1d3dd | [
"exceptions.Exception.__init__(self, msgText)\nself._Dict = kwargs\nself._Arg = msgText\nself._Name = self.__class__.__name__",
"strn = '%s\\n%s\\n' % (self._Name, self._Arg)\nfor key in self._Dict.keys():\n strn = strn + '%s : %s\\n' % (key, self._Dict[key])\nreturn strn"
] | <|body_start_0|>
exceptions.Exception.__init__(self, msgText)
self._Dict = kwargs
self._Arg = msgText
self._Name = self.__class__.__name__
<|end_body_0|>
<|body_start_1|>
strn = '%s\n%s\n' % (self._Name, self._Arg)
for key in self._Dict.keys():
strn = strn + ... | Based on Shahkar GenericException class. | genException | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class genException:
"""Based on Shahkar GenericException class."""
def __init__(self, msgText=None, **kwargs):
"""Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error and current module."""
<|body_0|>
def __str__... | stack_v2_sparse_classes_36k_train_007793 | 1,071 | no_license | [
{
"docstring": "Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error and current module.",
"name": "__init__",
"signature": "def __init__(self, msgText=None, **kwargs)"
},
{
"docstring": "Generate string representation of error.",
... | 2 | null | Implement the Python class `genException` described below.
Class description:
Based on Shahkar GenericException class.
Method signatures and docstrings:
- def __init__(self, msgText=None, **kwargs): Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error a... | Implement the Python class `genException` described below.
Class description:
Based on Shahkar GenericException class.
Method signatures and docstrings:
- def __init__(self, msgText=None, **kwargs): Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error a... | 4e47d578610485e0503fc1270c7d828064643120 | <|skeleton|>
class genException:
"""Based on Shahkar GenericException class."""
def __init__(self, msgText=None, **kwargs):
"""Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error and current module."""
<|body_0|>
def __str__... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class genException:
"""Based on Shahkar GenericException class."""
def __init__(self, msgText=None, **kwargs):
"""Constructor takes one optional argument of exception text and an optional set of key-value pairs describing the error and current module."""
exceptions.Exception.__init__(self, msgT... | the_stack_v2_python_sparse | Import/PublishAgent/genException.py | bbockelm/DBS | train | 0 |
c7390de65fe241b4275cd028cef51a57a8012b58 | [
"code = request.query_params.get('code')\noauth = OAuthQQ()\naccess_token = oauth.get_access_token(code)\nopenid = oauth.get_openid(access_token)\ntry:\n qquser = QQUser.objects.get(openid=openid)\nexcept:\n access_token = tjws.dumps({'openid': openid}, constants.QQ_AUTH_TOKEN_EXPIRES)\n return Response({'... | <|body_start_0|>
code = request.query_params.get('code')
oauth = OAuthQQ()
access_token = oauth.get_access_token(code)
openid = oauth.get_openid(access_token)
try:
qquser = QQUser.objects.get(openid=openid)
except:
access_token = tjws.dumps({'openi... | QQ登录视图 | QQLoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QQLoginView:
"""QQ登录视图"""
def get(self, request):
"""先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了"""
<|body_0|>
def post(self, request):
"""绑定视图, 来到这里就表示这个QQ之前没有授权和一个用户绑定过"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
code = request.query... | stack_v2_sparse_classes_36k_train_007794 | 3,650 | no_license | [
{
"docstring": "先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "绑定视图, 来到这里就表示这个QQ之前没有授权和一个用户绑定过",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008559 | Implement the Python class `QQLoginView` described below.
Class description:
QQ登录视图
Method signatures and docstrings:
- def get(self, request): 先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了
- def post(self, request): 绑定视图, 来到这里就表示这个QQ之前没有授权和一个用户绑定过 | Implement the Python class `QQLoginView` described below.
Class description:
QQ登录视图
Method signatures and docstrings:
- def get(self, request): 先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了
- def post(self, request): 绑定视图, 来到这里就表示这个QQ之前没有授权和一个用户绑定过
<|skeleton|>
class QQLoginView:
"""QQ登录视图"""
def get(se... | 30aa597ac25bff3594e7dfd0d0218f98e127cba5 | <|skeleton|>
class QQLoginView:
"""QQ登录视图"""
def get(self, request):
"""先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了"""
<|body_0|>
def post(self, request):
"""绑定视图, 来到这里就表示这个QQ之前没有授权和一个用户绑定过"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QQLoginView:
"""QQ登录视图"""
def get(self, request):
"""先获取openid, 判断是否已经存在openid,存在就是授权登录过了,直接就可以返回状态保持了"""
code = request.query_params.get('code')
oauth = OAuthQQ()
access_token = oauth.get_access_token(code)
openid = oauth.get_openid(access_token)
try:
... | the_stack_v2_python_sparse | meiduo/meiduo/apps/oauth/views.py | LittleDumbass/meiduo | train | 0 |
8d9231fa0f241d76d0f3fc5195b9f3b9624139e7 | [
"visited = [0] * len(nums)\nmax_depth = 0\nfor i in nums:\n depth = 0\n while not visited[i]:\n depth += 1\n visited[i] = 1\n i = nums[i]\n max_depth = max(max_depth, depth)\nreturn max_depth",
"def traverse(i, nums, count):\n if self.visited[i]:\n self.res = max(self.res, ... | <|body_start_0|>
visited = [0] * len(nums)
max_depth = 0
for i in nums:
depth = 0
while not visited[i]:
depth += 1
visited[i] = 1
i = nums[i]
max_depth = max(max_depth, depth)
return max_depth
<|end_body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def arrayNesting1(self, nums: List[int]) -> int:
"""Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first element in s[k] starts with the selection of the element nums[k] of index = k. - The next element in ... | stack_v2_sparse_classes_36k_train_007795 | 1,339 | no_license | [
{
"docstring": "Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first element in s[k] starts with the selection of the element nums[k] of index = k. - The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arrayNesting1(self, nums: List[int]) -> int: Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first elem... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arrayNesting1(self, nums: List[int]) -> int: Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first elem... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def arrayNesting1(self, nums: List[int]) -> int:
"""Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first element in s[k] starts with the selection of the element nums[k] of index = k. - The next element in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def arrayNesting1(self, nums: List[int]) -> int:
"""Purpose: Build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule: - The first element in s[k] starts with the selection of the element nums[k] of index = k. - The next element in s[k] should be... | the_stack_v2_python_sparse | arrayNesting.py | tashakim/puzzles_python | train | 8 | |
b257f9df6eb1bd6b0a5bfa16cffa9a5707e9f742 | [
"m = 1 if not s else len(s) + 1\nn = 1 if not p else len(p) + 1\ndp = [[False] * n for i in range(m)]\nfor i in range(m):\n for j in range(n):\n if i == 0 and j == 0:\n dp[i][j] = True\n elif i == 0:\n dp[i][j] = dp[i][j - 1] and p[j - 1] == '*'\n elif j == 0:\n ... | <|body_start_0|>
m = 1 if not s else len(s) + 1
n = 1 if not p else len(p) + 1
dp = [[False] * n for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = True
elif i == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isMatchWithDp(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = 1 if not s else len(s) + 1
... | stack_v2_sparse_classes_36k_train_007796 | 1,655 | no_license | [
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatchWithDp",
"signature": "def isMatchWithDp(self, s, p)"
},
{
"docstring": ":type s: str :type p: str :rtype: bool",
"name": "isMatch",
"signature": "def isMatch(self, s, p)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatchWithDp(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isMatchWithDp(self, s, p): :type s: str :type p: str :rtype: bool
- def isMatch(self, s, p): :type s: str :type p: str :rtype: bool
<|skeleton|>
class Solution:
def isM... | 0584b86642dff667f5bf6b7acfbbce86a41a55b6 | <|skeleton|>
class Solution:
def isMatchWithDp(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_0|>
def isMatch(self, s, p):
""":type s: str :type p: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isMatchWithDp(self, s, p):
""":type s: str :type p: str :rtype: bool"""
m = 1 if not s else len(s) + 1
n = 1 if not p else len(p) + 1
dp = [[False] * n for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == ... | the_stack_v2_python_sparse | python_solution/041_050/WildcardMatch.py | CescWang1991/LeetCode-Python | train | 1 | |
353a6ff0d796c054bc92a5c446de5b0439b6bfe8 | [
"if not hasattr(self, '_subscriptions'):\n self._subscriptions = self.request.user.subscriptions.all()\n if self.subscriptions_list_rights != SUBSCRIPTION_STATES.ALL_RIGHTS:\n self._subscriptions = self._subscriptions.filter(state__in=self.subscriptions_list_rights)\nreturn self._subscriptions",
"con... | <|body_start_0|>
if not hasattr(self, '_subscriptions'):
self._subscriptions = self.request.user.subscriptions.all()
if self.subscriptions_list_rights != SUBSCRIPTION_STATES.ALL_RIGHTS:
self._subscriptions = self._subscriptions.filter(state__in=self.subscriptions_list_rig... | A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cached property | WithSubscribedRepositoriesViewMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithSubscribedRepositoriesViewMixin:
"""A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cached property"""
def subscriptions(s... | stack_v2_sparse_classes_36k_train_007797 | 15,489 | no_license | [
{
"docstring": "Return (and cache) the list of all subscriptions of the current user based on the \"subscriptions_list_rights\" attribute",
"name": "subscriptions",
"signature": "def subscriptions(self)"
},
{
"docstring": "Add the list of subscribed repositories in the context, in a variable nam... | 2 | stack_v2_sparse_classes_30k_train_013571 | Implement the Python class `WithSubscribedRepositoriesViewMixin` described below.
Class description:
A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cach... | Implement the Python class `WithSubscribedRepositoriesViewMixin` described below.
Class description:
A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cach... | 63a405b993e77f10b9c2b6d9790aae7576d9d84f | <|skeleton|>
class WithSubscribedRepositoriesViewMixin:
"""A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cached property"""
def subscriptions(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WithSubscribedRepositoriesViewMixin:
"""A mixin that will put the list of all subscribed repositories in the context. Depends only on DependsOnSubscribedViewMixin to get the list of allowed repositories Provides also a list of all the subscriptions as a cached property"""
def subscriptions(self):
... | the_stack_v2_python_sparse | gim/front/mixins/views.py | derekey/github-issues-manager | train | 1 |
5ce8b5059b2ed15ef699e0467d7d0b354739b260 | [
"self.color = color\nself.width = width\nself.beg_x = beg_x\nself.beg_y = beg_y\nself.end_x = end_x\nself.end_y = end_y",
"w_str = f'Wall2d:{self.color}'\nw_str += f' w:{self.width}'\nw_str += f' beg_xy:{self.beg_x},{self.beg_y}'\nw_str += f' end_xy:{self.end_x},{self.end_y}'\nreturn w_str"
] | <|body_start_0|>
self.color = color
self.width = width
self.beg_x = beg_x
self.beg_y = beg_y
self.end_x = end_x
self.end_y = end_y
<|end_body_0|>
<|body_start_1|>
w_str = f'Wall2d:{self.color}'
w_str += f' w:{self.width}'
w_str += f' beg_xy:{self.... | Wall2d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Wall2d:
def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0):
"""Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertica... | stack_v2_sparse_classes_36k_train_007798 | 1,446 | no_license | [
{
"docstring": "Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertical down) in default units default: 0 :end_x: x (horizontal right) default units, default time inc defa... | 2 | null | Implement the Python class `Wall2d` described below.
Class description:
Implement the Wall2d class.
Method signatures and docstrings:
- def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in defau... | Implement the Python class `Wall2d` described below.
Class description:
Implement the Wall2d class.
Method signatures and docstrings:
- def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0): Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in defau... | bedc16eb5f6db0ad3b313355df6d51b5161c3835 | <|skeleton|>
class Wall2d:
def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0):
"""Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertica... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Wall2d:
def __init__(self, color='green', width=1, beg_x=0, beg_y=0, end_x=300, end_y=0):
"""Define/Setup Wall's attributes :color: wall's color default: black :width: width(thickness) in default units default: 1 :beg_x: x (horizontal right) in default units default: 0 :beg_y: y (vertical down) in def... | the_stack_v2_python_sparse | exercises/classes/ball_classes/walll_2d.py | raysmith619/Introduction-To-Programming | train | 3 | |
b0ea628baa6110af9330b6544603806266c37bf7 | [
"for obj in obj_list['hits']['hits']:\n obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)\nreturn obj_list['hits']",
"aggs = obj_list.get('aggregations')\nif not aggs:\n return missing\nreturn aggs"
] | <|body_start_0|>
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits']
<|end_body_0|>
<|body_start_1|>
aggs = obj_list.get('aggregations')
if not aggs:
return missing
r... | Schema for dumping extra information in the UI. | UIListSchema | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_007799 | 7,049 | permissive | [
{
"docstring": "Apply hits transformation.",
"name": "get_hits",
"signature": "def get_hits(self, obj_list)"
},
{
"docstring": "Apply aggregations transformation.",
"name": "get_aggs",
"signature": "def get_aggs(self, obj_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007233 | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation. | Implement the Python class `UIListSchema` described below.
Class description:
Schema for dumping extra information in the UI.
Method signatures and docstrings:
- def get_hits(self, obj_list): Apply hits transformation.
- def get_aggs(self, obj_list): Apply aggregations transformation.
<|skeleton|>
class UIListSchema... | b4bcc2e16df6048149177a6e1ebd514bdb6b0626 | <|skeleton|>
class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
<|body_0|>
def get_aggs(self, obj_list):
"""Apply aggregations transformation."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UIListSchema:
"""Schema for dumping extra information in the UI."""
def get_hits(self, obj_list):
"""Apply hits transformation."""
for obj in obj_list['hits']['hits']:
obj[self.context['object_key']] = self.context['object_schema_cls']().dump(obj)
return obj_list['hits... | the_stack_v2_python_sparse | invenio_rdm_records/resources/serializers/ui/schema.py | ppanero/invenio-rdm-records | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.