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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f66a188bcfcff52eb27aad0bfc01bebff5a3c3b | [
"self.ls = []\nself.ls_d = set()\nself.q = []\nself.q_d = set()\nself.idx = 0",
"self.ls.append([x, self.idx])\nheapq.heappush(self.q, [-x, -self.idx])\nself.idx += 1",
"self.top()\nx, idx = self.ls.pop()\nself.q_d.add(-idx)\nreturn x",
"while self.ls and self.ls[-1][1] in self.ls_d:\n _, idx = self.ls.pop... | <|body_start_0|>
self.ls = []
self.ls_d = set()
self.q = []
self.q_d = set()
self.idx = 0
<|end_body_0|>
<|body_start_1|>
self.ls.append([x, self.idx])
heapq.heappush(self.q, [-x, -self.idx])
self.idx += 1
<|end_body_1|>
<|body_start_2|>
self.top... | MaxStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_36k_train_027100 | 4,000 | no_license | [
{
"docstring": "initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":type x: int :rtype: None",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": ":rtype: int",
"name": "pop",
"signature": "def p... | 6 | null | Implement the Python class `MaxStack` described below.
Class description:
Implement the MaxStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def top(self): :rtype: int
- def peekMax(se... | Implement the Python class `MaxStack` described below.
Class description:
Implement the MaxStack class.
Method signatures and docstrings:
- def __init__(self): initialize your data structure here.
- def push(self, x): :type x: int :rtype: None
- def pop(self): :rtype: int
- def top(self): :rtype: int
- def peekMax(se... | 4c1288c99f78823c7c3bac0ceedd532e64af1258 | <|skeleton|>
class MaxStack:
def __init__(self):
"""initialize your data structure here."""
<|body_0|>
def push(self, x):
""":type x: int :rtype: None"""
<|body_1|>
def pop(self):
""":rtype: int"""
<|body_2|>
def top(self):
""":rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxStack:
def __init__(self):
"""initialize your data structure here."""
self.ls = []
self.ls_d = set()
self.q = []
self.q_d = set()
self.idx = 0
def push(self, x):
""":type x: int :rtype: None"""
self.ls.append([x, self.idx])
heapq.... | the_stack_v2_python_sparse | Algorithms/0716 Max Stack.py | cravo123/LeetCode | train | 6 | |
9083c15a4c1dd6180edcff8b9e90df0d753e1c4c | [
"method = VectorsFactory.method(config)\nif method == 'external':\n return ExternalVectors(config, scoring)\nif method == 'words':\n if not WORDS:\n raise ImportError('Word vector models are not available - install \"similarity\" extra to enable. Otherwise, specify ' + 'method=\"transformers\" to use t... | <|body_start_0|>
method = VectorsFactory.method(config)
if method == 'external':
return ExternalVectors(config, scoring)
if method == 'words':
if not WORDS:
raise ImportError('Word vector models are not available - install "similarity" extra to enable. Oth... | Methods to create Vectors models. | VectorsFactory | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
<|body_0|>
def method(config):
"""Get or derive the vector me... | stack_v2_sparse_classes_36k_train_027101 | 1,870 | permissive | [
{
"docstring": "Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors",
"name": "create",
"signature": "def create(config, scoring)"
},
{
"docstring": "Get or derive the vector method. Args: config: vector configuration Returns: vector met... | 2 | null | Implement the Python class `VectorsFactory` described below.
Class description:
Methods to create Vectors models.
Method signatures and docstrings:
- def create(config, scoring): Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors
- def method(config): Get or... | Implement the Python class `VectorsFactory` described below.
Class description:
Methods to create Vectors models.
Method signatures and docstrings:
- def create(config, scoring): Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors
- def method(config): Get or... | 789a4555cb60ee9cdfa69afae5a5236d197e2b07 | <|skeleton|>
class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
<|body_0|>
def method(config):
"""Get or derive the vector me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VectorsFactory:
"""Methods to create Vectors models."""
def create(config, scoring):
"""Create a Vectors model instance. Args: config: vector configuration scoring: scoring instance Returns: Vectors"""
method = VectorsFactory.method(config)
if method == 'external':
ret... | the_stack_v2_python_sparse | src/python/txtai/vectors/factory.py | neuml/txtai | train | 4,804 |
6d15daf53afe24495ec139b3ba62be1abbe7fd14 | [
"self.nums = nums\n\ndef create_linetree(left, right):\n if left == right:\n node = LineTree([left, right])\n node.sumrange = nums[left]\n return node\n else:\n mid = (left + right) // 2\n curnode = LineTree([left, right])\n curnode.left = create_linetree(left, mid)\n... | <|body_start_0|>
self.nums = nums
def create_linetree(left, right):
if left == right:
node = LineTree([left, right])
node.sumrange = nums[left]
return node
else:
mid = (left + right) // 2
curnode = L... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_027102 | 2,286 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_015753 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | d1a08ddeb06423bb23e8c22c88b3fde048e86b46 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
def create_linetree(left, right):
if left == right:
node = LineTree([left, right])
node.sumrange = nums[left]
return node
else:
... | the_stack_v2_python_sparse | test70.py | xfx1993/goto1000 | train | 0 | |
5d4369f933ee86ec845b1c3599d502952f527e6c | [
"ObjectManager.__init__(self)\nself.getters.update({'email_domain': 'get_general', 'organization': 'get_foreign_key', 'role': 'get_foreign_key', 'effective_role': 'get_foreign_key', 'effective_role_name': 'get_general'})\nself.setters.update({'email_domain': 'set_general', 'organization': 'set_foreign_key', 'role':... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'email_domain': 'get_general', 'organization': 'get_foreign_key', 'role': 'get_foreign_key', 'effective_role': 'get_foreign_key', 'effective_role_name': 'get_general'})
self.setters.update({'email_domain': 'set_general', 'organiz... | Manage mappings between email domain and automatic organization and role assignment. | OrgEmailDomainManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrgEmailDomainManager:
"""Manage mappings between email domain and automatic organization and role assignment."""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, email_domain, organization, role=None):
"""Create a new OrgEmailDomain ... | stack_v2_sparse_classes_36k_train_027103 | 1,902 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new OrgEmailDomain mapping @param email_domain domain name to look for in user's email address @param organization organization to be assigned @param role role to be assigned within or... | 2 | stack_v2_sparse_classes_30k_train_007832 | Implement the Python class `OrgEmailDomainManager` described below.
Class description:
Manage mappings between email domain and automatic organization and role assignment.
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, email_domain, organization, role=None): Create ... | Implement the Python class `OrgEmailDomainManager` described below.
Class description:
Manage mappings between email domain and automatic organization and role assignment.
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, email_domain, organization, role=None): Create ... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class OrgEmailDomainManager:
"""Manage mappings between email domain and automatic organization and role assignment."""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, email_domain, organization, role=None):
"""Create a new OrgEmailDomain ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrgEmailDomainManager:
"""Manage mappings between email domain and automatic organization and role assignment."""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'email_domain': 'get_general', 'organization': 'get_foreign_key', 'role': 'get_... | the_stack_v2_python_sparse | pr_services/user_system/organization_email_domain_manager.py | ninemoreminutes/openassign-server | train | 0 |
027ffea2b3983f93a5b22611ebbb9bcf12d3689d | [
"super().__init__()\nself.__file_list_str = []\nself.__file_list_pathlib = []\nself.__inc_dirs = inc_dirs\nif path is not None:\n os.chdir(path)\nself._recursive_find_files()",
"for f in Path.cwd().iterdir():\n if f.is_file():\n self.__file_list_str.append(str(f))\n self.__file_list_pathlib.ap... | <|body_start_0|>
super().__init__()
self.__file_list_str = []
self.__file_list_pathlib = []
self.__inc_dirs = inc_dirs
if path is not None:
os.chdir(path)
self._recursive_find_files()
<|end_body_0|>
<|body_start_1|>
for f in Path.cwd().iterdir():
... | RecursiveFindFiles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecursiveFindFiles:
def __init__(self, path: Path=None, inc_dirs: bool=False):
""":param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: include directories otherwise only include files"""
<|body_0|>
def _recursive_find_files(self):
... | stack_v2_sparse_classes_36k_train_027104 | 3,368 | no_license | [
{
"docstring": ":param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: include directories otherwise only include files",
"name": "__init__",
"signature": "def __init__(self, path: Path=None, inc_dirs: bool=False)"
},
{
"docstring": "gets a list of all f... | 3 | stack_v2_sparse_classes_30k_train_006984 | Implement the Python class `RecursiveFindFiles` described below.
Class description:
Implement the RecursiveFindFiles class.
Method signatures and docstrings:
- def __init__(self, path: Path=None, inc_dirs: bool=False): :param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: in... | Implement the Python class `RecursiveFindFiles` described below.
Class description:
Implement the RecursiveFindFiles class.
Method signatures and docstrings:
- def __init__(self, path: Path=None, inc_dirs: bool=False): :param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: in... | 1fa14cd2c742097e95e3b44bfda445c4dbf5c136 | <|skeleton|>
class RecursiveFindFiles:
def __init__(self, path: Path=None, inc_dirs: bool=False):
""":param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: include directories otherwise only include files"""
<|body_0|>
def _recursive_find_files(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecursiveFindFiles:
def __init__(self, path: Path=None, inc_dirs: bool=False):
""":param path: will recursively find all files in this path, if None will use CWD :param inc_dirs: include directories otherwise only include files"""
super().__init__()
self.__file_list_str = []
se... | the_stack_v2_python_sparse | python/utils/recursion.py | thermitegod/shell-scripts | train | 0 | |
d4debfa56e0886cd9149ac9660403776113a9204 | [
"try:\n lookup = await self.nyuki.storage.lookups.get_one(lookup_id)\nexcept AutoReconnect:\n return Response(status=503)\nif not lookup:\n return Response(status=404)\nreturn Response(lookup)",
"try:\n lookup = await self.nyuki.storage.lookups.get_one(lookup_id)\nexcept AutoReconnect:\n return Res... | <|body_start_0|>
try:
lookup = await self.nyuki.storage.lookups.get_one(lookup_id)
except AutoReconnect:
return Response(status=503)
if not lookup:
return Response(status=404)
return Response(lookup)
<|end_body_0|>
<|body_start_1|>
try:
... | ApiFactoryLookup | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"LicenseRef-scancode-warran... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiFactoryLookup:
async def get(self, request, lookup_id):
"""Return the lookup table for id `lookup_id`"""
<|body_0|>
async def patch(self, request, lookup_id):
"""Modify an existing lookup table"""
<|body_1|>
async def delete(self, request, lookup_id):... | stack_v2_sparse_classes_36k_train_027105 | 10,772 | permissive | [
{
"docstring": "Return the lookup table for id `lookup_id`",
"name": "get",
"signature": "async def get(self, request, lookup_id)"
},
{
"docstring": "Modify an existing lookup table",
"name": "patch",
"signature": "async def patch(self, request, lookup_id)"
},
{
"docstring": "Del... | 3 | null | Implement the Python class `ApiFactoryLookup` described below.
Class description:
Implement the ApiFactoryLookup class.
Method signatures and docstrings:
- async def get(self, request, lookup_id): Return the lookup table for id `lookup_id`
- async def patch(self, request, lookup_id): Modify an existing lookup table
-... | Implement the Python class `ApiFactoryLookup` described below.
Class description:
Implement the ApiFactoryLookup class.
Method signatures and docstrings:
- async def get(self, request, lookup_id): Return the lookup table for id `lookup_id`
- async def patch(self, request, lookup_id): Modify an existing lookup table
-... | f185fababee380660930243515652093855acfe7 | <|skeleton|>
class ApiFactoryLookup:
async def get(self, request, lookup_id):
"""Return the lookup table for id `lookup_id`"""
<|body_0|>
async def patch(self, request, lookup_id):
"""Modify an existing lookup table"""
<|body_1|>
async def delete(self, request, lookup_id):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApiFactoryLookup:
async def get(self, request, lookup_id):
"""Return the lookup table for id `lookup_id`"""
try:
lookup = await self.nyuki.storage.lookups.get_one(lookup_id)
except AutoReconnect:
return Response(status=503)
if not lookup:
ret... | the_stack_v2_python_sparse | nyuki/workflow/api/factory.py | d-nery/nyuki | train | 0 | |
69f55097bce684431e8e28900284848681d35c54 | [
"boxes = self.data\nsx, sy = factor if ub.iterable(factor) else (factor, factor)\nif torch.is_tensor(boxes):\n new_data = boxes.float().clone()\nelif boxes.dtype.kind != 'f':\n new_data = boxes.astype(np.float)\nelse:\n new_data = boxes.copy()\nnew_data[..., 0:4:2] *= sx\nnew_data[..., 1:4:2] *= sy\nreturn... | <|body_start_0|>
boxes = self.data
sx, sy = factor if ub.iterable(factor) else (factor, factor)
if torch.is_tensor(boxes):
new_data = boxes.float().clone()
elif boxes.dtype.kind != 'f':
new_data = boxes.astype(np.float)
else:
new_data = boxes.c... | methods for transforming bounding boxes | _BoxTransformMixins | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _BoxTransformMixins:
"""methods for transforming bounding boxes"""
def scale(self, factor):
"""works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([... | stack_v2_sparse_classes_36k_train_027106 | 30,722 | permissive | [
{
"docstring": "works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([[1, 1, 10, 10]])).scale((2, .5)).data array([[ 2. , 0.5, 20. , 5. ]]) >>> Boxes(np.array([[10, 10]])).scale... | 4 | stack_v2_sparse_classes_30k_train_015287 | Implement the Python class `_BoxTransformMixins` described below.
Class description:
methods for transforming bounding boxes
Method signatures and docstrings:
- def scale(self, factor): works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scal... | Implement the Python class `_BoxTransformMixins` described below.
Class description:
methods for transforming bounding boxes
Method signatures and docstrings:
- def scale(self, factor): works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scal... | facbc204c5c4596a07ba498883f3f7ffff002f67 | <|skeleton|>
class _BoxTransformMixins:
"""methods for transforming bounding boxes"""
def scale(self, factor):
"""works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _BoxTransformMixins:
"""methods for transforming bounding boxes"""
def scale(self, factor):
"""works with tlbr, cxywh, tlwh, xy, or wh formats Example: >>> # xdoctest: +IGNORE_WHITESPACE >>> Boxes(np.array([1, 1, 10, 10])).scale(2).data array([ 2., 2., 20., 20.]) >>> Boxes(np.array([[1, 1, 10, 10... | the_stack_v2_python_sparse | netharn/util/util_boxes.py | Cookt2/netharn | train | 0 |
536f92fbd41caf1fe602b81c53763013c7bb1888 | [
"try:\n natController = NatController()\n json_data = json.dumps(natController.get_floating_ip_public_address(id))\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype='application/jso... | <|body_start_0|>
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_public_address(id))
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
return Respo... | Nat_FloatingIP_PublicAddress | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP public address parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_027107 | 7,153 | no_license | [
{
"docstring": "Gets the Floating IP public address parameter",
"name": "get",
"signature": "def get(self, id=None)"
},
{
"docstring": "Update the Floating IP public address parameter",
"name": "put",
"signature": "def put(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007545 | Implement the Python class `Nat_FloatingIP_PublicAddress` described below.
Class description:
Implement the Nat_FloatingIP_PublicAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP public address parameter
- def put(self, id): Update the Floating IP public address parameter | Implement the Python class `Nat_FloatingIP_PublicAddress` described below.
Class description:
Implement the Nat_FloatingIP_PublicAddress class.
Method signatures and docstrings:
- def get(self, id=None): Gets the Floating IP public address parameter
- def put(self, id): Update the Floating IP public address parameter... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
<|body_0|>
def put(self, id):
"""Update the Floating IP public address parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Nat_FloatingIP_PublicAddress:
def get(self, id=None):
"""Gets the Floating IP public address parameter"""
try:
natController = NatController()
json_data = json.dumps(natController.get_floating_ip_public_address(id))
resp = Response(json_data, status=200, mim... | the_stack_v2_python_sparse | configuration-agent/nat/rest_api/resources/floating_ip.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
ba8cc8151387553293ff5f9ea0e0d5e8f39024f7 | [
"stack = []\npairs = {')': '(', '}': '{', ']': '['}\nfor c in s:\n if c in ['(', '{', '[']:\n stack.append(c)\n else:\n if not stack:\n return False\n if stack.pop() != pairs[c]:\n return False\nreturn False if stack else True",
"left_list = ['(', '[', '{']\nright_... | <|body_start_0|>
stack = []
pairs = {')': '(', '}': '{', ']': '['}
for c in s:
if c in ['(', '{', '[']:
stack.append(c)
else:
if not stack:
return False
if stack.pop() != pairs[c]:
ret... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid2(self, s: str) -> bool:
"""Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses only '()[]{}'. :param s: :return:"""
<|body_0|>
def isValid(self, s):
""":t... | stack_v2_sparse_classes_36k_train_027108 | 2,244 | permissive | [
{
"docstring": "Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses only '()[]{}'. :param s: :return:",
"name": "isValid2",
"signature": "def isValid2(self, s: str) -> bool"
},
{
"docstring": ":type s: str... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid2(self, s: str) -> bool: Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid2(self, s: str) -> bool: Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def isValid2(self, s: str) -> bool:
"""Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses only '()[]{}'. :param s: :return:"""
<|body_0|>
def isValid(self, s):
""":t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid2(self, s: str) -> bool:
"""Solved at 2022/3/13 Runtime: 49 ms, faster than 40.99% Memory Usage: 13.8 MB, less than 98.73% 1 <= s.length <= 10^4 s consists of parentheses only '()[]{}'. :param s: :return:"""
stack = []
pairs = {')': '(', '}': '{', ']': '['}
... | the_stack_v2_python_sparse | src/20-ValidParenthese.py | Jiezhi/myleetcode | train | 1 | |
0ab782a5ca06f415ab037667a11af8bb8a59443c | [
"M, N = (len(string), len(target))\ndp = [0 for _ in range(N)]\nfor i in range(M - 1, -1, -1):\n prev = 1\n for j in range(N - 1, -1, -1):\n dp_old = dp[j]\n if string[i] == target[j]:\n dp[j] += prev\n prev = dp_old\nreturn dp[0]",
"M, N = (len(string), len(target))\ndp = [[... | <|body_start_0|>
M, N = (len(string), len(target))
dp = [0 for _ in range(N)]
for i in range(M - 1, -1, -1):
prev = 1
for j in range(N - 1, -1, -1):
dp_old = dp[j]
if string[i] == target[j]:
dp[j] += prev
... | Subsequence | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subsequence:
def get_distinct_subsequence(self, string: str, target: str) -> int:
"""Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:"""
<|body_0|>
def get_distinct_subsequence_(self, string: str, target: str) -> int:
... | stack_v2_sparse_classes_36k_train_027109 | 2,461 | no_license | [
{
"docstring": "Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:",
"name": "get_distinct_subsequence",
"signature": "def get_distinct_subsequence(self, string: str, target: str) -> int"
},
{
"docstring": "Approach: DP 2-D Time Complexity: O(MN)... | 3 | stack_v2_sparse_classes_30k_train_007308 | Implement the Python class `Subsequence` described below.
Class description:
Implement the Subsequence class.
Method signatures and docstrings:
- def get_distinct_subsequence(self, string: str, target: str) -> int: Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:
- ... | Implement the Python class `Subsequence` described below.
Class description:
Implement the Subsequence class.
Method signatures and docstrings:
- def get_distinct_subsequence(self, string: str, target: str) -> int: Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:
- ... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Subsequence:
def get_distinct_subsequence(self, string: str, target: str) -> int:
"""Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:"""
<|body_0|>
def get_distinct_subsequence_(self, string: str, target: str) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subsequence:
def get_distinct_subsequence(self, string: str, target: str) -> int:
"""Approach: DP 1D Time Complexity: O(MN) Space Complexity: O(N) :param string: :param target: :return:"""
M, N = (len(string), len(target))
dp = [0 for _ in range(N)]
for i in range(M - 1, -1, -1... | the_stack_v2_python_sparse | data_structures/recurrsion_dp/distinct_subsequence.py | Shiv2157k/leet_code | train | 1 | |
6abba456b35e1eb725bea04447265be8c5681c51 | [
"post_body = json.dumps({'mapping': kwargs})\nresp, body = self.put('OS-FEDERATION/mappings/%s' % mapping_id, post_body)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)",
"resp, body = self.get('OS-FEDERATION/mappings/%s' % mapping_id)\nself.expected_... | <|body_start_0|>
post_body = json.dumps({'mapping': kwargs})
resp, body = self.put('OS-FEDERATION/mappings/%s' % mapping_id, post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
<|end_body_0|>
<|body_start_1|>
... | MappingsClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MappingsClient:
def create_mapping(self, mapping_id, **kwargs):
"""Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#create-a-mapping"""
<|body_0|>
def get_mapp... | stack_v2_sparse_classes_36k_train_027110 | 3,403 | permissive | [
{
"docstring": "Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#create-a-mapping",
"name": "create_mapping",
"signature": "def create_mapping(self, mapping_id, **kwargs)"
},
{
"do... | 5 | null | Implement the Python class `MappingsClient` described below.
Class description:
Implement the MappingsClient class.
Method signatures and docstrings:
- def create_mapping(self, mapping_id, **kwargs): Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.op... | Implement the Python class `MappingsClient` described below.
Class description:
Implement the MappingsClient class.
Method signatures and docstrings:
- def create_mapping(self, mapping_id, **kwargs): Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.op... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class MappingsClient:
def create_mapping(self, mapping_id, **kwargs):
"""Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#create-a-mapping"""
<|body_0|>
def get_mapp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MappingsClient:
def create_mapping(self, mapping_id, **kwargs):
"""Create a mapping. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#create-a-mapping"""
post_body = json.dumps({'mapping': kwargs}... | the_stack_v2_python_sparse | tempest/lib/services/identity/v3/mappings_client.py | openstack/tempest | train | 270 | |
10b36d23537743348c854f2510465570159006c7 | [
"import collections\nself.dict = collections.defaultdict(list)\nself.max = 0\n\ndef visit(root, count, i):\n if root == None:\n return\n self.dict[count].append(i)\n self.max = max(self.max, i - self.dict[count][0] + 1)\n if root.left:\n visit(root.left, count + 1, i * 2)\n if root.righ... | <|body_start_0|>
import collections
self.dict = collections.defaultdict(list)
self.max = 0
def visit(root, count, i):
if root == None:
return
self.dict[count].append(i)
self.max = max(self.max, i - self.dict[count][0] + 1)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def widthOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 45ms"""
<|body_0|>
def widthOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 45ms"""
<|body_1|>
def widthOfBinaryTree_2(self, root):
""":type root: Tr... | stack_v2_sparse_classes_36k_train_027111 | 4,327 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int 45ms",
"name": "widthOfBinaryTree",
"signature": "def widthOfBinaryTree(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int 45ms",
"name": "widthOfBinaryTree_1",
"signature": "def widthOfBinaryTree_1(self, root)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def widthOfBinaryTree(self, root): :type root: TreeNode :rtype: int 45ms
- def widthOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 45ms
- def widthOfBinaryTree_2(se... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def widthOfBinaryTree(self, root): :type root: TreeNode :rtype: int 45ms
- def widthOfBinaryTree_1(self, root): :type root: TreeNode :rtype: int 45ms
- def widthOfBinaryTree_2(se... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def widthOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 45ms"""
<|body_0|>
def widthOfBinaryTree_1(self, root):
""":type root: TreeNode :rtype: int 45ms"""
<|body_1|>
def widthOfBinaryTree_2(self, root):
""":type root: Tr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def widthOfBinaryTree(self, root):
""":type root: TreeNode :rtype: int 45ms"""
import collections
self.dict = collections.defaultdict(list)
self.max = 0
def visit(root, count, i):
if root == None:
return
self.dict[count... | the_stack_v2_python_sparse | MaximumWidthOfBinaryTree_MID_662.py | 953250587/leetcode-python | train | 2 | |
0169497c3fd16970b0adea35bd02e7c7fe319b51 | [
"groups: List[str] = []\nparameters: List[str] = []\nself.__metadata_overrides: Dict[str, Any] = {}\nfor attribute_or_method_name in dir(self):\n attribute_or_method = getattr(self, attribute_or_method_name)\n metadata = self.get_metadata(attribute_or_method_name)\n if metadata:\n _type = metadata.g... | <|body_start_0|>
groups: List[str] = []
parameters: List[str] = []
self.__metadata_overrides: Dict[str, Any] = {}
for attribute_or_method_name in dir(self):
attribute_or_method = getattr(self, attribute_or_method_name)
metadata = self.get_metadata(attribute_or_met... | A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent ParameterGroup instance. Attributes: header (str): User friendly name for the param... | ParameterGroup | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterGroup:
"""A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent ParameterGroup instance. Attributes: head... | stack_v2_sparse_classes_36k_train_027112 | 8,023 | permissive | [
{
"docstring": "Update parameter and group after __init__. This method is called after the __init__ method to update the parameter and group fields of the ParameterGroup instance.",
"name": "__attrs_post_init__",
"signature": "def __attrs_post_init__(self) -> None"
},
{
"docstring": "Retrieve th... | 5 | null | Implement the Python class `ParameterGroup` described below.
Class description:
A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent Pa... | Implement the Python class `ParameterGroup` described below.
Class description:
A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent Pa... | 80454808b38727e358e8b880043eeac0f18152fb | <|skeleton|>
class ParameterGroup:
"""A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent ParameterGroup instance. Attributes: head... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterGroup:
"""A group of configuration elements. Parameters living within the parameter group are typed attrs Attributes. The schema for each parameter is defined in its metadata, which can be retrieved using the `get_metadata` method from the parent ParameterGroup instance. Attributes: header (str): Use... | the_stack_v2_python_sparse | src/otx/api/configuration/elements/parameter_group.py | openvinotoolkit/training_extensions | train | 397 |
fc3bdc4a772dc33b0e34c1f6979fd5325a535f05 | [
"start_time = select_update_time('shfe') + 57600\nwhile start_time < self.today_time:\n start_time += 86400\n yield scrapy.Request(self.url.format(date=time.strftime('%Y%m%d', time.localtime(start_time))), callback=self.parse, meta={'time': start_time})",
"if response.status == 404:\n return\nitem = Data... | <|body_start_0|>
start_time = select_update_time('shfe') + 57600
while start_time < self.today_time:
start_time += 86400
yield scrapy.Request(self.url.format(date=time.strftime('%Y%m%d', time.localtime(start_time))), callback=self.parse, meta={'time': start_time})
<|end_body_0|>
... | ShfeSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShfeSpider:
def start_requests(self):
"""初始时间为:2002-01-07 16:00:00"""
<|body_0|>
def parse(self, response):
"""判断当天是否有数据 并解析提取数据"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start_time = select_update_time('shfe') + 57600
while start_time... | stack_v2_sparse_classes_36k_train_027113 | 2,377 | no_license | [
{
"docstring": "初始时间为:2002-01-07 16:00:00",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "判断当天是否有数据 并解析提取数据",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016250 | Implement the Python class `ShfeSpider` described below.
Class description:
Implement the ShfeSpider class.
Method signatures and docstrings:
- def start_requests(self): 初始时间为:2002-01-07 16:00:00
- def parse(self, response): 判断当天是否有数据 并解析提取数据 | Implement the Python class `ShfeSpider` described below.
Class description:
Implement the ShfeSpider class.
Method signatures and docstrings:
- def start_requests(self): 初始时间为:2002-01-07 16:00:00
- def parse(self, response): 判断当天是否有数据 并解析提取数据
<|skeleton|>
class ShfeSpider:
def start_requests(self):
"""初... | 2c6caa7af8fce32ecf04eb8d159df9b05e00c368 | <|skeleton|>
class ShfeSpider:
def start_requests(self):
"""初始时间为:2002-01-07 16:00:00"""
<|body_0|>
def parse(self, response):
"""判断当天是否有数据 并解析提取数据"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShfeSpider:
def start_requests(self):
"""初始时间为:2002-01-07 16:00:00"""
start_time = select_update_time('shfe') + 57600
while start_time < self.today_time:
start_time += 86400
yield scrapy.Request(self.url.format(date=time.strftime('%Y%m%d', time.localtime(start_t... | the_stack_v2_python_sparse | Data/spiders/shfeSpider.py | zhuce2022/Financial_data_crawler | train | 0 | |
f12a6e0721fac97c3349c5cd1e3a15f51400b75f | [
"logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.local_data['temperature'] = 0.0\nself._global_temp = 15.0\nself._fire_temp = 200.0\nscene = bge.logic.getCurrentScene()\nscript_empty_name = 'Scene_Script_Holder'\nscript_empty = scene.objects[script_empty_name]\ns... | <|body_start_0|>
logger.info('%s initialization' % obj.name)
super(self.__class__, self).__init__(obj, parent)
self.local_data['temperature'] = 0.0
self._global_temp = 15.0
self._fire_temp = 200.0
scene = bge.logic.getCurrentScene()
script_empty_name = 'Scene_Scri... | Class definition for the gyroscope sensor. Sub class of Morse_Object. | ThermometerClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThermometerClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0... | stack_v2_sparse_classes_36k_train_027114 | 2,343 | permissive | [
{
"docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.",
"name": "__init__",
"signature": "def __init__(self, obj, parent=None)"
},
{
"docstring": "Compute the local temperature Temperature is measured dep... | 2 | null | Implement the Python class `ThermometerClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter shoul... | Implement the Python class `ThermometerClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter shoul... | 07fcb64fea3b58b258e917eb1aed0a585f863418 | <|skeleton|>
class ThermometerClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThermometerClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
logger.info('%s initi... | the_stack_v2_python_sparse | src/morse/sensors/thermometer.py | DefaultUser/morse | train | 2 |
58ea64943f01258f862d43f0205e6793605a8ad8 | [
"left, right = (0, len(A) - 1)\nwhile left < right and A[left] < A[left + 1]:\n left += 1\nwhile right > 0 and A[right] < A[right - 1]:\n right -= 1\nreturn 0 < left == right < len(A) - 1",
"i = 0\nwhile i + 1 < len(A) and A[i] < A[i + 1]:\n i += 1\nif i == len(A) - 1 or i == 0:\n return False\nwhile ... | <|body_start_0|>
left, right = (0, len(A) - 1)
while left < right and A[left] < A[left + 1]:
left += 1
while right > 0 and A[right] < A[right - 1]:
right -= 1
return 0 < left == right < len(A) - 1
<|end_body_0|>
<|body_start_1|>
i = 0
while i + 1 ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
<|body_0|>
def validMountainArray2(A: List[int]) -> bool:
"""先找到峰顶 :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left, right = (0, len(A) - ... | stack_v2_sparse_classes_36k_train_027115 | 973 | no_license | [
{
"docstring": "双指针找峰顶 :param A: :return:",
"name": "validMountainArray",
"signature": "def validMountainArray(A: List[int]) -> bool"
},
{
"docstring": "先找到峰顶 :param A: :return:",
"name": "validMountainArray2",
"signature": "def validMountainArray2(A: List[int]) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(A: List[int]) -> bool: 双指针找峰顶 :param A: :return:
- def validMountainArray2(A: List[int]) -> bool: 先找到峰顶 :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def validMountainArray(A: List[int]) -> bool: 双指针找峰顶 :param A: :return:
- def validMountainArray2(A: List[int]) -> bool: 先找到峰顶 :param A: :return:
<|skeleton|>
class Solution:
... | 578cacff5851c5c2522981693c34e3c318002d30 | <|skeleton|>
class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
<|body_0|>
def validMountainArray2(A: List[int]) -> bool:
"""先找到峰顶 :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def validMountainArray(A: List[int]) -> bool:
"""双指针找峰顶 :param A: :return:"""
left, right = (0, len(A) - 1)
while left < right and A[left] < A[left + 1]:
left += 1
while right > 0 and A[right] < A[right - 1]:
right -= 1
return 0 < left ... | the_stack_v2_python_sparse | 有效的山脉数组.py | cjrzs/MyLeetCode | train | 8 | |
1062d7484b87e0873da468894b0da2d10ae1bd94 | [
"pool = threadpool.ThreadPool(4)\npool.addWork(Job(1))\npool.addWork(Job(2))\npool.addWork(Job(3))\npool.addWork(Job(4))\npool.addWork(Job(5))\npool.addWork(Job(6))\npool.wait()",
"exceptions = []\n\ndef handle_exception(request, exc_info):\n \"\"\"handle Exception\"\"\"\n _logger.debug('Exception occured i... | <|body_start_0|>
pool = threadpool.ThreadPool(4)
pool.addWork(Job(1))
pool.addWork(Job(2))
pool.addWork(Job(3))
pool.addWork(Job(4))
pool.addWork(Job(5))
pool.addWork(Job(6))
pool.wait()
<|end_body_0|>
<|body_start_1|>
exceptions = []
def... | TestThreadPool: sets up 6 jobs and clears them down again. | TestThreadPool | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestThreadPool:
"""TestThreadPool: sets up 6 jobs and clears them down again."""
def test_thread_pool(self):
"""Test the thread pool."""
<|body_0|>
def test_thread_pool_leaving(self):
"""Test the thread pool when exception happens."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_027116 | 2,900 | no_license | [
{
"docstring": "Test the thread pool.",
"name": "test_thread_pool",
"signature": "def test_thread_pool(self)"
},
{
"docstring": "Test the thread pool when exception happens.",
"name": "test_thread_pool_leaving",
"signature": "def test_thread_pool_leaving(self)"
}
] | 2 | null | Implement the Python class `TestThreadPool` described below.
Class description:
TestThreadPool: sets up 6 jobs and clears them down again.
Method signatures and docstrings:
- def test_thread_pool(self): Test the thread pool.
- def test_thread_pool_leaving(self): Test the thread pool when exception happens. | Implement the Python class `TestThreadPool` described below.
Class description:
TestThreadPool: sets up 6 jobs and clears them down again.
Method signatures and docstrings:
- def test_thread_pool(self): Test the thread pool.
- def test_thread_pool_leaving(self): Test the thread pool when exception happens.
<|skeleto... | f458a4ce83f74d603362fe6b71eaa647ccc62fee | <|skeleton|>
class TestThreadPool:
"""TestThreadPool: sets up 6 jobs and clears them down again."""
def test_thread_pool(self):
"""Test the thread pool."""
<|body_0|>
def test_thread_pool_leaving(self):
"""Test the thread pool when exception happens."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestThreadPool:
"""TestThreadPool: sets up 6 jobs and clears them down again."""
def test_thread_pool(self):
"""Test the thread pool."""
pool = threadpool.ThreadPool(4)
pool.addWork(Job(1))
pool.addWork(Job(2))
pool.addWork(Job(3))
pool.addWork(Job(4))
... | the_stack_v2_python_sparse | buildframework/helium/sf/python/pythoncore/lib/pythoncoretests/test_threadpool.py | anagovitsyn/oss.FCL.sftools.dev.build | train | 0 |
c105ef4c88111f5b6d549b27f97305e1e3ca9854 | [
"if self.request.method in ('PUT', 'PATCH'):\n return (permissions.IsAuthenticated(), IsProfileOwner())\nreturn tuple()",
"if self.request.user.is_authenticated:\n return UserSerializer\nreturn LimitedUserSerializer",
"queryset = self.filter_queryset(self.get_queryset())\nif self.request.user.is_authentic... | <|body_start_0|>
if self.request.method in ('PUT', 'PATCH'):
return (permissions.IsAuthenticated(), IsProfileOwner())
return tuple()
<|end_body_0|>
<|body_start_1|>
if self.request.user.is_authenticated:
return UserSerializer
return LimitedUserSerializer
<|end_bo... | User view set | UserViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserViewSet:
"""User view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List users"""
<|body_2|>
... | stack_v2_sparse_classes_36k_train_027117 | 9,286 | permissive | [
{
"docstring": "Get permissions",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "Get serializer class",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "List users",
"name": "list",
"s... | 3 | stack_v2_sparse_classes_30k_train_003435 | Implement the Python class `UserViewSet` described below.
Class description:
User view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List users | Implement the Python class `UserViewSet` described below.
Class description:
User view set
Method signatures and docstrings:
- def get_permissions(self): Get permissions
- def get_serializer_class(self): Get serializer class
- def list(self, request, *args, **kwargs): List users
<|skeleton|>
class UserViewSet:
"... | cf429f43251ad7e77c0d9bc9fe91bb030ca8bae8 | <|skeleton|>
class UserViewSet:
"""User view set"""
def get_permissions(self):
"""Get permissions"""
<|body_0|>
def get_serializer_class(self):
"""Get serializer class"""
<|body_1|>
def list(self, request, *args, **kwargs):
"""List users"""
<|body_2|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserViewSet:
"""User view set"""
def get_permissions(self):
"""Get permissions"""
if self.request.method in ('PUT', 'PATCH'):
return (permissions.IsAuthenticated(), IsProfileOwner())
return tuple()
def get_serializer_class(self):
"""Get serializer class"""... | the_stack_v2_python_sparse | user/views.py | 810Teams/clubs-and-events-backend | train | 3 |
ae48090cc176e09bb9942e72589575bd42c758f7 | [
"if cls.instrument_category is not None:\n inst_klass = cls.instrument_category\n for essential in inst_klass.essentialMethods + inst_klass.essentialProperties:\n if essential not in dir(cls):\n raise IncompleteClass(cls.__name__ + ' does not implement {}, '.format(essential) + 'which is ess... | <|body_start_0|>
if cls.instrument_category is not None:
inst_klass = cls.instrument_category
for essential in inst_klass.essentialMethods + inst_klass.essentialProperties:
if essential not in dir(cls):
raise IncompleteClass(cls.__name__ + ' does not i... | Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, providing some early protection against bad drivers, like this: :py:func:`~tests.t... | DriverMeta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DriverMeta:
"""Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, providing some early protection against bad ... | stack_v2_sparse_classes_36k_train_027118 | 7,955 | permissive | [
{
"docstring": "Checks that it satisfies the API of its Instrument. This occurs at compile-time",
"name": "__init__",
"signature": "def __init__(cls, name, bases, dct)"
},
{
"docstring": "All \\\\*args go to the driver. name and address go to both. kwargs go priority to driver bases, otherwise t... | 2 | stack_v2_sparse_classes_30k_train_005317 | Implement the Python class `DriverMeta` described below.
Class description:
Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, provi... | Implement the Python class `DriverMeta` described below.
Class description:
Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, provi... | e3e261cb77b6ff0f8a4110d083f1392dac365b29 | <|skeleton|>
class DriverMeta:
"""Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, providing some early protection against bad ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DriverMeta:
"""Driver initializer returns an instrument in ``instrument_category``, not an instance of the Driver itself, unless * ``instrument_category`` is None * ``directInit=True`` is passed in Also checks that the API is satistied at compile time, providing some early protection against bad drivers, like... | the_stack_v2_python_sparse | lightlab/equipment/visa_bases/visa_driver.py | lightwave-lab/lightlab | train | 37 |
2eee349dcf4062a89ecfa57592f26d3732cab261 | [
"outputs = self._build_rnn(**kwargs)\nx_anc, x_pos, x_neg, train, loss, embed_anc, embed_pos, embed_neg = outputs\nself.anchor = x_anc\nself.pos = x_pos\nself.neg = x_neg\nself.embed_anchor = embed_anc\nself.embed_pos = embed_pos\nself.embed_neg = embed_neg\nself.loss = loss\nself.train_step = train\nself.sess = se... | <|body_start_0|>
outputs = self._build_rnn(**kwargs)
x_anc, x_pos, x_neg, train, loss, embed_anc, embed_pos, embed_neg = outputs
self.anchor = x_anc
self.pos = x_pos
self.neg = x_neg
self.embed_anchor = embed_anc
self.embed_pos = embed_pos
self.embed_neg =... | Euclidean distance in embedded responses using RNN. | MetricRNN | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricRNN:
"""Euclidean distance in embedded responses using RNN."""
def __init__(self, sess, **kwargs):
"""Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwargs : arguments for building RNN."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_027119 | 8,278 | permissive | [
{
"docstring": "Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwargs : arguments for building RNN.",
"name": "__init__",
"signature": "def __init__(self, sess, **kwargs)"
},
{
"docstring": "Builds the tensorflow graph for embedd... | 6 | stack_v2_sparse_classes_30k_train_010768 | Implement the Python class `MetricRNN` described below.
Class description:
Euclidean distance in embedded responses using RNN.
Method signatures and docstrings:
- def __init__(self, sess, **kwargs): Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwarg... | Implement the Python class `MetricRNN` described below.
Class description:
Euclidean distance in embedded responses using RNN.
Method signatures and docstrings:
- def __init__(self, sess, **kwargs): Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwarg... | 0dea94bbd54f591d82d95169e33d40bb55b6be94 | <|skeleton|>
class MetricRNN:
"""Euclidean distance in embedded responses using RNN."""
def __init__(self, sess, **kwargs):
"""Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwargs : arguments for building RNN."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetricRNN:
"""Euclidean distance in embedded responses using RNN."""
def __init__(self, sess, **kwargs):
"""Initialize RNN for learning the response metric. Args : sess : Tensorflow session to initialize the model with. **kwargs : arguments for building RNN."""
outputs = self._build_rnn(*... | the_stack_v2_python_sparse | response_model/python/metric_learning/score_fcns/metric_rnn.py | googlearchive/rgc-models | train | 0 |
acb785fbc6765c2190f0fd07fce6f0ee3ca607db | [
"operand = 0\nstk = []\nprev_op = '+'\nfor i, c in enumerate(s):\n if c.isdigit():\n operand = operand * 10 + int(c)\n delimited = c in ('+', '-', '*', '/') or i == len(s) - 1\n if delimited:\n if prev_op == '+':\n cur = operand\n elif prev_op == '-':\n cur = -ope... | <|body_start_0|>
operand = 0
stk = []
prev_op = '+'
for i, c in enumerate(s):
if c.isdigit():
operand = operand * 10 + int(c)
delimited = c in ('+', '-', '*', '/') or i == len(s) - 1
if delimited:
if prev_op == '+':
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""No brackets. Look at previous operand and operator, when finishing scanning current operand."""
<|body_0|>
def calculate_error(self, s: str) -> int:
"""cannot use dictionary, since it is eager evaluation"""
<|b... | stack_v2_sparse_classes_36k_train_027120 | 2,396 | no_license | [
{
"docstring": "No brackets. Look at previous operand and operator, when finishing scanning current operand.",
"name": "calculate",
"signature": "def calculate(self, s: str) -> int"
},
{
"docstring": "cannot use dictionary, since it is eager evaluation",
"name": "calculate_error",
"signa... | 2 | stack_v2_sparse_classes_30k_train_013719 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: No brackets. Look at previous operand and operator, when finishing scanning current operand.
- def calculate_error(self, s: str) -> int: canno... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def calculate(self, s: str) -> int: No brackets. Look at previous operand and operator, when finishing scanning current operand.
- def calculate_error(self, s: str) -> int: canno... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def calculate(self, s: str) -> int:
"""No brackets. Look at previous operand and operator, when finishing scanning current operand."""
<|body_0|>
def calculate_error(self, s: str) -> int:
"""cannot use dictionary, since it is eager evaluation"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def calculate(self, s: str) -> int:
"""No brackets. Look at previous operand and operator, when finishing scanning current operand."""
operand = 0
stk = []
prev_op = '+'
for i, c in enumerate(s):
if c.isdigit():
operand = operand * ... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/227 Basic Calculator II py3.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
1b00e99db6ce038e2a920505a6ae0f4e7bc478a2 | [
"super(TransformerLoss, self).__init__()\nself.use_masking = use_masking\nself.bce_pos_weight = bce_pos_weight",
"if self.use_masking:\n mask = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)\n ys = ys.masked_select(mask)\n after_outs = after_outs.masked_select(mask)\n before_outs = before_outs.m... | <|body_start_0|>
super(TransformerLoss, self).__init__()
self.use_masking = use_masking
self.bce_pos_weight = bce_pos_weight
<|end_body_0|>
<|body_start_1|>
if self.use_masking:
mask = make_non_pad_mask(olens).unsqueeze(-1).to(ys.device)
ys = ys.masked_select(mas... | Loss function module for TTS-Transformer. | TransformerLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Wei... | stack_v2_sparse_classes_36k_train_027121 | 8,366 | permissive | [
{
"docstring": "Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Weight of positive sample of stop token (only for use_masking=True).",
"name": "__init__",
"signature": "def __init__(self, use_maski... | 2 | stack_v2_sparse_classes_30k_train_009818 | Implement the Python class `TransformerLoss` described below.
Class description:
Loss function module for TTS-Transformer.
Method signatures and docstrings:
- def __init__(self, use_masking=True, bce_pos_weight=5.0): Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part i... | Implement the Python class `TransformerLoss` described below.
Class description:
Loss function module for TTS-Transformer.
Method signatures and docstrings:
- def __init__(self, use_masking=True, bce_pos_weight=5.0): Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part i... | 41dc231931907e8c1fa9b85c5263f87163c723a4 | <|skeleton|>
class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Wei... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerLoss:
"""Loss function module for TTS-Transformer."""
def __init__(self, use_masking=True, bce_pos_weight=5.0):
"""Initialize Transformer loss module. Args: use_masking (bool, optional): Whether to mask padded part in loss calculation. bce_pos_weight (float, optional): Weight of positi... | the_stack_v2_python_sparse | modules/loss.py | wangfn/FastSpeech2 | train | 0 |
81a0a6eb752781e8d106a305f2cacf0886660a8f | [
"attr = getattr(cls, name)\nif _.is_list(attr):\n return util.create_validator(lengths=attr, required=required)\nelif _.is_string(attr):\n return util.create_validator(regex=attr, required=required)\nelif _.is_function(attr):\n return attr",
"result = {}\nfor attr_name in _.reject(set(dir(cls)), lambda x... | <|body_start_0|>
attr = getattr(cls, name)
if _.is_list(attr):
return util.create_validator(lengths=attr, required=required)
elif _.is_string(attr):
return util.create_validator(regex=attr, required=required)
elif _.is_function(attr):
return attr
<|end... | Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be validated agains string function - validation... | BaseValidator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be vali... | stack_v2_sparse_classes_36k_train_027122 | 10,196 | permissive | [
{
"docstring": "Creates validation function from given attribute name Args: name (string): Name of attribute required (bool, optional) If false, empty string will be always accepted as valid Returns: function: validation function",
"name": "create",
"signature": "def create(cls, name, required=True)"
... | 2 | stack_v2_sparse_classes_30k_train_020188 | Implement the Python class `BaseValidator` described below.
Class description:
Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max leng... | Implement the Python class `BaseValidator` described below.
Class description:
Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max leng... | a82de1321abab504a0be85497587fa90d75fa62d | <|skeleton|>
class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be vali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseValidator:
"""Base factory class for creating validators for ndb.Model properties To be able to create validator for some property, extending class has to define attribute which has to be one of these: list - with 2 elements, determining min and max length of string regex - which will be validated agains ... | the_stack_v2_python_sparse | main/model/base.py | jajberni/pcse_web | train | 3 |
2a9868e6d79a8d00663e85a595dee930ff76314e | [
"online_minions = list()\noffline_minions = list()\nexpired_minions = list()\nfor minion_obj in minions:\n current_datetime = datetime.datetime.utcnow()\n current_datetime = current_datetime.replace(tzinfo=pytz.utc)\n last_seen = minion_obj.last_seen\n try:\n delta_diff = current_datetime - last_... | <|body_start_0|>
online_minions = list()
offline_minions = list()
expired_minions = list()
for minion_obj in minions:
current_datetime = datetime.datetime.utcnow()
current_datetime = current_datetime.replace(tzinfo=pytz.utc)
last_seen = minion_obj.last... | API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format | AllMinionReport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllMinionReport:
"""API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format"""
def minion_connection_stats(self, minions):
"""To get a list of online, offline and expired minions"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_027123 | 6,377 | no_license | [
{
"docstring": "To get a list of online, offline and expired minions",
"name": "minion_connection_stats",
"signature": "def minion_connection_stats(self, minions)"
},
{
"docstring": "To show the key stats for the minions",
"name": "minion_key_stats",
"signature": "def minion_key_stats(se... | 5 | stack_v2_sparse_classes_30k_train_010998 | Implement the Python class `AllMinionReport` described below.
Class description:
API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format
Method signatures and docstrings:
- def minion_connection_stats(self, minions): To get a list of onl... | Implement the Python class `AllMinionReport` described below.
Class description:
API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format
Method signatures and docstrings:
- def minion_connection_stats(self, minions): To get a list of onl... | 122a172caea82ef660e81a9dfc6377afd731f9cb | <|skeleton|>
class AllMinionReport:
"""API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format"""
def minion_connection_stats(self, minions):
"""To get a list of online, offline and expired minions"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllMinionReport:
"""API to list online, office and expired minions URL http://<hostname>/report/minion/all/ Method: GET Returns data in the following format"""
def minion_connection_stats(self, minions):
"""To get a list of online, offline and expired minions"""
online_minions = list()
... | the_stack_v2_python_sparse | sso/files/gui/sse/report/views.py | nofxrok/headless | train | 1 |
5613ea5f0c521d070cfede68ea2a98d0255c0db8 | [
"super().__init__(coordinator, vehicle)\nself.entity_description = description\nself._attr_unique_id = f'{vehicle.vin}-{description.key}'",
"try:\n await self.entity_description.remote_function(self.vehicle)\nexcept MyBMWAPIError as ex:\n raise HomeAssistantError(ex) from ex\nself.coordinator.async_update_l... | <|body_start_0|>
super().__init__(coordinator, vehicle)
self.entity_description = description
self._attr_unique_id = f'{vehicle.vin}-{description.key}'
<|end_body_0|>
<|body_start_1|>
try:
await self.entity_description.remote_function(self.vehicle)
except MyBMWAPIErr... | Representation of a MyBMW button. | BMWButton | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BMWButton:
"""Representation of a MyBMW button."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
<|body_0|>
async def async_press(self) -> None:
... | stack_v2_sparse_classes_36k_train_027124 | 4,184 | permissive | [
{
"docstring": "Initialize BMW vehicle sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None"
},
{
"docstring": "Press the button.",
"name": "async_press",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_018549 | Implement the Python class `BMWButton` described below.
Class description:
Representation of a MyBMW button.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None: Initialize BMW vehicle sensor.
- async def... | Implement the Python class `BMWButton` described below.
Class description:
Representation of a MyBMW button.
Method signatures and docstrings:
- def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None: Initialize BMW vehicle sensor.
- async def... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class BMWButton:
"""Representation of a MyBMW button."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
<|body_0|>
async def async_press(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BMWButton:
"""Representation of a MyBMW button."""
def __init__(self, coordinator: BMWDataUpdateCoordinator, vehicle: MyBMWVehicle, description: BMWButtonEntityDescription) -> None:
"""Initialize BMW vehicle sensor."""
super().__init__(coordinator, vehicle)
self.entity_description... | the_stack_v2_python_sparse | homeassistant/components/bmw_connected_drive/button.py | home-assistant/core | train | 35,501 |
c6f1d8f18f6bb58b8469fe31665ab3dc27218ea6 | [
"self.min = np.array([-10.0, 1.0])\nself.value = 0.0\nself.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])\nself.n = 2\nself.smooth = False\nself.info = [True, False, False]\nself.latex_name = 'Bukin Function No.6'\nself.latex_type = 'Many Local Minima'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = 100\\\\sqrt{\\\\l... | <|body_start_0|>
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])
self.n = 2
self.smooth = False
self.info = [True, False, False]
self.latex_name = 'Bukin Function No.6'
self.latex_type = 'Many Local M... | Bukin No. 6 Function. | Bukin6 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.do... | stack_v2_sparse_classes_36k_train_027125 | 1,037 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018953 | Implement the Python class `Bukin6` described below.
Class description:
Bukin No. 6 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function. | Implement the Python class `Bukin6` described below.
Class description:
Bukin No. 6 Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
<|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bukin6:
"""Bukin No. 6 Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([-10.0, 1.0])
self.value = 0.0
self.domain = np.array([[-15.0, -5.0], [-3.0, 3.0]])
self.n = 2
self.smooth = False
self.info = [True, False, False]
... | the_stack_v2_python_sparse | ctf/functions2d/bukin_6.py | cntaylor/ctf | train | 1 |
862c8250b34df1a532ee8a8bd5b21dfb8afda9e9 | [
"super().__init__()\nself.out_dim = out_dim\nself.num_heads = num_heads\nself.fc = nn.Linear(in_dim, num_heads * out_dim, bias=False)\nself.attn = get_graph_attention(attn_type, out_dim, num_heads)\nself.neg_sampler = RatioNegativeSampler(neg_sample_ratio)\nself.feat_drop = nn.Dropout(feat_drop)\nself.attn_drop = n... | <|body_start_0|>
super().__init__()
self.out_dim = out_dim
self.num_heads = num_heads
self.fc = nn.Linear(in_dim, num_heads * out_dim, bias=False)
self.attn = get_graph_attention(attn_type, out_dim, num_heads)
self.neg_sampler = RatioNegativeSampler(neg_sample_ratio)
... | SuperGATConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SuperGATConv:
def __init__(self, in_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2, activation=None):
"""SuperGAT层,自监督任务是连接预测 :param in_dim: int 输入特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: st... | stack_v2_sparse_classes_36k_train_027126 | 5,266 | no_license | [
{
"docstring": "SuperGAT层,自监督任务是连接预测 :param in_dim: int 输入特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: str 注意力类型,可选择GO, DP, SD和MX :param neg_sample_ratio: float, optional 负样本边数量占正样本边数量的比例,默认0.5 :param feat_drop: float, optional 输入特征Dropout概率,默认为0 :param attn_drop: float, option... | 3 | stack_v2_sparse_classes_30k_train_010850 | Implement the Python class `SuperGATConv` described below.
Class description:
Implement the SuperGATConv class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2, activation=None): SuperGAT层,自监督任务是连接预测 :... | Implement the Python class `SuperGATConv` described below.
Class description:
Implement the SuperGATConv class.
Method signatures and docstrings:
- def __init__(self, in_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2, activation=None): SuperGAT层,自监督任务是连接预测 :... | b40071dc9f9fb20f081f4ed4944a7b65de919c18 | <|skeleton|>
class SuperGATConv:
def __init__(self, in_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2, activation=None):
"""SuperGAT层,自监督任务是连接预测 :param in_dim: int 输入特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SuperGATConv:
def __init__(self, in_dim, out_dim, num_heads, attn_type, neg_sample_ratio=0.5, feat_drop=0.0, attn_drop=0.0, negative_slope=0.2, activation=None):
"""SuperGAT层,自监督任务是连接预测 :param in_dim: int 输入特征维数 :param out_dim: int 输出特征维数 :param num_heads: int 注意力头数K :param attn_type: str 注意力类型,可选择GO,... | the_stack_v2_python_sparse | gnn/supergat/model.py | deepdumbo/pytorch-tutorial-1 | train | 0 | |
21bfce8435fcdc7d0022851634e888eeba6efd82 | [
"active_objects = self.model.objects.all().annotate(count_albums=Count('albums')).order_by('-count_albums', '-pk')\nfor active_object in active_objects:\n yield (str(active_object.pk), ungettext_lazy('%(item)s (%(count)i album)', '%(item)s (%(count)i albums)', active_object.count_albums) % {'item': smart_text(ac... | <|body_start_0|>
active_objects = self.model.objects.all().annotate(count_albums=Count('albums')).order_by('-count_albums', '-pk')
for active_object in active_objects:
yield (str(active_object.pk), ungettext_lazy('%(item)s (%(count)i album)', '%(item)s (%(count)i albums)', active_object.coun... | Base filter for related objects to published entries. | RelatedPublishedFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelatedPublishedFilter:
"""Base filter for related objects to published entries."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
<|body_0|>
def queryset(self, request, queryset):
"""Return the object's entrie... | stack_v2_sparse_classes_36k_train_027127 | 1,653 | no_license | [
{
"docstring": "Return published objects with the number of entries.",
"name": "lookups",
"signature": "def lookups(self, request, model_admin)"
},
{
"docstring": "Return the object's entries if a value is set.",
"name": "queryset",
"signature": "def queryset(self, request, queryset)"
... | 2 | stack_v2_sparse_classes_30k_val_001000 | Implement the Python class `RelatedPublishedFilter` described below.
Class description:
Base filter for related objects to published entries.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Return published objects with the number of entries.
- def queryset(self, request, queryset): Retur... | Implement the Python class `RelatedPublishedFilter` described below.
Class description:
Base filter for related objects to published entries.
Method signatures and docstrings:
- def lookups(self, request, model_admin): Return published objects with the number of entries.
- def queryset(self, request, queryset): Retur... | d19a07ab4bdee26e5d2ca624f8798edc800993bd | <|skeleton|>
class RelatedPublishedFilter:
"""Base filter for related objects to published entries."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
<|body_0|>
def queryset(self, request, queryset):
"""Return the object's entrie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelatedPublishedFilter:
"""Base filter for related objects to published entries."""
def lookups(self, request, model_admin):
"""Return published objects with the number of entries."""
active_objects = self.model.objects.all().annotate(count_albums=Count('albums')).order_by('-count_albums'... | the_stack_v2_python_sparse | admin/filters.py | virtualGain/django-flickr-gallery | train | 0 |
b16f980cb2face72ae520a466091e66a270bf997 | [
"if 'mirror_hints' not in self._args:\n return\nfunc = lambda attr: attr and any((hint in attr for hint in self._args['mirror_hints']))\nif soup.find_all(href=func) or soup.find_all(src=func):\n raise ParserExclusionError()",
"try:\n return bs4.BeautifulSoup(text, 'lxml')\nexcept ValueError:\n return ... | <|body_start_0|>
if 'mirror_hints' not in self._args:
return
func = lambda attr: attr and any((hint in attr for hint in self._args['mirror_hints']))
if soup.find_all(href=func) or soup.find_all(src=func):
raise ParserExclusionError()
<|end_body_0|>
<|body_start_1|>
... | A parser that can extract the text from an HTML document. | _HTMLParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HTMLParser:
"""A parser that can extract the text from an HTML document."""
def _fail_if_mirror(self, soup):
"""Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in the workers and causes this source to excluded."""
... | stack_v2_sparse_classes_36k_train_027128 | 14,045 | permissive | [
{
"docstring": "Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in the workers and causes this source to excluded.",
"name": "_fail_if_mirror",
"signature": "def _fail_if_mirror(self, soup)"
},
{
"docstring": "Parse some text using ... | 6 | null | Implement the Python class `_HTMLParser` described below.
Class description:
A parser that can extract the text from an HTML document.
Method signatures and docstrings:
- def _fail_if_mirror(self, soup): Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in... | Implement the Python class `_HTMLParser` described below.
Class description:
A parser that can extract the text from an HTML document.
Method signatures and docstrings:
- def _fail_if_mirror(self, soup): Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in... | 9ee44932f6e9afeb0e5eb4bd01f3bc88fdb00790 | <|skeleton|>
class _HTMLParser:
"""A parser that can extract the text from an HTML document."""
def _fail_if_mirror(self, soup):
"""Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in the workers and causes this source to excluded."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _HTMLParser:
"""A parser that can extract the text from an HTML document."""
def _fail_if_mirror(self, soup):
"""Look for obvious signs that the given soup is a wiki mirror. If so, raise ParserExclusionError, which is caught in the workers and causes this source to excluded."""
if 'mirror... | the_stack_v2_python_sparse | earwigbot/wiki/copyvios/parsers.py | earwig/earwigbot | train | 23 |
62e5a501a1d62b366038b9a0a3695f1bcfc8cef0 | [
"if not root:\n return root\nroot.left, root.right = (root.right, root.left)\nself.invertTree(root.left)\nself.invertTree(root.right)\nreturn root",
"if not root:\n return root\nself.invertTree(root.left)\nroot.left, root.right = (root.right, root.left)\nself.invertTree(root.right)\nreturn root"
] | <|body_start_0|>
if not root:
return root
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
<|end_body_0|>
<|body_start_1|>
if not root:
return root
self.invertTree(root.left... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
<|body_0|>
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:中序遍历 关键:将每个点的左右子节点交换"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_027129 | 1,754 | no_license | [
{
"docstring": "思路:先序遍历 关键:将每个点的左右子节点交换",
"name": "invertTree",
"signature": "def invertTree(self, root: TreeNode) -> TreeNode"
},
{
"docstring": "思路:中序遍历 关键:将每个点的左右子节点交换",
"name": "invertTree",
"signature": "def invertTree(self, root: TreeNode) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_015315 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:先序遍历 关键:将每个点的左右子节点交换
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:中序遍历 关键:将每个点的左右子节点交换 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:先序遍历 关键:将每个点的左右子节点交换
- def invertTree(self, root: TreeNode) -> TreeNode: 思路:中序遍历 关键:将每个点的左右子节点交换
<|skeleton|>
class Solution... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
<|body_0|>
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:中序遍历 关键:将每个点的左右子节点交换"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
"""思路:先序遍历 关键:将每个点的左右子节点交换"""
if not root:
return root
root.left, root.right = (root.right, root.left)
self.invertTree(root.left)
self.invertTree(root.right)
return root
def invertTree(... | the_stack_v2_python_sparse | LeetCode/树(Binary Tree)/226. 翻转二叉树.py | yiming1012/MyLeetCode | train | 2 | |
94d80eee91f6060a17a57aee20e286d0bde3e879 | [
"self.num = num\nself.name = name\nself.values = values\nself.size = len(self.values)\nself.limits = (values.min(), values.max())\nself.min, self.max = self.limits\nself.range = self.max - self.min\nself.dx = np.diff(values)[0]\nsplit_name = self.name.split('_')\nif split_name[0] == 'spectrum':\n self.basename =... | <|body_start_0|>
self.num = num
self.name = name
self.values = values
self.size = len(self.values)
self.limits = (values.min(), values.max())
self.min, self.max = self.limits
self.range = self.max - self.min
self.dx = np.diff(values)[0]
split_name ... | GridAxis | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridAxis:
def __init__(self, name=None, num=None, values=None):
"""Initialize GridAxis object. Parameters ----------"""
<|body_0|>
def locate(self, val, tol=0.0):
"""Return index of axis value closest to supplied value."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_027130 | 17,232 | permissive | [
{
"docstring": "Initialize GridAxis object. Parameters ----------",
"name": "__init__",
"signature": "def __init__(self, name=None, num=None, values=None)"
},
{
"docstring": "Return index of axis value closest to supplied value.",
"name": "locate",
"signature": "def locate(self, val, tol... | 2 | null | Implement the Python class `GridAxis` described below.
Class description:
Implement the GridAxis class.
Method signatures and docstrings:
- def __init__(self, name=None, num=None, values=None): Initialize GridAxis object. Parameters ----------
- def locate(self, val, tol=0.0): Return index of axis value closest to su... | Implement the Python class `GridAxis` described below.
Class description:
Implement the GridAxis class.
Method signatures and docstrings:
- def __init__(self, name=None, num=None, values=None): Initialize GridAxis object. Parameters ----------
- def locate(self, val, tol=0.0): Return index of axis value closest to su... | f323300b56ae61fab56eda1e5179cfc991eaa74f | <|skeleton|>
class GridAxis:
def __init__(self, name=None, num=None, values=None):
"""Initialize GridAxis object. Parameters ----------"""
<|body_0|>
def locate(self, val, tol=0.0):
"""Return index of axis value closest to supplied value."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridAxis:
def __init__(self, name=None, num=None, values=None):
"""Initialize GridAxis object. Parameters ----------"""
self.num = num
self.name = name
self.values = values
self.size = len(self.values)
self.limits = (values.min(), values.max())
self.min,... | the_stack_v2_python_sparse | ares/inference/GridND.py | mirochaj/ares | train | 16 | |
50fa60b10976f3693c1c4b7d8fb71238856a3b9d | [
"res = []\nfor i in range(len(words)):\n for j in range(len(words)):\n if i != j:\n temp = words[i] + words[j]\n if temp == temp[::-1]:\n res.append([i, j])\nreturn res",
"def isPalindrome(temp):\n return temp == temp[::-1]\ndict, res = ({}, [])\nfor i in range(le... | <|body_start_0|>
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == temp[::-1]:
res.append([i, j])
return res
<|end_body_0|>
<|body_start_1|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r... | stack_v2_sparse_classes_36k_train_027131 | 2,198 | no_license | [
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol1",
"signature": "def palindromePairsSol1(self, words)"
},
{
"docstring": ":type words: List[str] :rtype: List[List[int]]",
"name": "palindromePairsSol2",
"signature": "def palindromePairsSol2(sel... | 2 | stack_v2_sparse_classes_30k_val_001077 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def palindromePairsSol1(self, words): :type words: List[str] :rtype: List[List[int]]
- def palindromePairsSol2(self, words): :type words: List[str] :rtype: List[List[int]]
<|ske... | 7fa160362ebb58e7286b490012542baa2d51e5c9 | <|skeleton|>
class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_0|>
def palindromePairsSol2(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def palindromePairsSol1(self, words):
""":type words: List[str] :rtype: List[List[int]]"""
res = []
for i in range(len(words)):
for j in range(len(words)):
if i != j:
temp = words[i] + words[j]
if temp == tem... | the_stack_v2_python_sparse | google/hard/palindrome_pairs.py | gerrycfchang/leetcode-python | train | 2 | |
6fbbd1793932b45b7bd25d66e41fa77cc69801d4 | [
"dd_1 = Counter(nums1)\ndd_2 = Counter(nums2)\nres = []\nfor k in dd_1:\n if k in dd_2:\n res.extend([k] * min(dd_1[k], dd_2[k]))\nreturn res",
"dd_1 = Counter(nums1)\nres = []\nfor k in nums2:\n if k in dd_1 and dd_1[k] != 0:\n res.append(k)\n dd_1[k] -= 1\nreturn res"
] | <|body_start_0|>
dd_1 = Counter(nums1)
dd_2 = Counter(nums2)
res = []
for k in dd_1:
if k in dd_2:
res.extend([k] * min(dd_1[k], dd_2[k]))
return res
<|end_body_0|>
<|body_start_1|>
dd_1 = Counter(nums1)
res = []
for k in nums2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_027132 | 1,450 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect",
"signature": "def intersect(self, nums1, nums2)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: List[int]",
"name": "intersect1",
"signature": "def intersect1(... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect1(self, nums1, nums2): :type nums1: List[int] :type nums2: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: List[int]
- def intersect1(self, nums1, nums2): :type nums1: List[int] :type nums2: List[... | c55b0cfd2967a2221c27ed738e8de15034775945 | <|skeleton|>
class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_0|>
def intersect1(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: List[int]"""
dd_1 = Counter(nums1)
dd_2 = Counter(nums2)
res = []
for k in dd_1:
if k in dd_2:
res.extend([k] * min(dd_1[k], dd_2[k]))
... | the_stack_v2_python_sparse | PycharmProjects/leetcode/Find/IntersectionofTwoArraysII350.py | crystal30/DataStructure | train | 0 | |
3498d556b10af91a07b7551e2c2947717e1eac27 | [
"super().__init__(CheatMAB(*args, **kwargs))\nself.observation_space = Discrete(2)\nself._last_reward = False",
"s, r, done, info = super().step(action)\nself._last_reward = r > 0.0\nreturn (int(self._last_reward), r, done, info)"
] | <|body_start_0|>
super().__init__(CheatMAB(*args, **kwargs))
self.observation_space = Discrete(2)
self._last_reward = False
<|end_body_0|>
<|body_start_1|>
s, r, done, info = super().step(action)
self._last_reward = r > 0.0
return (int(self._last_reward), r, done, info)
... | Non-Markovian CheatMAB. | NonMarkovianCheatMAB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonMarkovianCheatMAB:
"""Non-Markovian CheatMAB."""
def __init__(self, *args, **kwargs):
"""Initialize a non-Markovian sequential MAB."""
<|body_0|>
def step(self, action):
"""Do a step."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__... | stack_v2_sparse_classes_36k_train_027133 | 3,255 | no_license | [
{
"docstring": "Initialize a non-Markovian sequential MAB.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Do a step.",
"name": "step",
"signature": "def step(self, action)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000195 | Implement the Python class `NonMarkovianCheatMAB` described below.
Class description:
Non-Markovian CheatMAB.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a non-Markovian sequential MAB.
- def step(self, action): Do a step. | Implement the Python class `NonMarkovianCheatMAB` described below.
Class description:
Non-Markovian CheatMAB.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Initialize a non-Markovian sequential MAB.
- def step(self, action): Do a step.
<|skeleton|>
class NonMarkovianCheatMAB:
"""Non-Ma... | b516ffa46e9df6a67fbda7546f9128c23920c460 | <|skeleton|>
class NonMarkovianCheatMAB:
"""Non-Markovian CheatMAB."""
def __init__(self, *args, **kwargs):
"""Initialize a non-Markovian sequential MAB."""
<|body_0|>
def step(self, action):
"""Do a step."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NonMarkovianCheatMAB:
"""Non-Markovian CheatMAB."""
def __init__(self, *args, **kwargs):
"""Initialize a non-Markovian sequential MAB."""
super().__init__(CheatMAB(*args, **kwargs))
self.observation_space = Discrete(2)
self._last_reward = False
def step(self, action):... | the_stack_v2_python_sparse | src/envs/cheat_mab.py | marcofavorito/PAC-RDPs-code | train | 2 |
d8c3ec2856565c7c3d6dc5ffdb82bbc44b2bec8f | [
"self.students = []\nself.grades = {}\nself.isSorted = True",
"if student in self.students:\n raise ValueError('Duplicate student')\nself.students.append(student)\nself.grades[student.getNum()] = []\nself.isSorted = False",
"try:\n self.grades[student.getNum()].append(grade)\nexcept KeyError:\n raise V... | <|body_start_0|>
self.students = []
self.grades = {}
self.isSorted = True
<|end_body_0|>
<|body_start_1|>
if student in self.students:
raise ValueError('Duplicate student')
self.students.append(student)
self.grades[student.getNum()] = []
self.isSorted... | A mapping from students to a list of grades | Grades | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Creat empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade book"""
<|body_1|>
def addGrade(self,... | stack_v2_sparse_classes_36k_train_027134 | 4,596 | no_license | [
{
"docstring": "Creat empty grade book",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Assumes: student is of type Student Add student to the grade book",
"name": "addStudent",
"signature": "def addStudent(self, student)"
},
{
"docstring": "Assumes: gra... | 5 | stack_v2_sparse_classes_30k_train_006204 | Implement the Python class `Grades` described below.
Class description:
A mapping from students to a list of grades
Method signatures and docstrings:
- def __init__(self): Creat empty grade book
- def addStudent(self, student): Assumes: student is of type Student Add student to the grade book
- def addGrade(self, stu... | Implement the Python class `Grades` described below.
Class description:
A mapping from students to a list of grades
Method signatures and docstrings:
- def __init__(self): Creat empty grade book
- def addStudent(self, student): Assumes: student is of type Student Add student to the grade book
- def addGrade(self, stu... | b72144c258d07915936908214ec0a1bcd8a0c56a | <|skeleton|>
class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Creat empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade book"""
<|body_1|>
def addGrade(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Creat empty grade book"""
self.students = []
self.grades = {}
self.isSorted = True
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade b... | the_stack_v2_python_sparse | class_inheritance.py | aduxhi/learnpython | train | 0 |
859643e7301dfffd401aebe600e53595571d4ba4 | [
"self.frameHeight, self.frameWidth, channels = image.shape\nself.widthDivisor = int(self.frameWidth / appConfig.camera['resizeWidthDiv'])\nif self.widthDivisor < 1:\n self.widthDivisor = 1\nself.frameResizeWidth = int(self.frameWidth / self.widthDivisor)\nself.frameResizeHeight = int(self.frameHeight / self.widt... | <|body_start_0|>
self.frameHeight, self.frameWidth, channels = image.shape
self.widthDivisor = int(self.frameWidth / appConfig.camera['resizeWidthDiv'])
if self.widthDivisor < 1:
self.widthDivisor = 1
self.frameResizeWidth = int(self.frameWidth / self.widthDivisor)
se... | Detect abstract base class. Common functions for detectors. | detectbase | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class detectbase:
"""Detect abstract base class. Common functions for detectors."""
def frameInfo(self, image, appConfig):
"""Set common frame info"""
<|body_0|>
def inside(self, r, q):
"""See if one rectangle inside another"""
<|body_1|>
def markRectSize(... | stack_v2_sparse_classes_36k_train_027135 | 2,254 | permissive | [
{
"docstring": "Set common frame info",
"name": "frameInfo",
"signature": "def frameInfo(self, image, appConfig)"
},
{
"docstring": "See if one rectangle inside another",
"name": "inside",
"signature": "def inside(self, r, q)"
},
{
"docstring": "Mark rectangles in image",
"na... | 3 | stack_v2_sparse_classes_30k_train_011191 | Implement the Python class `detectbase` described below.
Class description:
Detect abstract base class. Common functions for detectors.
Method signatures and docstrings:
- def frameInfo(self, image, appConfig): Set common frame info
- def inside(self, r, q): See if one rectangle inside another
- def markRectSize(self... | Implement the Python class `detectbase` described below.
Class description:
Detect abstract base class. Common functions for detectors.
Method signatures and docstrings:
- def frameInfo(self, image, appConfig): Set common frame info
- def inside(self, r, q): See if one rectangle inside another
- def markRectSize(self... | a5af3a96d8d465bcbb7a77578f56b2e3e0ad680b | <|skeleton|>
class detectbase:
"""Detect abstract base class. Common functions for detectors."""
def frameInfo(self, image, appConfig):
"""Set common frame info"""
<|body_0|>
def inside(self, r, q):
"""See if one rectangle inside another"""
<|body_1|>
def markRectSize(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class detectbase:
"""Detect abstract base class. Common functions for detectors."""
def frameInfo(self, image, appConfig):
"""Set common frame info"""
self.frameHeight, self.frameWidth, channels = image.shape
self.widthDivisor = int(self.frameWidth / appConfig.camera['resizeWidthDiv'])
... | the_stack_v2_python_sparse | codeferm/detectbase.py | sanderginn/motiondetector | train | 0 |
c16005703e57c5d1e2cc81c7ebb7ba49406a221c | [
"control_samples = self._sample_data[column].dropna()\nnew_values = self._values.copy()\nfor sample, ctrl in dict(control_samples).items():\n mask = self._call_mask(self._values[ctrl], self._values[sample])\n new_values.loc[~mask, sample] = mask_value\nreturn self._constructor(new_values)",
"ctrl_sign = np.... | <|body_start_0|>
control_samples = self._sample_data[column].dropna()
new_values = self._values.copy()
for sample, ctrl in dict(control_samples).items():
mask = self._call_mask(self._values[ctrl], self._values[sample])
new_values.loc[~mask, sample] = mask_value
re... | Cnv matrix containing CNV calls (genes-by-samples). | CnvCallMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme... | stack_v2_sparse_classes_36k_train_027136 | 5,483 | no_license | [
{
"docstring": "Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme than the control sample or (c) the sample and control have calls with different signs (loss/gain). Matched control samples should be indicate... | 2 | stack_v2_sparse_classes_30k_train_002241 | Implement the Python class `CnvCallMatrix` described below.
Class description:
Cnv matrix containing CNV calls (genes-by-samples).
Method signatures and docstrings:
- def mask_with_controls(self, column, mask_value=0.0): Masks calls present in control samples. Calls are retained if (a) no call is present in the match... | Implement the Python class `CnvCallMatrix` described below.
Class description:
Cnv matrix containing CNV calls (genes-by-samples).
Method signatures and docstrings:
- def mask_with_controls(self, column, mask_value=0.0): Masks calls present in control samples. Calls are retained if (a) no call is present in the match... | f02c5d0232003c15a571fcadb528268bd4ff1c5b | <|skeleton|>
class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CnvCallMatrix:
"""Cnv matrix containing CNV calls (genes-by-samples)."""
def mask_with_controls(self, column, mask_value=0.0):
"""Masks calls present in control samples. Calls are retained if (a) no call is present in the matched control sample, (b) if the sample call is more extreme than the con... | the_stack_v2_python_sparse | Coffee2Go/Coffee/Lib/site-packages/genopandas/ngs/cnv.py | FeliciaWilliamson/Coffee2Go | train | 0 |
09deed5c7650ddeb41114645607ccdc3609362a9 | [
"ans = 0\nimport bisect\nages = sorted(ages)\ni = 0\nwhile i < len(ages):\n age = ages[i]\n count = 1\n while i + 1 < len(ages) and ages[i + 1] == age:\n i += 1\n count += 1\n low = 0.5 * age + 7\n pos = bisect.bisect_right(ages[0:i], low)\n ans += (i - pos) * count\n i += 1\nretu... | <|body_start_0|>
ans = 0
import bisect
ages = sorted(ages)
i = 0
while i < len(ages):
age = ages[i]
count = 1
while i + 1 < len(ages) and ages[i + 1] == age:
i += 1
count += 1
low = 0.5 * age + 7
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numFriendRequests(self, ages):
""":type ages: List[int] :rtype: int 202ms"""
<|body_0|>
def numFriendRequests_1(self, ages):
"""433ms :param ages: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = 0
import bisect
... | stack_v2_sparse_classes_36k_train_027137 | 2,018 | no_license | [
{
"docstring": ":type ages: List[int] :rtype: int 202ms",
"name": "numFriendRequests",
"signature": "def numFriendRequests(self, ages)"
},
{
"docstring": "433ms :param ages: :return:",
"name": "numFriendRequests_1",
"signature": "def numFriendRequests_1(self, ages)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFriendRequests(self, ages): :type ages: List[int] :rtype: int 202ms
- def numFriendRequests_1(self, ages): 433ms :param ages: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numFriendRequests(self, ages): :type ages: List[int] :rtype: int 202ms
- def numFriendRequests_1(self, ages): 433ms :param ages: :return:
<|skeleton|>
class Solution:
d... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def numFriendRequests(self, ages):
""":type ages: List[int] :rtype: int 202ms"""
<|body_0|>
def numFriendRequests_1(self, ages):
"""433ms :param ages: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numFriendRequests(self, ages):
""":type ages: List[int] :rtype: int 202ms"""
ans = 0
import bisect
ages = sorted(ages)
i = 0
while i < len(ages):
age = ages[i]
count = 1
while i + 1 < len(ages) and ages[i + 1] ==... | the_stack_v2_python_sparse | FriendsOfAppropriateAges_MID_825.py | 953250587/leetcode-python | train | 2 | |
031d8fa3af0b4fe49a3f09f41d414480858b05f6 | [
"try:\n return parseString(open(path, 'r', encoding='utf-8', errors='ignore').read())\nexcept ExpatError as e:\n log(XmlHandler.ERROR_MESSAGE.format(path, e))\n return XmlHandler.preprocess(path)",
"with open(path, 'r', encoding='utf-8', errors='ignore') as f:\n pat = re.compile('&([^;\\\\W]*([^;\\\\w... | <|body_start_0|>
try:
return parseString(open(path, 'r', encoding='utf-8', errors='ignore').read())
except ExpatError as e:
log(XmlHandler.ERROR_MESSAGE.format(path, e))
return XmlHandler.preprocess(path)
<|end_body_0|>
<|body_start_1|>
with open(path, 'r', e... | Utility class for handling Neutrino xml files. | XmlHandler | [
"MIT",
"GPL-3.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlHandler:
"""Utility class for handling Neutrino xml files."""
def parse(path):
"""Parses a file into the DOM by filename."""
<|body_0|>
def preprocess(path):
"""Pre-processing xml [for '&' symbol] for correct parsing."""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_027138 | 4,467 | permissive | [
{
"docstring": "Parses a file into the DOM by filename.",
"name": "parse",
"signature": "def parse(path)"
},
{
"docstring": "Pre-processing xml [for '&' symbol] for correct parsing.",
"name": "preprocess",
"signature": "def preprocess(path)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006594 | Implement the Python class `XmlHandler` described below.
Class description:
Utility class for handling Neutrino xml files.
Method signatures and docstrings:
- def parse(path): Parses a file into the DOM by filename.
- def preprocess(path): Pre-processing xml [for '&' symbol] for correct parsing. | Implement the Python class `XmlHandler` described below.
Class description:
Utility class for handling Neutrino xml files.
Method signatures and docstrings:
- def parse(path): Parses a file into the DOM by filename.
- def preprocess(path): Pre-processing xml [for '&' symbol] for correct parsing.
<|skeleton|>
class X... | 917e184486ff212b4a19b36ab726343f900da8b7 | <|skeleton|>
class XmlHandler:
"""Utility class for handling Neutrino xml files."""
def parse(path):
"""Parses a file into the DOM by filename."""
<|body_0|>
def preprocess(path):
"""Pre-processing xml [for '&' symbol] for correct parsing."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlHandler:
"""Utility class for handling Neutrino xml files."""
def parse(path):
"""Parses a file into the DOM by filename."""
try:
return parseString(open(path, 'r', encoding='utf-8', errors='ignore').read())
except ExpatError as e:
log(XmlHandler.ERROR_M... | the_stack_v2_python_sparse | app/eparser/neutrino/nxml.py | DYefremov/DemonEditor | train | 105 |
1a5fb09857bac0628261f119714021d83c0b030f | [
"m = len(enums) // 2\nif m > 0:\n l, r = (self._mergesort(enums[:m]), self._mergesort(enums[m:]))\n for i in range(len(enums) - 1, -1, -1):\n if not r or (l and l[-1][1] > r[-1][1]):\n self.ans[l[-1][0]] += len(r)\n enums[i] = l.pop()\n else:\n enums[i] = r.pop()... | <|body_start_0|>
m = len(enums) // 2
if m > 0:
l, r = (self._mergesort(enums[:m]), self._mergesort(enums[m:]))
for i in range(len(enums) - 1, -1, -1):
if not r or (l and l[-1][1] > r[-1][1]):
self.ans[l[-1][0]] += len(r)
enu... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _mergesort(self, enums):
"""Args enums: (index, value) of nums, index to write back the jumps."""
<|body_0|>
def countSmaller(self, nums: List[int]) -> List[int]:
"""mergesort, num of smaller after is num of right-to-left jump over in merge sort, accumu... | stack_v2_sparse_classes_36k_train_027139 | 1,685 | no_license | [
{
"docstring": "Args enums: (index, value) of nums, index to write back the jumps.",
"name": "_mergesort",
"signature": "def _mergesort(self, enums)"
},
{
"docstring": "mergesort, num of smaller after is num of right-to-left jump over in merge sort, accumulate from each recursion.",
"name": ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _mergesort(self, enums): Args enums: (index, value) of nums, index to write back the jumps.
- def countSmaller(self, nums: List[int]) -> List[int]: mergesort, num of smaller ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _mergesort(self, enums): Args enums: (index, value) of nums, index to write back the jumps.
- def countSmaller(self, nums: List[int]) -> List[int]: mergesort, num of smaller ... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Solution:
def _mergesort(self, enums):
"""Args enums: (index, value) of nums, index to write back the jumps."""
<|body_0|>
def countSmaller(self, nums: List[int]) -> List[int]:
"""mergesort, num of smaller after is num of right-to-left jump over in merge sort, accumu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _mergesort(self, enums):
"""Args enums: (index, value) of nums, index to write back the jumps."""
m = len(enums) // 2
if m > 0:
l, r = (self._mergesort(enums[:m]), self._mergesort(enums[m:]))
for i in range(len(enums) - 1, -1, -1):
... | the_stack_v2_python_sparse | src/0300-0399/0315.count.smaller.after.self.py | gyang274/leetcode | train | 1 | |
78f8e7c459409eeba38c33bf2a5a5aa17ed788c5 | [
"self._queue: multiprocessing.Queue = queue\nself._leq: LogEventQueue = leq\nself._predicate: Callable[[str], bool] = predicate",
"audio_file = event.pathname\nif self._predicate(audio_file):\n self._leq.info('File {0} changed/added, adding it to processing list!'.format(audio_file))\n self._queue.put(audio... | <|body_start_0|>
self._queue: multiprocessing.Queue = queue
self._leq: LogEventQueue = leq
self._predicate: Callable[[str], bool] = predicate
<|end_body_0|>
<|body_start_1|>
audio_file = event.pathname
if self._predicate(audio_file):
self._leq.info('File {0} changed/... | Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..). | DirectoryWatchHandler | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectoryWatchHandler:
"""Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..)."""
def my_init(self, queue: multiprocessing.Queue, leq: LogEventQueue, predicate: Callable[[str], bool]):
... | stack_v2_sparse_classes_36k_train_027140 | 4,840 | permissive | [
{
"docstring": "Keep a handle on the process pool at init time so we can terminate it later if needed :param queue: queue onto which new files will be placed if they qualify as work items. :param leq: instance of LogEventQueue to be used for logging :param predicate: function that qualifies new files as being c... | 2 | stack_v2_sparse_classes_30k_train_006565 | Implement the Python class `DirectoryWatchHandler` described below.
Class description:
Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..).
Method signatures and docstrings:
- def my_init(self, queue: multiprocess... | Implement the Python class `DirectoryWatchHandler` described below.
Class description:
Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..).
Method signatures and docstrings:
- def my_init(self, queue: multiprocess... | 8b0a5492361ff9473ab66c2f64aaccd5340f2f62 | <|skeleton|>
class DirectoryWatchHandler:
"""Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..)."""
def my_init(self, queue: multiprocessing.Queue, leq: LogEventQueue, predicate: Callable[[str], bool]):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectoryWatchHandler:
"""Handler for inotify event for modified/added files in a work directory, such as files corresponding to work items (audio file, image file, text file, etc..)."""
def my_init(self, queue: multiprocessing.Queue, leq: LogEventQueue, predicate: Callable[[str], bool]):
"""Keep... | the_stack_v2_python_sparse | batchkit/handlers.py | microsoft/batch-processing-kit | train | 29 |
3e79601fb9582a89895752f4851208bac731fa8c | [
"allow_speech_tags = [as_text(item) for item in allow_speech_tags]\nself.default_speech_tag_filter = allow_speech_tags\nself.stop_words = set()\nself.stop_words_file = stopwords_path\nif type(stop_words_file) is str:\n self.stop_words_file = stop_words_file\nfor word in codecs.open(self.stop_words_file, 'r', 'ut... | <|body_start_0|>
allow_speech_tags = [as_text(item) for item in allow_speech_tags]
self.default_speech_tag_filter = allow_speech_tags
self.stop_words = set()
self.stop_words_file = stopwords_path
if type(stop_words_file) is str:
self.stop_words_file = stop_words_file
... | WordSegmentation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz']):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
<|body_0|>
def segment(self, text,... | stack_v2_sparse_classes_36k_train_027141 | 20,624 | no_license | [
{
"docstring": "Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤",
"name": "__init__",
"signature": "def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz'])"
},
{
"docstring": "对一段文本进行分... | 3 | null | Implement the Python class `WordSegmentation` described below.
Class description:
Implement the WordSegmentation class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz']): Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一... | Implement the Python class `WordSegmentation` described below.
Class description:
Implement the WordSegmentation class.
Method signatures and docstrings:
- def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz']): Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一... | ca2cf55b4dbae09a3c85689c8dae104908060c86 | <|skeleton|>
class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz']):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
<|body_0|>
def segment(self, text,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordSegmentation:
def __init__(self, stop_words_file=None, allow_speech_tags=['an', 'n', 'nt', 'x', 'eng', 'nt', 'nz']):
"""Keyword arguments: stop_words_file -- 保存停止词的文件路径,utf8编码,每行一个停止词。若不是str类型,则使用默认的停止词 allow_speech_tags -- 词性列表,用于过滤"""
allow_speech_tags = [as_text(item) for item in allow_... | the_stack_v2_python_sparse | owner/吴伟/keyword_extraction.py | dxcv/GsEnv | train | 0 | |
85f47f0d3e6a9c0418d427d00de354e8fc2f4223 | [
"self.plugin = OrographicEnhancement()\ntopography = set_up_orography_cube(np.zeros((3, 4), dtype=np.float32))\nself.plugin.topography = sort_coord_in_cube(topography, topography.coord(axis='y'))\nt_attributes = {'institution': 'Met Office', 'source': 'Met Office Unified Model', 'mosg__grid_type': 'standard', 'mosg... | <|body_start_0|>
self.plugin = OrographicEnhancement()
topography = set_up_orography_cube(np.zeros((3, 4), dtype=np.float32))
self.plugin.topography = sort_coord_in_cube(topography, topography.coord(axis='y'))
t_attributes = {'institution': 'Met Office', 'source': 'Met Office Unified Mod... | Test the _create_output_cube method | Test__create_output_cube | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__create_output_cube:
"""Test the _create_output_cube method"""
def setUp(self):
"""Set up a plugin instance, data array and cubes"""
<|body_0|>
def test_basic(self):
"""Test that the cube is returned with float32 coords"""
<|body_1|>
def test_va... | stack_v2_sparse_classes_36k_train_027142 | 34,979 | permissive | [
{
"docstring": "Set up a plugin instance, data array and cubes",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that the cube is returned with float32 coords",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test the cube is c... | 4 | stack_v2_sparse_classes_30k_train_011266 | Implement the Python class `Test__create_output_cube` described below.
Class description:
Test the _create_output_cube method
Method signatures and docstrings:
- def setUp(self): Set up a plugin instance, data array and cubes
- def test_basic(self): Test that the cube is returned with float32 coords
- def test_values... | Implement the Python class `Test__create_output_cube` described below.
Class description:
Test the _create_output_cube method
Method signatures and docstrings:
- def setUp(self): Set up a plugin instance, data array and cubes
- def test_basic(self): Test that the cube is returned with float32 coords
- def test_values... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__create_output_cube:
"""Test the _create_output_cube method"""
def setUp(self):
"""Set up a plugin instance, data array and cubes"""
<|body_0|>
def test_basic(self):
"""Test that the cube is returned with float32 coords"""
<|body_1|>
def test_va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test__create_output_cube:
"""Test the _create_output_cube method"""
def setUp(self):
"""Set up a plugin instance, data array and cubes"""
self.plugin = OrographicEnhancement()
topography = set_up_orography_cube(np.zeros((3, 4), dtype=np.float32))
self.plugin.topography = s... | the_stack_v2_python_sparse | improver_tests/orographic_enhancement/test_OrographicEnhancement.py | metoppv/improver | train | 101 |
bd69b5975fd1ee3fc6dd6facff5edead53de0e83 | [
"for i in range(len(nums)):\n for j in range(1, k + 1):\n if i + j < len(nums) and nums[i] == nums[i + j]:\n return True\nreturn False",
"window = set()\nfor i in range(len(nums)):\n if nums[i] in window:\n return True\n window.add(nums[i])\n if len(window) > k:\n windo... | <|body_start_0|>
for i in range(len(nums)):
for j in range(1, k + 1):
if i + j < len(nums) and nums[i] == nums[i + j]:
return True
return False
<|end_body_0|>
<|body_start_1|>
window = set()
for i in range(len(nums)):
if nums[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_027143 | 1,078 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate1",
"signature": "def containsNearbyDuplicate1(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def cont... | 2 | stack_v2_sparse_classes_30k_train_013830 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate1(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rt... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate1(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rt... | 8dfbb10a87d8a3fdde466ab16fff8b67503e41f4 | <|skeleton|>
class Solution:
def containsNearbyDuplicate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def containsNearbyDuplicate1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
for i in range(len(nums)):
for j in range(1, k + 1):
if i + j < len(nums) and nums[i] == nums[i + j]:
return True
return False
... | the_stack_v2_python_sparse | easy/0219.contains-duplicate-II.py | codershenghai/PyLeetcode | train | 0 | |
cb9c469d1df50f59a1b1673c45f39db7aaf992f0 | [
"self.all = False\nself.coverage = False\nsuper(test, self).initialize_options()",
"if self.all:\n cmd = self.apply_options(self.test_all_cmd)\n self.call_and_exit(cmd)\nelse:\n cmds = (self.apply_options(self.unit_test_cmd, ('coverage',)),)\n if self.coverage:\n cmds += (self.apply_options(sel... | <|body_start_0|>
self.all = False
self.coverage = False
super(test, self).initialize_options()
<|end_body_0|>
<|body_start_1|>
if self.all:
cmd = self.apply_options(self.test_all_cmd)
self.call_and_exit(cmd)
else:
cmds = (self.apply_options(se... | Run the test suites for this project. | test | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the test suites."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.all = False
self.covera... | stack_v2_sparse_classes_36k_train_027144 | 3,851 | permissive | [
{
"docstring": "Set the default options.",
"name": "initialize_options",
"signature": "def initialize_options(self)"
},
{
"docstring": "Run the test suites.",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001789 | Implement the Python class `test` described below.
Class description:
Run the test suites for this project.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the test suites. | Implement the Python class `test` described below.
Class description:
Run the test suites for this project.
Method signatures and docstrings:
- def initialize_options(self): Set the default options.
- def run(self): Run the test suites.
<|skeleton|>
class test:
"""Run the test suites for this project."""
de... | 4e2c417f68bc07c72b508e107431569b0783c4ef | <|skeleton|>
class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
<|body_0|>
def run(self):
"""Run the test suites."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test:
"""Run the test suites for this project."""
def initialize_options(self):
"""Set the default options."""
self.all = False
self.coverage = False
super(test, self).initialize_options()
def run(self):
"""Run the test suites."""
if self.all:
... | the_stack_v2_python_sparse | tasks.py | dbcli/cli_helpers | train | 102 |
70aabd6683ba8213f7a634d55b8f376177250505 | [
"url = reverse('category-list')\ndata = {'category': 'S'}\nresponse = self.client.post(url, data, format='json')\nself.assertEqual(response.status_code, status.HTTP_201_CREATED)\nself.assertEqual(Category.objects.count(), 1)\nself.assertEqual(Category.objects.get().category, 'S')",
"url = reverse('category-list')... | <|body_start_0|>
url = reverse('category-list')
data = {'category': 'S'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Category.objects.count(), 1)
self.assertEqual(Category.objects.g... | CategoryRegistrationAPIViewTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
<|body_0|>
def test_error_category(self):
"""Test to verify that a bad post call with category"""
<|body_1|>
def test_two_category(self)... | stack_v2_sparse_classes_36k_train_027145 | 1,595 | no_license | [
{
"docstring": "Test to verify that a post call with category",
"name": "test_one_category",
"signature": "def test_one_category(self)"
},
{
"docstring": "Test to verify that a bad post call with category",
"name": "test_error_category",
"signature": "def test_error_category(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_018332 | Implement the Python class `CategoryRegistrationAPIViewTestCase` described below.
Class description:
Implement the CategoryRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_one_category(self): Test to verify that a post call with category
- def test_error_category(self): Test to verify t... | Implement the Python class `CategoryRegistrationAPIViewTestCase` described below.
Class description:
Implement the CategoryRegistrationAPIViewTestCase class.
Method signatures and docstrings:
- def test_one_category(self): Test to verify that a post call with category
- def test_error_category(self): Test to verify t... | 6b2296994b6db3a828715d2f47b340d84e5b4c84 | <|skeleton|>
class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
<|body_0|>
def test_error_category(self):
"""Test to verify that a bad post call with category"""
<|body_1|>
def test_two_category(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryRegistrationAPIViewTestCase:
def test_one_category(self):
"""Test to verify that a post call with category"""
url = reverse('category-list')
data = {'category': 'S'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, sta... | the_stack_v2_python_sparse | app/categories/tests.py | sergiii24/FitHaus_Backend | train | 0 | |
01c9f97169cc36b84ceb28be27208d19fc3942bb | [
"if not root:\n return 0\nreturn 1 + self.countNodes(root.left) + self.countNodes(root.right)",
"if not root:\n return 0\nq = [root]\ncnt = 1\nwhile q:\n tmp = q.pop()\n if tmp.left:\n q.append(tmp.left)\n cnt += 1\n if tmp.right:\n q.append(tmp.right)\n cnt += 1\nreturn... | <|body_start_0|>
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
<|end_body_0|>
<|body_start_1|>
if not root:
return 0
q = [root]
cnt = 1
while q:
tmp = q.pop()
if tmp.left:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countNodes(self, root):
"""brute force recursive, TLE :type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes2(self, root):
"""brute force iteration, TLE :param root: :return:"""
<|body_1|>
def countNode3(self, root):
"""cuz i... | stack_v2_sparse_classes_36k_train_027146 | 1,338 | no_license | [
{
"docstring": "brute force recursive, TLE :type root: TreeNode :rtype: int",
"name": "countNodes",
"signature": "def countNodes(self, root)"
},
{
"docstring": "brute force iteration, TLE :param root: :return:",
"name": "countNodes2",
"signature": "def countNodes2(self, root)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root): brute force recursive, TLE :type root: TreeNode :rtype: int
- def countNodes2(self, root): brute force iteration, TLE :param root: :return:
- def coun... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countNodes(self, root): brute force recursive, TLE :type root: TreeNode :rtype: int
- def countNodes2(self, root): brute force iteration, TLE :param root: :return:
- def coun... | e16702d2b3ec4e5054baad56f4320bc3b31676ad | <|skeleton|>
class Solution:
def countNodes(self, root):
"""brute force recursive, TLE :type root: TreeNode :rtype: int"""
<|body_0|>
def countNodes2(self, root):
"""brute force iteration, TLE :param root: :return:"""
<|body_1|>
def countNode3(self, root):
"""cuz i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countNodes(self, root):
"""brute force recursive, TLE :type root: TreeNode :rtype: int"""
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
def countNodes2(self, root):
"""brute force iteration, TLE :param r... | the_stack_v2_python_sparse | leetcode/medium/count_complete_tree_nodes.py | SuperMartinYang/learning_algorithm | train | 0 | |
c6ab01ab5c293127d2388c11a1ffc8cdae404dee | [
"qs = FriendshipRequest.objects.select_related('from_user', 'to_user').filter(rejected__isnull=True).filter(to_user=user).all()\nrequests = list(qs)\nreturn requests",
"try:\n return FriendshipRequest.objects.select_related('from_user', 'to_user').filter(to_user=to_user, from_user=from_user).get(rejected__isnu... | <|body_start_0|>
qs = FriendshipRequest.objects.select_related('from_user', 'to_user').filter(rejected__isnull=True).filter(to_user=user).all()
requests = list(qs)
return requests
<|end_body_0|>
<|body_start_1|>
try:
return FriendshipRequest.objects.select_related('from_user... | Friendshiprequest manager | FriendshipRequestManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FriendshipRequestManager:
"""Friendshiprequest manager"""
def requests(self, user):
"""Return a list of friendship requests"""
<|body_0|>
def get_friendship_request_id(self, to_user, from_user):
"""Is there friend request between user1 and user2"""
<|body... | stack_v2_sparse_classes_36k_train_027147 | 5,408 | no_license | [
{
"docstring": "Return a list of friendship requests",
"name": "requests",
"signature": "def requests(self, user)"
},
{
"docstring": "Is there friend request between user1 and user2",
"name": "get_friendship_request_id",
"signature": "def get_friendship_request_id(self, to_user, from_use... | 3 | stack_v2_sparse_classes_30k_train_016616 | Implement the Python class `FriendshipRequestManager` described below.
Class description:
Friendshiprequest manager
Method signatures and docstrings:
- def requests(self, user): Return a list of friendship requests
- def get_friendship_request_id(self, to_user, from_user): Is there friend request between user1 and us... | Implement the Python class `FriendshipRequestManager` described below.
Class description:
Friendshiprequest manager
Method signatures and docstrings:
- def requests(self, user): Return a list of friendship requests
- def get_friendship_request_id(self, to_user, from_user): Is there friend request between user1 and us... | 371730ba887d41b47d9a7cff1d8ba37d1f96fc94 | <|skeleton|>
class FriendshipRequestManager:
"""Friendshiprequest manager"""
def requests(self, user):
"""Return a list of friendship requests"""
<|body_0|>
def get_friendship_request_id(self, to_user, from_user):
"""Is there friend request between user1 and user2"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FriendshipRequestManager:
"""Friendshiprequest manager"""
def requests(self, user):
"""Return a list of friendship requests"""
qs = FriendshipRequest.objects.select_related('from_user', 'to_user').filter(rejected__isnull=True).filter(to_user=user).all()
requests = list(qs)
... | the_stack_v2_python_sparse | web/project/friendship/models.py | kochnev/Speak-n-Time | train | 0 |
23bb8e671463c4b5c60b4d5ac1b3eee2cc2f1eb4 | [
"self.window = window\nself.wizards = wizards\nwsp = WizardSelectionPage(wizards=wizards, id='wizard_selection')\nwsp.on_trait_change(self.on_wizard_changed, 'wizard')\nself.pages = [wsp]\nsuper(WizardSelectionWizard, self).__init__(**traits)",
"if new is not None:\n app = self.window.application\n wizard_k... | <|body_start_0|>
self.window = window
self.wizards = wizards
wsp = WizardSelectionPage(wizards=wizards, id='wizard_selection')
wsp.on_trait_change(self.on_wizard_changed, 'wizard')
self.pages = [wsp]
super(WizardSelectionWizard, self).__init__(**traits)
<|end_body_0|>
<|... | A wizard for wizard selection. | WizardSelectionWizard | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WizardSelectionWizard:
"""A wizard for wizard selection."""
def __init__(self, window, wizards, **traits):
"""Returns a new WizardSelectionWizard instance."""
<|body_0|>
def on_wizard_changed(self, new):
"""Handles the selected wizard changing."""
<|body_... | stack_v2_sparse_classes_36k_train_027148 | 6,572 | permissive | [
{
"docstring": "Returns a new WizardSelectionWizard instance.",
"name": "__init__",
"signature": "def __init__(self, window, wizards, **traits)"
},
{
"docstring": "Handles the selected wizard changing.",
"name": "on_wizard_changed",
"signature": "def on_wizard_changed(self, new)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007778 | Implement the Python class `WizardSelectionWizard` described below.
Class description:
A wizard for wizard selection.
Method signatures and docstrings:
- def __init__(self, window, wizards, **traits): Returns a new WizardSelectionWizard instance.
- def on_wizard_changed(self, new): Handles the selected wizard changin... | Implement the Python class `WizardSelectionWizard` described below.
Class description:
A wizard for wizard selection.
Method signatures and docstrings:
- def __init__(self, window, wizards, **traits): Returns a new WizardSelectionWizard instance.
- def on_wizard_changed(self, new): Handles the selected wizard changin... | e8fc0b2d6b9b08e60389fc4714a5cf51f628b57f | <|skeleton|>
class WizardSelectionWizard:
"""A wizard for wizard selection."""
def __init__(self, window, wizards, **traits):
"""Returns a new WizardSelectionWizard instance."""
<|body_0|>
def on_wizard_changed(self, new):
"""Handles the selected wizard changing."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WizardSelectionWizard:
"""A wizard for wizard selection."""
def __init__(self, window, wizards, **traits):
"""Returns a new WizardSelectionWizard instance."""
self.window = window
self.wizards = wizards
wsp = WizardSelectionPage(wizards=wizards, id='wizard_selection')
... | the_stack_v2_python_sparse | puddle/resource/wizard/wizard_selection_wizard.py | rwl/puddle | train | 2 |
7d36c52ee93cdceb413da17b691a813df91ae5c7 | [
"self.settings = ai_game.settings\nfilname = 'highscore.txt'\nwith open(filname, 'r') as objects:\n num = objects.read()\nself.high_score = int(num)\nself.reset_stats()\nself.game_active = False",
"self.ship_left = self.settings.ship_limit\nself.score = 0\nself.level = 1"
] | <|body_start_0|>
self.settings = ai_game.settings
filname = 'highscore.txt'
with open(filname, 'r') as objects:
num = objects.read()
self.high_score = int(num)
self.reset_stats()
self.game_active = False
<|end_body_0|>
<|body_start_1|>
self.ship_left ... | Track statistics for Alien Invasion. | GameStats | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion."""
def __init__(self, ai_game):
"""Initilaze statistics."""
<|body_0|>
def reset_stats(self):
"""Initilize stastics that can change during the game."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027149 | 690 | no_license | [
{
"docstring": "Initilaze statistics.",
"name": "__init__",
"signature": "def __init__(self, ai_game)"
},
{
"docstring": "Initilize stastics that can change during the game.",
"name": "reset_stats",
"signature": "def reset_stats(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001878 | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion.
Method signatures and docstrings:
- def __init__(self, ai_game): Initilaze statistics.
- def reset_stats(self): Initilize stastics that can change during the game. | Implement the Python class `GameStats` described below.
Class description:
Track statistics for Alien Invasion.
Method signatures and docstrings:
- def __init__(self, ai_game): Initilaze statistics.
- def reset_stats(self): Initilize stastics that can change during the game.
<|skeleton|>
class GameStats:
"""Trac... | eb40f515564fe781eaaf5202165e06be6b22b34d | <|skeleton|>
class GameStats:
"""Track statistics for Alien Invasion."""
def __init__(self, ai_game):
"""Initilaze statistics."""
<|body_0|>
def reset_stats(self):
"""Initilize stastics that can change during the game."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GameStats:
"""Track statistics for Alien Invasion."""
def __init__(self, ai_game):
"""Initilaze statistics."""
self.settings = ai_game.settings
filname = 'highscore.txt'
with open(filname, 'r') as objects:
num = objects.read()
self.high_score = int(num)... | the_stack_v2_python_sparse | SidewaysShooter/game_stats.py | noshah/Python_Practice | train | 0 |
82358a33de70dcbb4cdd519bdec561c36ff4770a | [
"self.d = {}\nfor idx, word in enumerate(words):\n if word in self.d:\n self.d[word] += [idx]\n else:\n self.d[word] = [idx]",
"i = 0\nj = 0\nm = len(self.d[word1])\nn = len(self.d[word2])\nminlen = max(self.d[word1][m - 1] - self.d[word2][0], self.d[word2][n - 1] - self.d[word1][0])\nwhile i ... | <|body_start_0|>
self.d = {}
for idx, word in enumerate(words):
if word in self.d:
self.d[word] += [idx]
else:
self.d[word] = [idx]
<|end_body_0|>
<|body_start_1|>
i = 0
j = 0
m = len(self.d[word1])
n = len(self.d[w... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.d = {}
for idx, word in ... | stack_v2_sparse_classes_36k_train_027150 | 1,827 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 5510ef424135783f6dc40d3f5e85c4c42677c211 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.d = {}
for idx, word in enumerate(words):
if word in self.d:
self.d[word] += [idx]
else:
self.d[word] = [idx]
def shortest(self, word1, word2):
... | the_stack_v2_python_sparse | crackfun/244. Shortest Word Distance II.py | JoyiS/Leetcode | train | 0 | |
f716835362c0566798ee425b08fa28afe591fe78 | [
"self.multi_pdb_file = multi_pdb_file\nself.model_num = model_num\nself.pair1 = pair1\nself.pair2 = pair2\nself.type = multi_pdb_file[0:-12]\nself.template = self.type.split('_')[0]\nself.variant = self.type.split('_')[1]\nself.distances, self.long_distances = self.parse()",
"molid = vmd.molecule.load('pdb', self... | <|body_start_0|>
self.multi_pdb_file = multi_pdb_file
self.model_num = model_num
self.pair1 = pair1
self.pair2 = pair2
self.type = multi_pdb_file[0:-12]
self.template = self.type.split('_')[0]
self.variant = self.type.split('_')[1]
self.distances, self.lon... | MeasureDistances | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MeasureDistances:
def __init__(self, multi_pdb_file, model_num, pair1, pair2):
""":param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1: indexes of first atom pair :param pair2: indexes of second atom pair"""
<|body_0|>
def par... | stack_v2_sparse_classes_36k_train_027151 | 3,445 | no_license | [
{
"docstring": ":param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1: indexes of first atom pair :param pair2: indexes of second atom pair",
"name": "__init__",
"signature": "def __init__(self, multi_pdb_file, model_num, pair1, pair2)"
},
{
"docst... | 3 | null | Implement the Python class `MeasureDistances` described below.
Class description:
Implement the MeasureDistances class.
Method signatures and docstrings:
- def __init__(self, multi_pdb_file, model_num, pair1, pair2): :param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1... | Implement the Python class `MeasureDistances` described below.
Class description:
Implement the MeasureDistances class.
Method signatures and docstrings:
- def __init__(self, multi_pdb_file, model_num, pair1, pair2): :param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1... | fdb8a1a14bcf0b372ebaf152f2bbb1f5d804172e | <|skeleton|>
class MeasureDistances:
def __init__(self, multi_pdb_file, model_num, pair1, pair2):
""":param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1: indexes of first atom pair :param pair2: indexes of second atom pair"""
<|body_0|>
def par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MeasureDistances:
def __init__(self, multi_pdb_file, model_num, pair1, pair2):
""":param multi_pdb_file: pdb file containing all models :param model_num: number of models :param pair1: indexes of first atom pair :param pair2: indexes of second atom pair"""
self.multi_pdb_file = multi_pdb_file
... | the_stack_v2_python_sparse | homology_modeling/model_evaluation/pl_models/model_distance.py | michal2am/bioscripts | train | 3 | |
82955516e881ccf4670cd6b3b46d2cee0fad8b2f | [
"folders_abs = [config.script_folder]\nfor folder in [utils.strings.randstr() for f in range(0, deepness)]:\n folders_abs.append(os.path.join(*[folders_abs[-1], folder]))\n self.check_call(config.cmd_env_mkdir_s % folders_abs[-1], shell=True)\nfolders_rel = [f.replace(config.script_folder, '') for f in folder... | <|body_start_0|>
folders_abs = [config.script_folder]
for folder in [utils.strings.randstr() for f in range(0, deepness)]:
folders_abs.append(os.path.join(*[folders_abs[-1], folder]))
self.check_call(config.cmd_env_mkdir_s % folders_abs[-1], shell=True)
folders_rel = [f.r... | BaseFilesystem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFilesystem:
def populate_folders(self, deepness=4):
"""Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings, dir_abs_path and dir_rel_path"""
<|body_0|>
def populate_files(self, dir_abs_paths, file... | stack_v2_sparse_classes_36k_train_027152 | 2,022 | no_license | [
{
"docstring": "Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings, dir_abs_path and dir_rel_path",
"name": "populate_folders",
"signature": "def populate_folders(self, deepness=4)"
},
{
"docstring": "Populate a folder t... | 2 | stack_v2_sparse_classes_30k_train_021550 | Implement the Python class `BaseFilesystem` described below.
Class description:
Implement the BaseFilesystem class.
Method signatures and docstrings:
- def populate_folders(self, deepness=4): Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings... | Implement the Python class `BaseFilesystem` described below.
Class description:
Implement the BaseFilesystem class.
Method signatures and docstrings:
- def populate_folders(self, deepness=4): Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings... | fb0a0c2af8a22f9d0506b678e61d6088902b7011 | <|skeleton|>
class BaseFilesystem:
def populate_folders(self, deepness=4):
"""Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings, dir_abs_path and dir_rel_path"""
<|body_0|>
def populate_files(self, dir_abs_paths, file... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseFilesystem:
def populate_folders(self, deepness=4):
"""Generate a folder tree with random names. Args: deepness (int): How much is deep the folder tree Returns: A set of two strings, dir_abs_path and dir_rel_path"""
folders_abs = [config.script_folder]
for folder in [utils.strings.... | the_stack_v2_python_sparse | utils/weevely3/testsuite/base_fs.py | zhl2008/ctf-framework | train | 27 | |
e999dbeee8b7d3b8c609be050e9be82f0785ce24 | [
"self.dist = dist\nsamples_ = chaospy.generate_samples(2 * samples, domain=len(dist), rule=rule)\nself.samples1 = samples_.T[:samples].T\nself.samples2 = samples_.T[samples:].T\nself.poly = poly\nself.buffer = {}",
"new = numpy.empty(self.samples1.shape)\nfor idx in range(len(indices)):\n if indices[idx]:\n ... | <|body_start_0|>
self.dist = dist
samples_ = chaospy.generate_samples(2 * samples, domain=len(dist), rule=rule)
self.samples1 = samples_.T[:samples].T
self.samples2 = samples_.T[samples:].T
self.poly = poly
self.buffer = {}
<|end_body_0|>
<|body_start_1|>
new = n... | Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Saltelli(dist, 3, rule="halton") >>> generator[False, False].round(4) array([... | Saltelli | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Saltelli:
"""Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Saltelli(dist, 3, rule="halton") >>> gene... | stack_v2_sparse_classes_36k_train_027153 | 8,039 | permissive | [
{
"docstring": "Initialize the matrix generator. dist (chaopy.Distribution): distribution to sample from. samples (int): The number of samples to draw for each matrix. poly (numpoly.ndpoly): If provided, evaluated samples through polynomials before returned. rule (str): Scheme for generating random samples.",
... | 3 | stack_v2_sparse_classes_30k_train_019216 | Implement the Python class `Saltelli` described below.
Class description:
Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Sa... | Implement the Python class `Saltelli` described below.
Class description:
Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Sa... | b5959a24e0bd9b214c292485919d7ce58795f5dc | <|skeleton|>
class Saltelli:
"""Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Saltelli(dist, 3, rule="halton") >>> gene... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Saltelli:
"""Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Saltelli(dist, 3, rule="halton") >>> generator[False, ... | the_stack_v2_python_sparse | chaospy/saltelli.py | jonathf/chaospy | train | 405 |
d020b4ba0f5d54bcc91221ef2c1503192c9c019c | [
"if not isinstance(expr, (str, list, int)):\n raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))\nself.expr = expr\nself.to = to\nself.container = cont",
"if id(self.container) != id(col2.container):\n raise RuntimeError('Only one container is allowed.')\nif self.to is not ... | <|body_start_0|>
if not isinstance(expr, (str, list, int)):
raise TypeError('expr must be a string, int or a list of string, int.'.format(expr))
self.expr = expr
self.to = to
self.container = cont
<|end_body_0|>
<|body_start_1|>
if id(self.container) != id(col2.conta... | Column selector. | COL | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_36k_train_027154 | 35,835 | permissive | [
{
"docstring": ":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous transform in the pipeline",
"name": "__init__",
"signature": "def __... | 4 | stack_v2_sparse_classes_30k_train_016963 | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | Implement the Python class `COL` described below.
Class description:
Column selector.
Method signatures and docstrings:
- def __init__(self, expr, to=None, cont=None): :param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists),... | b5f1c2e3422fadc81e21337bcddb7372682dd455 | <|skeleton|>
class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class COL:
"""Column selector."""
def __init__(self, expr, to=None, cont=None):
""":param expr: input column :param to: output column, (overwrites input if not specified) :param cont: input container (used to check the input exists), if not specified (None), the container is assumed to be the previous ... | the_stack_v2_python_sparse | src/python/nimbusml/internal/utils/data_schema.py | zyw400/NimbusML-1 | train | 3 |
01fd7df4bb3171651def567c2c1f7892418ba4b2 | [
"rows = []\nfor index in range(1, numrows):\n rows.append(int(rowcount / numrows * index))\nrows.append(int(rowcount / numrows * numrows) - 1)\nreturn rows",
"np_patient_reshaped = np.empty((0, 5 * len(Worker.columns) * Worker.frames_per_excersise))\nindicator = None\nfor combination in patient_combinations:\n... | <|body_start_0|>
rows = []
for index in range(1, numrows):
rows.append(int(rowcount / numrows * index))
rows.append(int(rowcount / numrows * numrows) - 1)
return rows
<|end_body_0|>
<|body_start_1|>
np_patient_reshaped = np.empty((0, 5 * len(Worker.columns) * Worker.... | Worker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Worker:
def select_rows(rowcount, numrows):
"""creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] -- number of rows to devide in. Returns: [list] -- list of row indexes based on size of table."""... | stack_v2_sparse_classes_36k_train_027155 | 3,644 | no_license | [
{
"docstring": "creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] -- number of rows to devide in. Returns: [list] -- list of row indexes based on size of table.",
"name": "select_rows",
"signature": "def select... | 3 | stack_v2_sparse_classes_30k_train_000264 | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def select_rows(rowcount, numrows): creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] --... | Implement the Python class `Worker` described below.
Class description:
Implement the Worker class.
Method signatures and docstrings:
- def select_rows(rowcount, numrows): creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] --... | e850ea81b3f1e92b9c6a9bbd401fd5aaab1a3cf2 | <|skeleton|>
class Worker:
def select_rows(rowcount, numrows):
"""creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] -- number of rows to devide in. Returns: [list] -- list of row indexes based on size of table."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Worker:
def select_rows(rowcount, numrows):
"""creates a list of evenly devided row indexes based on size of an table. Arguments: rowcount [int] -- amount of rows in the table. numrows [int] -- number of rows to devide in. Returns: [list] -- list of row indexes based on size of table."""
rows ... | the_stack_v2_python_sparse | Fingerprinting/DataScience/src/tools/worker.py | lvkoppen/DataScienceMinor | train | 0 | |
b6a9a38d9226c3b921153362ad655e877a205353 | [
"sql = 'SELECT * FROM `appointment` where user_id = %s and enabled = 1;' % user_id\nresult = self.my_sql.find_all(sql)\nprint(result)",
"create_time = datetime.strptime(str(self.get_yesterday()) + ' ' + datetime.now().strftime('%H:%M:%S'), '%Y-%m-%d %H:%M:%S')\ntime = datetime.strptime(str(date.today()) + ' ' + d... | <|body_start_0|>
sql = 'SELECT * FROM `appointment` where user_id = %s and enabled = 1;' % user_id
result = self.my_sql.find_all(sql)
print(result)
<|end_body_0|>
<|body_start_1|>
create_time = datetime.strptime(str(self.get_yesterday()) + ' ' + datetime.now().strftime('%H:%M:%S'), '%Y-... | CaterHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaterHelper:
def query_appointment(self, user_id):
"""查询预约记录"""
<|body_0|>
def update_appointment_time(self, user_id):
"""修改预约时间"""
<|body_1|>
def update_server_order_time(self, user_id):
"""修改就餐时间"""
<|body_2|>
def get_yesterday(sel... | stack_v2_sparse_classes_36k_train_027156 | 2,181 | no_license | [
{
"docstring": "查询预约记录",
"name": "query_appointment",
"signature": "def query_appointment(self, user_id)"
},
{
"docstring": "修改预约时间",
"name": "update_appointment_time",
"signature": "def update_appointment_time(self, user_id)"
},
{
"docstring": "修改就餐时间",
"name": "update_serve... | 4 | stack_v2_sparse_classes_30k_train_012085 | Implement the Python class `CaterHelper` described below.
Class description:
Implement the CaterHelper class.
Method signatures and docstrings:
- def query_appointment(self, user_id): 查询预约记录
- def update_appointment_time(self, user_id): 修改预约时间
- def update_server_order_time(self, user_id): 修改就餐时间
- def get_yesterday(... | Implement the Python class `CaterHelper` described below.
Class description:
Implement the CaterHelper class.
Method signatures and docstrings:
- def query_appointment(self, user_id): 查询预约记录
- def update_appointment_time(self, user_id): 修改预约时间
- def update_server_order_time(self, user_id): 修改就餐时间
- def get_yesterday(... | 024bb8f0e8be7d19abfb14b405ef79bd85cc6b7b | <|skeleton|>
class CaterHelper:
def query_appointment(self, user_id):
"""查询预约记录"""
<|body_0|>
def update_appointment_time(self, user_id):
"""修改预约时间"""
<|body_1|>
def update_server_order_time(self, user_id):
"""修改就餐时间"""
<|body_2|>
def get_yesterday(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaterHelper:
def query_appointment(self, user_id):
"""查询预约记录"""
sql = 'SELECT * FROM `appointment` where user_id = %s and enabled = 1;' % user_id
result = self.my_sql.find_all(sql)
print(result)
def update_appointment_time(self, user_id):
"""修改预约时间"""
creat... | the_stack_v2_python_sparse | source/CaterSet/cater_helper.py | cjuan123/auto_api | train | 0 | |
a1239f4ed517661675af6b8785004ce7bff3af9a | [
"letters = 'abcdefghijklmnopqrstuvwxyz'\ncnt = collections.Counter()\nn = 0\nfor s in licensePlate:\n if s.lower() in letters:\n cnt[s.lower()] += 1\n n += 1\nres, leng = ('', float('inf'))\nfor each in words:\n if len(each) >= n:\n flag = 1\n for key in cnt:\n if cnt[ke... | <|body_start_0|>
letters = 'abcdefghijklmnopqrstuvwxyz'
cnt = collections.Counter()
n = 0
for s in licensePlate:
if s.lower() in letters:
cnt[s.lower()] += 1
n += 1
res, leng = ('', float('inf'))
for each in words:
i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
<|body_0|>
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
... | stack_v2_sparse_classes_36k_train_027157 | 2,799 | no_license | [
{
"docstring": ":type licensePlate: str :type words: List[str] :rtype: str",
"name": "shortestCompletingWord",
"signature": "def shortestCompletingWord(self, licensePlate, words)"
},
{
"docstring": ":type licensePlate: str :type words: List[str] :rtype: str",
"name": "shortestCompletingWord"... | 2 | stack_v2_sparse_classes_30k_train_009537 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestCompletingWord(self, licensePlate, words): :type licensePlate: str :type words: List[str] :rtype: str
- def shortestCompletingWord(self, licensePlate, words): :type l... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def shortestCompletingWord(self, licensePlate, words): :type licensePlate: str :type words: List[str] :rtype: str
- def shortestCompletingWord(self, licensePlate, words): :type l... | 8bb17099be02d997d554519be360ef4aa1c028e3 | <|skeleton|>
class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
<|body_0|>
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def shortestCompletingWord(self, licensePlate, words):
""":type licensePlate: str :type words: List[str] :rtype: str"""
letters = 'abcdefghijklmnopqrstuvwxyz'
cnt = collections.Counter()
n = 0
for s in licensePlate:
if s.lower() in letters:
... | the_stack_v2_python_sparse | Google/2. medium/749. Shortest Completing Word.py | yemao616/summer18 | train | 0 | |
633b09a7dd7b57ba8b07184c03febf04b524b4d6 | [
"params = {'pf': pf, 'uid': uid, 'ver': ver, 'page': page, 'channel': channel, 'accesstoken': accesstoken}\ntry:\n request = requests.get(hostname + '/article/list/home', params=params)\n return request.json()\nexcept Exception as e:\n pass",
"params = {'uid': uid, 'accesstoken': accesstoken, 'islogin': ... | <|body_start_0|>
params = {'pf': pf, 'uid': uid, 'ver': ver, 'page': page, 'channel': channel, 'accesstoken': accesstoken}
try:
request = requests.get(hostname + '/article/list/home', params=params)
return request.json()
except Exception as e:
pass
<|end_body_... | Article | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Article:
def article_list_home(hostname, uid, accesstoken, page, channel, ver, pf='android'):
"""article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param channel: not required :param page: not required :param pf: android or ios :return: request"""
... | stack_v2_sparse_classes_36k_train_027158 | 2,307 | no_license | [
{
"docstring": "article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param channel: not required :param page: not required :param pf: android or ios :return: request",
"name": "article_list_home",
"signature": "def article_list_home(hostname, uid, accesstoken, page, c... | 3 | stack_v2_sparse_classes_30k_train_011236 | Implement the Python class `Article` described below.
Class description:
Implement the Article class.
Method signatures and docstrings:
- def article_list_home(hostname, uid, accesstoken, page, channel, ver, pf='android'): article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param ... | Implement the Python class `Article` described below.
Class description:
Implement the Article class.
Method signatures and docstrings:
- def article_list_home(hostname, uid, accesstoken, page, channel, ver, pf='android'): article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param ... | ce85f22be71fe7466fd6bc3c94d5b5744551ec01 | <|skeleton|>
class Article:
def article_list_home(hostname, uid, accesstoken, page, channel, ver, pf='android'):
"""article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param channel: not required :param page: not required :param pf: android or ios :return: request"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Article:
def article_list_home(hostname, uid, accesstoken, page, channel, ver, pf='android'):
"""article/list/home GET :param uid: user id :param accesstoken: token :param ver: version :param channel: not required :param page: not required :param pf: android or ios :return: request"""
params =... | the_stack_v2_python_sparse | Lib/Article.py | yangkechuan/ApiTest | train | 1 | |
91a410ff5eeccd735ddfc784fba01a79738469b1 | [
"if self.parent.ct is None:\n pn.state.notifications.warning('no CT found', duration=3000)\nelse:\n threshold = -1 if self.auto_threshold else self.threshold\n tomopy_threshold = -1 if self.auto_tomopy_threshold else self.tomopy_threshold\n self.parent.ct = gamma_filter(arrays=self.parent.ct, threshold=... | <|body_start_0|>
if self.parent.ct is None:
pn.state.notifications.warning('no CT found', duration=3000)
else:
threshold = -1 if self.auto_threshold else self.threshold
tomopy_threshold = -1 if self.auto_tomopy_threshold else self.tomopy_threshold
self.par... | Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack. | GammaFilter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GammaFilter:
"""Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack."""
def apply(self):
"""Apply gamma filter."""
<|body_0|>
def panel(self, width=200):
"""App card view."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k_train_027159 | 4,494 | permissive | [
{
"docstring": "Apply gamma filter.",
"name": "apply",
"signature": "def apply(self)"
},
{
"docstring": "App card view.",
"name": "panel",
"signature": "def panel(self, width=200)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019769 | Implement the Python class `GammaFilter` described below.
Class description:
Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack.
Method signatures and docstrings:
- def apply(self): Apply gamma filter.
- def panel(self, width=200): App card view. | Implement the Python class `GammaFilter` described below.
Class description:
Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack.
Method signatures and docstrings:
- def apply(self): Apply gamma filter.
- def panel(self, width=200): App card view.
<|skeleto... | 7c9dea7a3a7877af1bafdfb71da8fb018d5d828f | <|skeleton|>
class GammaFilter:
"""Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack."""
def apply(self):
"""Apply gamma filter."""
<|body_0|>
def panel(self, width=200):
"""App card view."""
<|body_1|>
<|end_sk... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GammaFilter:
"""Gamma filter widget. Widget for the gamma filter from iMars3D, must have a parent widget with validate ct stack."""
def apply(self):
"""Apply gamma filter."""
if self.parent.ct is None:
pn.state.notifications.warning('no CT found', duration=3000)
else:
... | the_stack_v2_python_sparse | src/imars3d/ui/widgets/gamma_filter.py | ornlneutronimaging/iMars3D | train | 3 |
cc0b36428e21a392ba04c6f31e97140d306df458 | [
"self.IO = IO\nself.GR = GR\nself.PF_PKJ = PF_PKJ\nself.CF_PKJ = CF_PKJ\nself.ltd_decay = ltd_decay\nself.ltd_bins = int(window / defaultclock.dt)\nSpikeMonitor.__init__(self, IO)",
"if len(spikes):\n pkj_inds = PF_PKJ_LTD.postsynaptic_indexes(spikes, self.CF_PKJ)\n gr_inds = PF_PKJ_LTD.presynaptic_indexes(... | <|body_start_0|>
self.IO = IO
self.GR = GR
self.PF_PKJ = PF_PKJ
self.CF_PKJ = CF_PKJ
self.ltd_decay = ltd_decay
self.ltd_bins = int(window / defaultclock.dt)
SpikeMonitor.__init__(self, IO)
<|end_body_0|>
<|body_start_1|>
if len(spikes):
pkj_i... | Implements LTD on PF-PKJ synapses driven by CF activity | PF_PKJ_LTD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PF_PKJ_LTD:
"""Implements LTD on PF-PKJ synapses driven by CF activity"""
def __init__(self, IO, GR, PF_PKJ, CF_PKJ, ltd_decay=0.995, window=50 * ms):
"""IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cells PF_PKJ: Synapses object of PF-PKJ synapses CF_PKJ: Syna... | stack_v2_sparse_classes_36k_train_027160 | 5,461 | no_license | [
{
"docstring": "IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cells PF_PKJ: Synapses object of PF-PKJ synapses CF_PKJ: Synapses object of CF-PKJ synapses ltd_decay: the multiplicative decay constant to decay PF-PKJ synapses by. window: the time window to depress PF-PKJ synapses for GR spi... | 2 | stack_v2_sparse_classes_30k_train_010114 | Implement the Python class `PF_PKJ_LTD` described below.
Class description:
Implements LTD on PF-PKJ synapses driven by CF activity
Method signatures and docstrings:
- def __init__(self, IO, GR, PF_PKJ, CF_PKJ, ltd_decay=0.995, window=50 * ms): IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cell... | Implement the Python class `PF_PKJ_LTD` described below.
Class description:
Implements LTD on PF-PKJ synapses driven by CF activity
Method signatures and docstrings:
- def __init__(self, IO, GR, PF_PKJ, CF_PKJ, ltd_decay=0.995, window=50 * ms): IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cell... | 6579a4d9636332267d0f26d8d4c8226e4fecf85d | <|skeleton|>
class PF_PKJ_LTD:
"""Implements LTD on PF-PKJ synapses driven by CF activity"""
def __init__(self, IO, GR, PF_PKJ, CF_PKJ, ltd_decay=0.995, window=50 * ms):
"""IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cells PF_PKJ: Synapses object of PF-PKJ synapses CF_PKJ: Syna... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PF_PKJ_LTD:
"""Implements LTD on PF-PKJ synapses driven by CF activity"""
def __init__(self, IO, GR, PF_PKJ, CF_PKJ, ltd_decay=0.995, window=50 * ms):
"""IO: NeuronGroup of inferior olive neurons GR: NeuronGroup of granule cells PF_PKJ: Synapses object of PF-PKJ synapses CF_PKJ: Synapses object o... | the_stack_v2_python_sparse | neuron_models/cf_learning.py | blennon/research | train | 0 |
285b7087fb18311a04510e123e05ec35856026c7 | [
"self.logging.info('Looking in memcache for session at ID: \"%s\".' % id)\nself.logging.info('Looking in memcache for encoded session ID: \"%s\"' % self._en(id))\nsession = memcache.get(self._en(id))\nself.logging.info('Memcache result: \"%s\"' % session)\nreturn session",
"self.logging.info('Saving session in me... | <|body_start_0|>
self.logging.info('Looking in memcache for session at ID: "%s".' % id)
self.logging.info('Looking in memcache for encoded session ID: "%s"' % self._en(id))
session = memcache.get(self._en(id))
self.logging.info('Memcache result: "%s"' % session)
return session
<|... | Session loader that loads and saves sessions with memcache | MemcacheSessionLoader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
<|body_0|>
def put_session(self, id, struct, handler):
"""Saves a session to memcache, fr... | stack_v2_sparse_classes_36k_train_027161 | 4,626 | no_license | [
{
"docstring": "Returns a session from memcache, given a session ID.",
"name": "get_session",
"signature": "def get_session(self, id)"
},
{
"docstring": "Saves a session to memcache, from a generated response.",
"name": "put_session",
"signature": "def put_session(self, id, struct, handl... | 2 | null | Implement the Python class `MemcacheSessionLoader` described below.
Class description:
Session loader that loads and saves sessions with memcache
Method signatures and docstrings:
- def get_session(self, id): Returns a session from memcache, given a session ID.
- def put_session(self, id, struct, handler): Saves a se... | Implement the Python class `MemcacheSessionLoader` described below.
Class description:
Session loader that loads and saves sessions with memcache
Method signatures and docstrings:
- def get_session(self, id): Returns a session from memcache, given a session ID.
- def put_session(self, id, struct, handler): Saves a se... | b0ea12ff7b56ea86179a97b08055d6ff1b57355c | <|skeleton|>
class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
<|body_0|>
def put_session(self, id, struct, handler):
"""Saves a session to memcache, fr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemcacheSessionLoader:
"""Session loader that loads and saves sessions with memcache"""
def get_session(self, id):
"""Returns a session from memcache, given a session ID."""
self.logging.info('Looking in memcache for session at ID: "%s".' % id)
self.logging.info('Looking in memcac... | the_stack_v2_python_sparse | app/openfire/core/sessions/loader.py | openfire/openfire_old | train | 0 |
644639d73d3652e66e828bd6fc735369d2009e68 | [
"res = []\n\ndef bracket(s='', left=0, right=0):\n \"\"\"\n :param s:当前生成序列\n :param left:左括号个数\n :param right:右括号个数\n :return:\n \"\"\"\n if len(s) == 2 * n:\n res.append(s)\n return\n if left < n:\n bracket(s + '(', left + 1, rig... | <|body_start_0|>
res = []
def bracket(s='', left=0, right=0):
"""
:param s:当前生成序列
:param left:左括号个数
:param right:右括号个数
:return:
"""
if len(s) == 2 * n:
res.append(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis1(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = []
def bracket(s='', left... | stack_v2_sparse_classes_36k_train_027162 | 1,146 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis1",
"signature": "def generateParenthesis1(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis1(self, n): :type n: int :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def generateParenthesis1(self, n): :type n: int :rtype: List[str]
<|skeleton|>
class Solution:
def genera... | b8ec1350e904665f1375c29a53f443ecf262d723 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def generateParenthesis1(self, n):
""":type n: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
res = []
def bracket(s='', left=0, right=0):
"""
:param s:当前生成序列
:param left:左括号个数
:param right:右括号个数
:return:
... | the_stack_v2_python_sparse | leetcode/022括号生成.py | ShawDa/Coding | train | 0 | |
8e478993ed439e058d0df69121db484f8c936899 | [
"if not nums:\n return 0\ndp = [1] * len(nums)\nfor i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\nreturn max(dp)",
"if not nums:\n return 0\ntail = [nums[0]]\nfor num in nums:\n if num > tail[-1]:\n tail.append(num)\n e... | <|body_start_0|>
if not nums:
return 0
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1|>
if not nums:
... | 详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个... | stack_v2_sparse_classes_36k_train_027163 | 2,709 | no_license | [
{
"docstring": "DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个更长的子序列 3. 状态转移:dp[i] = max(dp[i], dp[j] + 1) if nums[i] > nums[j]",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums: List[int]) -> int"
},
{
"docstring": "贪心+二分查找:维护tail数组 tai... | 2 | stack_v2_sparse_classes_30k_train_004771 | Implement the Python class `Solution` described below.
Class description:
详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: DP: 1. 定义状态:dp[i] 表示以 nums[i]结... | Implement the Python class `Solution` described below.
Class description:
详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/
Method signatures and docstrings:
- def lengthOfLIS1(self, nums: List[int]) -> int: DP: 1. 定义状态:dp[i] 表示以 nums[i]结... | 2bbb1640589aab34f2bc42489283033cc11fb885 | <|skeleton|>
class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""详细思路:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/dong-tai-gui-hua-er-fen-cha-zhao-tan-xin-suan-fa-p/"""
def lengthOfLIS1(self, nums: List[int]) -> int:
"""DP: 1. 定义状态:dp[i] 表示以 nums[i]结尾的「上升子序列」的长度 2. 遍历nums[i]之前的数字,只要nums[i]大于它,则可以在它的基础上形成一个更长的子序列 3. 状态转... | the_stack_v2_python_sparse | 300_longest-increasing-subsequence.py | helloocc/algorithm | train | 1 |
ab5030e286b8bc087ea11ecfcc4d0427ea03ecae | [
"super(AdelaideFastNAS, self).__init__()\nself.desc = copy.deepcopy(net_desc)\nself.encoder = MobileNetV2Backbone(load_path=self.desc.pop('backbone_load_path'))\nself.decoder = Decoder(**self.desc)",
"enc = self.encoder(input_var)\noutput = self.decoder(enc)\noutput = F.interpolate(output, size=input_var.size()[2... | <|body_start_0|>
super(AdelaideFastNAS, self).__init__()
self.desc = copy.deepcopy(net_desc)
self.encoder = MobileNetV2Backbone(load_path=self.desc.pop('backbone_load_path'))
self.decoder = Decoder(**self.desc)
<|end_body_0|>
<|body_start_1|>
enc = self.encoder(input_var)
... | Search space of AdelaideFastNAS. | AdelaideFastNAS | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdelaideFastNAS:
"""Search space of AdelaideFastNAS."""
def __init__(self, net_desc):
"""Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure"""
<|body_0|>
def forward(self, input_var):
"""Do an inference on AdelaideFastNAS model... | stack_v2_sparse_classes_36k_train_027164 | 1,695 | permissive | [
{
"docstring": "Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure",
"name": "__init__",
"signature": "def __init__(self, net_desc)"
},
{
"docstring": "Do an inference on AdelaideFastNAS model. :param input_var: input tensor :return: output tensor",
"name"... | 2 | null | Implement the Python class `AdelaideFastNAS` described below.
Class description:
Search space of AdelaideFastNAS.
Method signatures and docstrings:
- def __init__(self, net_desc): Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure
- def forward(self, input_var): Do an inference on ... | Implement the Python class `AdelaideFastNAS` described below.
Class description:
Search space of AdelaideFastNAS.
Method signatures and docstrings:
- def __init__(self, net_desc): Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure
- def forward(self, input_var): Do an inference on ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class AdelaideFastNAS:
"""Search space of AdelaideFastNAS."""
def __init__(self, net_desc):
"""Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure"""
<|body_0|>
def forward(self, input_var):
"""Do an inference on AdelaideFastNAS model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdelaideFastNAS:
"""Search space of AdelaideFastNAS."""
def __init__(self, net_desc):
"""Construct the AdelaideFastNAS class. :param net_desc: config of the searched structure"""
super(AdelaideFastNAS, self).__init__()
self.desc = copy.deepcopy(net_desc)
self.encoder = Mob... | the_stack_v2_python_sparse | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/vega/search_space/networks/pytorch/customs/adelaide.py | Huawei-Ascend/modelzoo | train | 1 |
2cfa8547dac6c6967dd79611594fcf86e15eaa82 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{device_id}_{description.key}'\nself._attr_device_info = device\nself.utility_account_id = utility_account_id",
"if self.coordinator.data is not None:\n return self.entity_description.value_fn(self.coordinator.data[... | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f'{device_id}_{description.key}'
self._attr_device_info = device
self.utility_account_id = utility_account_id
<|end_body_0|>
<|body_start_1|>
if self.coordinator.d... | Representation of an Opower sensor. | OpowerSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value... | stack_v2_sparse_classes_36k_train_027165 | 8,626 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None"
},
{
"docstring": "Return the state.",
"name": "native_val... | 2 | stack_v2_sparse_classes_30k_train_017732 | Implement the Python class `OpowerSensor` described below.
Class description:
Representation of an Opower sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None: Initializ... | Implement the Python class `OpowerSensor` described below.
Class description:
Representation of an Opower sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None: Initializ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OpowerSensor:
"""Representation of an Opower sensor."""
def __init__(self, coordinator: OpowerCoordinator, description: OpowerEntityDescription, utility_account_id: str, device: DeviceInfo, device_id: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.en... | the_stack_v2_python_sparse | homeassistant/components/opower/sensor.py | home-assistant/core | train | 35,501 |
5cf61de597a11674ffa642b6f77ed54031bc3be6 | [
"d = defaultdict(list)\nfor s in strs:\n d[''.join(sorted(s))].append(s)\nreturn list(d.values())",
"d = defaultdict(set)\nfor i, s in enumerate((''.join(sorted(x)) for x in strs)):\n d[s].add(i)\nreturn [[strs[i] for i in indexes] for indexes in d.values()]",
"def encode(w):\n cnt = [0] * 26\n for ... | <|body_start_0|>
d = defaultdict(list)
for s in strs:
d[''.join(sorted(s))].append(s)
return list(d.values())
<|end_body_0|>
<|body_start_1|>
d = defaultdict(set)
for i, s in enumerate((''.join(sorted(x)) for x in strs)):
d[s].add(i)
return [[strs... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
"""04/22/2018 04:37"""
<|body_0|>
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""09/22/2021 23:39"""
<|body_1|>
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""11/06/2022 1... | stack_v2_sparse_classes_36k_train_027166 | 2,115 | no_license | [
{
"docstring": "04/22/2018 04:37",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": "09/22/2021 23:39",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs: List[str]) -> List[List[str]]"
},
{
"docstring": "11/06/2022 14:20",... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): 04/22/2018 04:37
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 09/22/2021 23:39
- def groupAnagrams(self, strs: List[str]) -> List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): 04/22/2018 04:37
- def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 09/22/2021 23:39
- def groupAnagrams(self, strs: List[str]) -> List... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
"""04/22/2018 04:37"""
<|body_0|>
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""09/22/2021 23:39"""
<|body_1|>
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""11/06/2022 1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
"""04/22/2018 04:37"""
d = defaultdict(list)
for s in strs:
d[''.join(sorted(s))].append(s)
return list(d.values())
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
"""09/22/2021 23:39"""
d = ... | the_stack_v2_python_sparse | leetcode/solved/49_Group_Anagrams/solution.py | sungminoh/algorithms | train | 0 | |
0169d0106347a9e0ec51a39b20f1ebe57acc4308 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | NXDOManagerServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NXDOManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetLogDir(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetManagerMetaData(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k_train_027167 | 8,976 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetLogDir",
"signature": "def GetLogDir(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "GetManagerMetaData",
"signature": "def GetManagerMet... | 5 | stack_v2_sparse_classes_30k_train_010197 | Implement the Python class `NXDOManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetLogDir(self, request, context): Missing associated documentation comment in .proto file.
- def GetManagerMetaData(self, request, cont... | Implement the Python class `NXDOManagerServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetLogDir(self, request, context): Missing associated documentation comment in .proto file.
- def GetManagerMetaData(self, request, cont... | 1ddd92aa56ba10fa468396de8f8824c83ba9d0ba | <|skeleton|>
class NXDOManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetLogDir(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def GetManagerMetaData(self, request, context):
"""Missing associa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NXDOManagerServicer:
"""Missing associated documentation comment in .proto file."""
def GetLogDir(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | grl/algos/nxdo/nxdo_manager/protobuf/nxdo_manager_pb2_grpc.py | RL-code-lib/nxdo | train | 0 |
28a059cdfaaa32e9f484a6a1639b63239456da51 | [
"dummy = tail = ListNode(None)\nwhile l1 and l2:\n if l1.val <= l2.val:\n tail.next, tail, l1 = (l1, l1, l1.next)\n else:\n tail.next, tail, l2 = (l2, l2, l2.next)\ntail.next = l1 or l2 if l1 or l2 else None\nreturn dummy.next",
"dummyRoot = ListNode(0)\nptr = dummyRoot\nptr1 = l1\nptr2 = l2\n... | <|body_start_0|>
dummy = tail = ListNode(None)
while l1 and l2:
if l1.val <= l2.val:
tail.next, tail, l1 = (l1, l1, l1.next)
else:
tail.next, tail, l2 = (l2, l2, l2.next)
tail.next = l1 or l2 if l1 or l2 else None
return dummy.next
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_my_first(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_027168 | 2,623 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists_my_first",
"signature": "def mergeTwoLists_m... | 2 | stack_v2_sparse_classes_30k_train_011722 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_my_first(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def mergeTwoLists_my_first(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def mergeTwoLists_my_first(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
dummy = tail = ListNode(None)
while l1 and l2:
if l1.val <= l2.val:
tail.next, tail, l1 = (l1, l1, l1.next)
else:
tail.next, t... | the_stack_v2_python_sparse | 21.MergeTwoSortedLists.py | JerryRoc/leetcode | train | 0 | |
fe9b243e3b8006ac10166b5d5a35719d4258eb83 | [
"Inventory.__init__(self, product_code, description, market_price, rental_price)\nself.material = material\nself.size = size",
"furniture = Inventory.return_as_dictionary(self)\nfurniture['material'] = self.material\nfurniture['size'] = self.size\nreturn furniture"
] | <|body_start_0|>
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.material = material
self.size = size
<|end_body_0|>
<|body_start_1|>
furniture = Inventory.return_as_dictionary(self)
furniture['material'] = self.material
furniture['si... | furniture class | Furniture | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Furniture:
"""furniture class"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""furniture construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return a furniture dictionary from super class"""
... | stack_v2_sparse_classes_36k_train_027169 | 1,084 | no_license | [
{
"docstring": "furniture construction",
"name": "__init__",
"signature": "def __init__(self, product_code, description, market_price, rental_price, material, size)"
},
{
"docstring": "function to return a furniture dictionary from super class",
"name": "return_as_dictionary",
"signature... | 2 | null | Implement the Python class `Furniture` described below.
Class description:
furniture class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, material, size): furniture construction
- def return_as_dictionary(self): function to return a furniture dictionary f... | Implement the Python class `Furniture` described below.
Class description:
furniture class
Method signatures and docstrings:
- def __init__(self, product_code, description, market_price, rental_price, material, size): furniture construction
- def return_as_dictionary(self): function to return a furniture dictionary f... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class Furniture:
"""furniture class"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""furniture construction"""
<|body_0|>
def return_as_dictionary(self):
"""function to return a furniture dictionary from super class"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Furniture:
"""furniture class"""
def __init__(self, product_code, description, market_price, rental_price, material, size):
"""furniture construction"""
Inventory.__init__(self, product_code, description, market_price, rental_price)
self.material = material
self.size = siz... | the_stack_v2_python_sparse | students/ethan_nguyen/Lesson01/assignment/inventory_management/furniture_class.py | JavaRod/SP_Python220B_2019 | train | 1 |
95789cee0dae8807a2c2c31bf3af6f91affe250b | [
"phone = request.COOKIES.get('ph')\nnow_time = datetime.now()\nbefore_time = datetime.now() - timedelta(days=7)\nuser_info = check_user_auth_level(user_phone=phone)\nif user_info[0] == '0':\n '\\n 超级管理员\\n '\n data = func_for_general_statistics_admin(start_time=before_time, end_time=now_... | <|body_start_0|>
phone = request.COOKIES.get('ph')
now_time = datetime.now()
before_time = datetime.now() - timedelta(days=7)
user_info = check_user_auth_level(user_phone=phone)
if user_info[0] == '0':
'\n 超级管理员\n '
data = func_for_ge... | 后台首页统计表 代理商利润 使用次数 设备状态 用户总量等 | GeneralStatistics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
phone = request.COOKIES... | stack_v2_sparse_classes_36k_train_027170 | 34,277 | no_license | [
{
"docstring": ":param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": ":param request: :return:",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021355 | Implement the Python class `GeneralStatistics` described below.
Class description:
后台首页统计表 代理商利润 使用次数 设备状态 用户总量等
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return: | Implement the Python class `GeneralStatistics` described below.
Class description:
后台首页统计表 代理商利润 使用次数 设备状态 用户总量等
Method signatures and docstrings:
- def get(self, request): :param request: :return:
- def post(self, request): :param request: :return:
<|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状... | 37b0bbff8818e73fd4897871956cfef446589e2f | <|skeleton|>
class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
<|body_0|>
def post(self, request):
""":param request: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralStatistics:
"""后台首页统计表 代理商利润 使用次数 设备状态 用户总量等"""
def get(self, request):
""":param request: :return:"""
phone = request.COOKIES.get('ph')
now_time = datetime.now()
before_time = datetime.now() - timedelta(days=7)
user_info = check_user_auth_level(user_phone=p... | the_stack_v2_python_sparse | applet_background/system_home/system_views.py | xieboxiebo/escortbed | train | 0 |
9a9508a4c8549282b4342a83b891d54a39fcd8c6 | [
"self._smax = soil_moisture_max\nself._g = beta_parameter\nself._c = bulk_coefficient\nself._l = specific_latent_heat_of_water\nsuper(BucketHydrology, self).__init__(**kwargs)",
"beta_factor = 0\nnew_state = initialize_numpy_arrays_with_properties(self.output_properties, state, self.input_properties)\ndiagnostics... | <|body_start_0|>
self._smax = soil_moisture_max
self._g = beta_parameter
self._c = bulk_coefficient
self._l = specific_latent_heat_of_water
super(BucketHydrology, self).__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
beta_factor = 0
new_state = initialize_nump... | Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input. | BucketHydrology | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BucketHydrology:
"""Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input."""
def __init__(self, soil_moisture_max=... | stack_v2_sparse_classes_36k_train_027171 | 6,883 | permissive | [
{
"docstring": "Args: soil_moisture_max: The maximum moisture that can be held by the surface_temperature beta_parameter: A constant value that is used in the beta_factor calculation. bulk_coefficient: The bulk transfer coefficient that is used to calculate maximum evaporation rate and sensible heat flux",
... | 2 | stack_v2_sparse_classes_30k_train_016814 | Implement the Python class `BucketHydrology` described below.
Class description:
Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input.
Metho... | Implement the Python class `BucketHydrology` described below.
Class description:
Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input.
Metho... | 556487e1b5e78011004a9264ace5130c3dc3507a | <|skeleton|>
class BucketHydrology:
"""Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input."""
def __init__(self, soil_moisture_max=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BucketHydrology:
"""Manages surface energy and moisture balance This component assumes that the surface is a slab with some heat capacity and moisture holding capacity. Calculates the sensible and latent heat flux, takes precipitation values as input."""
def __init__(self, soil_moisture_max=0.15, beta_pa... | the_stack_v2_python_sparse | climt/_components/bucket_hydrology/component.py | CliMT/climt | train | 129 |
69ac09976f92f4a0b5cc69bda570dfcee1650f13 | [
"_instance = super(BowlerDefinition, self).update(instance, validated_data)\nif self.context.get('remove_team', False):\n _instance.team = None\n _instance.save()\nreturn _instance",
"league = self.context.get('league')\nteam = league.teams.filter(pk=value.pk)\nif not len(team):\n raise serializers.Valid... | <|body_start_0|>
_instance = super(BowlerDefinition, self).update(instance, validated_data)
if self.context.get('remove_team', False):
_instance.team = None
_instance.save()
return _instance
<|end_body_0|>
<|body_start_1|>
league = self.context.get('league')
... | BowlerDefinition | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BowlerDefinition:
def update(self, instance, validated_data):
"""Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return:"""
<|body_0|>
def validate_team(self, value):
"""Need to make sure that the team i... | stack_v2_sparse_classes_36k_train_027172 | 8,223 | no_license | [
{
"docstring": "Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return:",
"name": "update",
"signature": "def update(self, instance, validated_data)"
},
{
"docstring": "Need to make sure that the team is defined in the league that t... | 2 | stack_v2_sparse_classes_30k_train_014281 | Implement the Python class `BowlerDefinition` described below.
Class description:
Implement the BowlerDefinition class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return... | Implement the Python class `BowlerDefinition` described below.
Class description:
Implement the BowlerDefinition class.
Method signatures and docstrings:
- def update(self, instance, validated_data): Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return... | 8d2afcc5a8069d21e11d009def8b4a891fb43bc0 | <|skeleton|>
class BowlerDefinition:
def update(self, instance, validated_data):
"""Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return:"""
<|body_0|>
def validate_team(self, value):
"""Need to make sure that the team i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BowlerDefinition:
def update(self, instance, validated_data):
"""Update the object and remove the team if the context item is provided. :param instance: :param validated_data: :return:"""
_instance = super(BowlerDefinition, self).update(instance, validated_data)
if self.context.get('re... | the_stack_v2_python_sparse | bowling_entry/serializers/common.py | MeerkatLabs/Bowling-Entry | train | 0 | |
2b33396f1c98803d3e79ba9a3b70b5831876f668 | [
"form = self.form_class()\ndata_category = queries.get_all_data_category(reverse=True)\npaginator = Paginator(data_category, 10)\npage_number = request.GET.get('page')\npage_obj = paginator.get_page(page_number)\nreturn render(request, 'data_manager_app/dataCategory.html', {'form': form, 'datas': page_obj})",
"ur... | <|body_start_0|>
form = self.form_class()
data_category = queries.get_all_data_category(reverse=True)
paginator = Paginator(data_category, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'data_manager_app/dataCat... | DataCategoryView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataCategoryView:
def get(self, request):
"""get all data categories"""
<|body_0|>
def post(self, request):
"""add data category"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
form = self.form_class()
data_category = queries.get_all_data_ca... | stack_v2_sparse_classes_36k_train_027173 | 18,044 | no_license | [
{
"docstring": "get all data categories",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "add data category",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019153 | Implement the Python class `DataCategoryView` described below.
Class description:
Implement the DataCategoryView class.
Method signatures and docstrings:
- def get(self, request): get all data categories
- def post(self, request): add data category | Implement the Python class `DataCategoryView` described below.
Class description:
Implement the DataCategoryView class.
Method signatures and docstrings:
- def get(self, request): get all data categories
- def post(self, request): add data category
<|skeleton|>
class DataCategoryView:
def get(self, request):
... | 2dedee10bded628a0eaecacc4554b421cc6f0ddd | <|skeleton|>
class DataCategoryView:
def get(self, request):
"""get all data categories"""
<|body_0|>
def post(self, request):
"""add data category"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataCategoryView:
def get(self, request):
"""get all data categories"""
form = self.form_class()
data_category = queries.get_all_data_category(reverse=True)
paginator = Paginator(data_category, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_p... | the_stack_v2_python_sparse | data_model_manager_app/views/data_manager_views.py | SonThanhNguyen13/django_data_manager | train | 0 | |
8acb26eaefec70ccdff227346b3ee29b8ff90f84 | [
"answer = list()\nif root is not None:\n self.__traverse(root, answer)\nreturn answer",
"if node.left is not None:\n self.__traverse(node.left, answer)\nif node.right is not None:\n self.__traverse(node.right, answer)\nanswer.append(node.val)"
] | <|body_start_0|>
answer = list()
if root is not None:
self.__traverse(root, answer)
return answer
<|end_body_0|>
<|body_start_1|>
if node.left is not None:
self.__traverse(node.left, answer)
if node.right is not None:
self.__traverse(node.righ... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __traverse(self, node, answer):
""":type node: TreeNode :type answer: List[int] :rtype: None"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
an... | stack_v2_sparse_classes_36k_train_027174 | 1,125 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "postorderTraversal",
"signature": "def postorderTraversal(self, root)"
},
{
"docstring": ":type node: TreeNode :type answer: List[int] :rtype: None",
"name": "__traverse",
"signature": "def __traverse(self, node, answer)"
... | 2 | stack_v2_sparse_classes_30k_train_010212 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __traverse(self, node, answer): :type node: TreeNode :type answer: List[int] :rtype: None | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def postorderTraversal(self, root): :type root: TreeNode :rtype: List[int]
- def __traverse(self, node, answer): :type node: TreeNode :type answer: List[int] :rtype: None
<|skel... | c60b332866caa28e1ae5e216cbfc2c6f869a751a | <|skeleton|>
class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_0|>
def __traverse(self, node, answer):
""":type node: TreeNode :type answer: List[int] :rtype: None"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def postorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
answer = list()
if root is not None:
self.__traverse(root, answer)
return answer
def __traverse(self, node, answer):
""":type node: TreeNode :type answer: List[in... | the_stack_v2_python_sparse | leetcode/hard/tree/test_binary_tree_postorder_traversal.py | yenbohuang/online-contest-python | train | 0 | |
08b463d8d16a3f31c24c226dbc218f1910de4085 | [
"super(SequenceThumbnailTask, self).__init__(*args, **kwargs)\nself.setOption('width', self.__defaultWidth)\nself.setOption('height', self.__defaultHeight)",
"targetThumbnails = OrderedDict()\nfor crawler in self.crawlers():\n targetFilePath = self.target(crawler)\n if targetFilePath not in targetThumbnails... | <|body_start_0|>
super(SequenceThumbnailTask, self).__init__(*args, **kwargs)
self.setOption('width', self.__defaultWidth)
self.setOption('height', self.__defaultHeight)
<|end_body_0|>
<|body_start_1|>
targetThumbnails = OrderedDict()
for crawler in self.crawlers():
... | Creates a thumbnail for the image sequence. | SequenceThumbnailTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027175 | 1,609 | permissive | [
{
"docstring": "Create a sequence thumbnail object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | null | Implement the Python class `SequenceThumbnailTask` described below.
Class description:
Creates a thumbnail for the image sequence.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a sequence thumbnail object.
- def _perform(self): Perform the task. | Implement the Python class `SequenceThumbnailTask` described below.
Class description:
Creates a thumbnail for the image sequence.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a sequence thumbnail object.
- def _perform(self): Perform the task.
<|skeleton|>
class SequenceThumbnailT... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SequenceThumbnailTask:
"""Creates a thumbnail for the image sequence."""
def __init__(self, *args, **kwargs):
"""Create a sequence thumbnail object."""
super(SequenceThumbnailTask, self).__init__(*args, **kwargs)
self.setOption('width', self.__defaultWidth)
self.setOption(... | the_stack_v2_python_sparse | src/lib/kombi/Task/ImageSequence/SequenceThumbnailTask.py | kombiHQ/kombi | train | 2 |
b17e89269a56dc422d6f9ad639fbf14455020cfa | [
"self.index = index\nself.got_motion_plan = False\nrospy.Subscriber('mopat/control/motion_plan_{0}'.format(index), UInt32MultiArray, self.motion_plan_cb)",
"self.gen_pathx = []\nself.gen_pathy = []\nfor i in range(0, len(data.data) // 2):\n self.gen_pathx.append(data.data[i * 2])\n self.gen_pathy.append(dat... | <|body_start_0|>
self.index = index
self.got_motion_plan = False
rospy.Subscriber('mopat/control/motion_plan_{0}'.format(index), UInt32MultiArray, self.motion_plan_cb)
<|end_body_0|>
<|body_start_1|>
self.gen_pathx = []
self.gen_pathy = []
for i in range(0, len(data.data... | The robot plan class Parameters: index : robot's predefined index | robot_plan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class robot_plan:
"""The robot plan class Parameters: index : robot's predefined index"""
def __init__(self, index):
"""Well, initialize Arguments: index : robot's predefined index"""
<|body_0|>
def motion_plan_cb(self, data):
"""Get the motion plan for ith robot Argum... | stack_v2_sparse_classes_36k_train_027176 | 6,980 | no_license | [
{
"docstring": "Well, initialize Arguments: index : robot's predefined index",
"name": "__init__",
"signature": "def __init__(self, index)"
},
{
"docstring": "Get the motion plan for ith robot Arguments: data : ROS std_msgs/UInt32MultiArray",
"name": "motion_plan_cb",
"signature": "def m... | 2 | stack_v2_sparse_classes_30k_train_001982 | Implement the Python class `robot_plan` described below.
Class description:
The robot plan class Parameters: index : robot's predefined index
Method signatures and docstrings:
- def __init__(self, index): Well, initialize Arguments: index : robot's predefined index
- def motion_plan_cb(self, data): Get the motion pla... | Implement the Python class `robot_plan` described below.
Class description:
The robot plan class Parameters: index : robot's predefined index
Method signatures and docstrings:
- def __init__(self, index): Well, initialize Arguments: index : robot's predefined index
- def motion_plan_cb(self, data): Get the motion pla... | 048b260ca2f9ac49384a05fd3840c2e40126acb5 | <|skeleton|>
class robot_plan:
"""The robot plan class Parameters: index : robot's predefined index"""
def __init__(self, index):
"""Well, initialize Arguments: index : robot's predefined index"""
<|body_0|>
def motion_plan_cb(self, data):
"""Get the motion plan for ith robot Argum... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class robot_plan:
"""The robot plan class Parameters: index : robot's predefined index"""
def __init__(self, index):
"""Well, initialize Arguments: index : robot's predefined index"""
self.index = index
self.got_motion_plan = False
rospy.Subscriber('mopat/control/motion_plan_{0}... | the_stack_v2_python_sparse | ros_src/plot_node.py | chindimaga/MoPAT_Design | train | 0 |
cbef57d14d1a679357a84899a4d3881d4d0d9abb | [
"n = len(grid)\nans = 0\nfor i in range(n):\n for j in range(n):\n if grid[i][j]:\n ans += 2\n for r, c in ((i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)):\n if (r >= 0 and r < n) and (c >= 0 and c < n):\n val = grid[r][c]\n else:\n ... | <|body_start_0|>
n = len(grid)
ans = 0
for i in range(n):
for j in range(n):
if grid[i][j]:
ans += 2
for r, c in ((i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)):
if (r >= 0 and r < n) and (c >= 0 and c <... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
"""官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判断同行左列,上一行同列即可"""
<|body_0|>
def surfaceArea_2(self, grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k_train_027177 | 2,555 | no_license | [
{
"docstring": "官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判断同行左列,上一行同列即可",
"name": "surfaceArea",
"signature": "def surfaceArea(self, grid: List[List[int]]) -> int"
},
{
"docstring": "更简洁的方法: 统计立方体个数block,则共有block*... | 2 | stack_v2_sparse_classes_30k_train_001444 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def surfaceArea(self, grid: List[List[int]]) -> int: 官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def surfaceArea(self, grid: List[List[int]]) -> int: 官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判... | 0ec1a89e5b1e3d32af4da9693e9e5c36d4cd42eb | <|skeleton|>
class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
"""官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判断同行左列,上一行同列即可"""
<|body_0|>
def surfaceArea_2(self, grid: List[List[int]]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
"""官方题解:较难理解 若v>0,则顶面和底面分别贡献一个面,共计2个表面积 对于4个侧面,依次判断与之相邻的位置的值, 只有当v大于相邻位置的值nv时,才可以贡献表面积n-nv 否则不贡献表面积 ps: 其实该方法也可以按照下面的更简洁的方法优化,只判断同行左列,上一行同列即可"""
n = len(grid)
ans = 0
for i in range(n):
for j in range(n)... | the_stack_v2_python_sparse | 892.py | zhiweiguo/my_leetcode | train | 1 | |
e2c3824f9bcb320885d126719aa3da32d8356ecc | [
"test = u'\\x00\\u202a\\u202b\\u202c\\u202d\\u202e'\nexpected = u''\nresult = self.request.normalizePagename(test)\nself.assertEqual(result, expected, 'Expected \"%(expected)s\" but got \"%(result)s\"' % locals())",
"cases = ((u'/////', u''), (u'/a', u'a'), (u'a/', u'a'), (u'a/////b/////c', u'a/b/c'), (u'a b/////... | <|body_start_0|>
test = u'\x00\u202a\u202b\u202c\u202d\u202e'
expected = u''
result = self.request.normalizePagename(test)
self.assertEqual(result, expected, 'Expected "%(expected)s" but got "%(result)s"' % locals())
<|end_body_0|>
<|body_start_1|>
cases = ((u'/////', u''), (u'/... | NormalizePagenameTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
<|body_0|>
def testNormalizeSlashes(self):
"""request: normalize pagename: normalize slashes"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_027178 | 4,403 | no_license | [
{
"docstring": "request: normalize pagename: remove invalid unicode chars Assume the default setting",
"name": "testPageInvalidChars",
"signature": "def testPageInvalidChars(self)"
},
{
"docstring": "request: normalize pagename: normalize slashes",
"name": "testNormalizeSlashes",
"signat... | 4 | null | Implement the Python class `NormalizePagenameTestCase` described below.
Class description:
Implement the NormalizePagenameTestCase class.
Method signatures and docstrings:
- def testPageInvalidChars(self): request: normalize pagename: remove invalid unicode chars Assume the default setting
- def testNormalizeSlashes(... | Implement the Python class `NormalizePagenameTestCase` described below.
Class description:
Implement the NormalizePagenameTestCase class.
Method signatures and docstrings:
- def testPageInvalidChars(self): request: normalize pagename: remove invalid unicode chars Assume the default setting
- def testNormalizeSlashes(... | a17b987c5adaa13befb0fd74ac400c8edbe62ef5 | <|skeleton|>
class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
<|body_0|>
def testNormalizeSlashes(self):
"""request: normalize pagename: normalize slashes"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormalizePagenameTestCase:
def testPageInvalidChars(self):
"""request: normalize pagename: remove invalid unicode chars Assume the default setting"""
test = u'\x00\u202a\u202b\u202c\u202d\u202e'
expected = u''
result = self.request.normalizePagename(test)
self.assertEqu... | the_stack_v2_python_sparse | moin/lib/python2.4/site-packages/MoinMoin/_tests/test_request.py | imosts/flume | train | 0 | |
67182e49ae024550f7272ea4081b3a9712eacd29 | [
"res = []\n\ndef helper(root, res):\n if root:\n helper(root.left, res)\n res.append(root.val)\n helper(root.right, res)\n return res\nreturn helper(root, res)",
"stack = []\nres = []\nwhile True:\n if root:\n stack.append(root)\n root = root.left\n elif stack:\n ... | <|body_start_0|>
res = []
def helper(root, res):
if root:
helper(root.left, res)
res.append(root.val)
helper(root.right, res)
return res
return helper(root, res)
<|end_body_0|>
<|body_start_1|>
stack = []
r... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def inorder_rec(self, root):
"""Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call for the right subtree recursively."""
<|body_0|>
def inorder_iter(self, root):
... | stack_v2_sparse_classes_36k_train_027179 | 1,126 | no_license | [
{
"docstring": "Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call for the right subtree recursively.",
"name": "inorder_rec",
"signature": "def inorder_rec(self, root)"
},
{
"docstring": "Iterative... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorder_rec(self, root): Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def inorder_rec(self, root): Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call ... | 74194e660c2417f8d0c2a1b090dd41912e72efb3 | <|skeleton|>
class Solution:
def inorder_rec(self, root):
"""Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call for the right subtree recursively."""
<|body_0|>
def inorder_iter(self, root):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def inorder_rec(self, root):
"""Recursive. The stack is maintained by the language for us. In this easy to understand way, we just call for the left subtree, read the root and call for the right subtree recursively."""
res = []
def helper(root, res):
if root:
... | the_stack_v2_python_sparse | Extras/Inorder recursive and iterative.py | okaysidd/Interview_material | train | 0 | |
eb8696ec4c2a4408cbe2e773de8e8b03a4a6b8fe | [
"def _dfs(rest, wallet_id):\n if rest == 0:\n return 1\n res = 0\n for idx in range(wallet_id, len(coins)):\n if rest >= coins[idx]:\n res += _dfs(rest - coins[idx], idx)\n return res\nreturn _dfs(amount, 0)",
"dp = [0] * (amount + 1)\ndp[0] = 1\nfor idx in range(1, amount + 1... | <|body_start_0|>
def _dfs(rest, wallet_id):
if rest == 0:
return 1
res = 0
for idx in range(wallet_id, len(coins)):
if rest >= coins[idx]:
res += _dfs(rest - coins[idx], idx)
return res
return _dfs(amount... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_027180 | 2,720 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change",
"signature": "def change(self, amount, coins)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007967 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
<|s... | 085b8dfa8e12f7c39107bab60110cd3b182f0c13 | <|skeleton|>
class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def change(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
def _dfs(rest, wallet_id):
if rest == 0:
return 1
res = 0
for idx in range(wallet_id, len(coins)):
if rest >= coins[idx]:
... | the_stack_v2_python_sparse | eet/Coin_Change_2.py | wangyunge/algorithmpractice | train | 0 | |
c4112c969120817c018cc7706d82d4efc59b915a | [
"user_provider: UserProvider = module.load(provider.module).object()\nuser = await user_provider.retrieve_by_credentials(username, password, **provider.options)\nreturn user",
"if user.superadmin:\n return\nroute_permissions = scopes.scopes\nif not route_permissions:\n return\nfor permission in route_permis... | <|body_start_0|>
user_provider: UserProvider = module.load(provider.module).object()
user = await user_provider.retrieve_by_credentials(username, password, **provider.options)
return user
<|end_body_0|>
<|body_start_1|>
if user.superadmin:
return
route_permissions = ... | Base Auth middleware class | Auth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Auth:
"""Base Auth middleware class"""
async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]:
"""Retrieve user from User Provider backend"""
<|body_0|>
def validate_permissions(self, user: User, scopes: SecurityScopes) -> None:
... | stack_v2_sparse_classes_36k_train_027181 | 9,337 | permissive | [
{
"docstring": "Retrieve user from User Provider backend",
"name": "retrieve_user",
"signature": "async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]"
},
{
"docstring": "Validate logged in users permissions again route permissions",
"name": "validate... | 3 | null | Implement the Python class `Auth` described below.
Class description:
Base Auth middleware class
Method signatures and docstrings:
- async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]: Retrieve user from User Provider backend
- def validate_permissions(self, user: User, scop... | Implement the Python class `Auth` described below.
Class description:
Base Auth middleware class
Method signatures and docstrings:
- async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]: Retrieve user from User Provider backend
- def validate_permissions(self, user: User, scop... | 9c21b85e9e470c6d789899340332a9abd0b26ab1 | <|skeleton|>
class Auth:
"""Base Auth middleware class"""
async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]:
"""Retrieve user from User Provider backend"""
<|body_0|>
def validate_permissions(self, user: User, scopes: SecurityScopes) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Auth:
"""Base Auth middleware class"""
async def retrieve_user(self, username: str, password: str, provider: Dict) -> Optional[User]:
"""Retrieve user from User Provider backend"""
user_provider: UserProvider = module.load(provider.module).object()
user = await user_provider.retri... | the_stack_v2_python_sparse | uvicore/auth/middleware/auth_OLD.py | webclinic017/framework | train | 0 |
48ea98bd23f30124ef17e5a15fb824db40c94602 | [
"my_dim = symbol.shape[index]\nif isinstance(my_dim, ArrayType.ArrayBounds):\n lower_bound = my_dim.lower.copy()\n upper_bound = my_dim.upper.copy()\n step = Literal('1', INTEGER_TYPE)\n return (lower_bound, upper_bound, step)\nlower_bound = BinaryOperation.create(BinaryOperation.Operator.LBOUND, Refere... | <|body_start_0|>
my_dim = symbol.shape[index]
if isinstance(my_dim, ArrayType.ArrayBounds):
lower_bound = my_dim.lower.copy()
upper_bound = my_dim.upper.copy()
step = Literal('1', INTEGER_TYPE)
return (lower_bound, upper_bound, step)
lower_bound = ... | Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranReader >>> from psyclone.psyir.nodes import Reference >>> from psyclone.psyir.transformations i... | Reference2ArrayRangeTrans | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reference2ArrayRangeTrans:
"""Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranReader >>> from psyclone.psyir.nodes impor... | stack_v2_sparse_classes_36k_train_027182 | 8,629 | permissive | [
{
"docstring": "A utility function that returns the appropriate loop bounds (lower, upper and step) for an array dimension. If the array dimension is declared with known bounds (an integer or a symbol) then these bound values are used. If the size is unknown (a deferred or attribute type) then the LBOUND and UB... | 3 | stack_v2_sparse_classes_30k_train_014569 | Implement the Python class `Reference2ArrayRangeTrans` described below.
Class description:
Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranRea... | Implement the Python class `Reference2ArrayRangeTrans` described below.
Class description:
Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranRea... | 0b149bc5a76ca85c1dd086c3aa813102d0d04b56 | <|skeleton|>
class Reference2ArrayRangeTrans:
"""Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranReader >>> from psyclone.psyir.nodes impor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reference2ArrayRangeTrans:
"""Provides a transformation from PSyIR Array Notation (a reference to an Array) to a PSyIR Range. For example: >>> from psyclone.psyir.backend.fortran import FortranWriter >>> from psyclone.psyir.frontend.fortran import FortranReader >>> from psyclone.psyir.nodes import Reference >... | the_stack_v2_python_sparse | src/psyclone/psyir/transformations/reference2arrayrange_trans.py | stfc/PSyclone | train | 100 |
5941b852eabd3249c528b15a7ac173121b2c64dc | [
"self.input_path = input\nself.pack_name = get_pack_name(file_path=self.input_path)\nself.pack_path = os.path.join(PACKS_DIR, self.pack_name)\nself.input_file_name = os.path.basename(self.input_path).rstrip('.json')\nself.use_force = force\nself.marketplace = marketplace\nif output:\n if not os.path.isdir(output... | <|body_start_0|>
self.input_path = input
self.pack_name = get_pack_name(file_path=self.input_path)
self.pack_path = os.path.join(PACKS_DIR, self.pack_name)
self.input_file_name = os.path.basename(self.input_path).rstrip('.json')
self.use_force = force
self.marketplace = m... | Unifies a GenericModule object with it's Dashboards | GenericModuleUnifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output:... | stack_v2_sparse_classes_36k_train_027183 | 4,492 | permissive | [
{
"docstring": "Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output: The output dir to write the unified GenericModule json to. force: if True - Forcefully overwrites the preexisting unified GenericModule file if one exists.",
"name": "__init__",
"signature": "def ... | 4 | null | Implement the Python class `GenericModuleUnifier` described below.
Class description:
Unifies a GenericModule object with it's Dashboards
Method signatures and docstrings:
- def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs): Init a GenericModuleUnifier Args: ... | Implement the Python class `GenericModuleUnifier` described below.
Class description:
Unifies a GenericModule object with it's Dashboards
Method signatures and docstrings:
- def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs): Init a GenericModuleUnifier Args: ... | 3169757a2f98c8457e46572bf656ec6b69cc3a2e | <|skeleton|>
class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenericModuleUnifier:
"""Unifies a GenericModule object with it's Dashboards"""
def __init__(self, input: str, output: str='', force: bool=False, marketplace: Optional[str]=None, **kwargs):
"""Init a GenericModuleUnifier Args: input: a path of the GenericModule file to unify. output: The output d... | the_stack_v2_python_sparse | demisto_sdk/commands/prepare_content/generic_module_unifier.py | demisto/demisto-sdk | train | 63 |
397a2c8d131ab6b124a0bf7379863e6f1510a78f | [
"Utils.validate_uuid(muscle_test_id)\nif not MuscleTest.objects.filter(id=muscle_test_id).exists():\n raise ValidationError('The muscle test is not valid!')",
"BodyZoneService.is_valid_body_zone(muscle_test['body_zone'])\nnew_muscle_test = MuscleTest.objects.create(strength=muscle_test['strength'], body_zone_i... | <|body_start_0|>
Utils.validate_uuid(muscle_test_id)
if not MuscleTest.objects.filter(id=muscle_test_id).exists():
raise ValidationError('The muscle test is not valid!')
<|end_body_0|>
<|body_start_1|>
BodyZoneService.is_valid_body_zone(muscle_test['body_zone'])
new_muscle_t... | Service class for muscle test related operations | MuscleTestService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MuscleTestService:
"""Service class for muscle test related operations"""
def is_valid_muscle_test(muscle_test_id):
"""Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test"""
<|body_0|>
def add_muscle_test(muscle_test, id_treatment):
... | stack_v2_sparse_classes_36k_train_027184 | 2,092 | no_license | [
{
"docstring": "Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test",
"name": "is_valid_muscle_test",
"signature": "def is_valid_muscle_test(muscle_test_id)"
},
{
"docstring": "Creates a muscle test for a new treatment :param muscle_test: Muscle test info :par... | 3 | null | Implement the Python class `MuscleTestService` described below.
Class description:
Service class for muscle test related operations
Method signatures and docstrings:
- def is_valid_muscle_test(muscle_test_id): Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test
- def add_muscle_tes... | Implement the Python class `MuscleTestService` described below.
Class description:
Service class for muscle test related operations
Method signatures and docstrings:
- def is_valid_muscle_test(muscle_test_id): Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test
- def add_muscle_tes... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class MuscleTestService:
"""Service class for muscle test related operations"""
def is_valid_muscle_test(muscle_test_id):
"""Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test"""
<|body_0|>
def add_muscle_test(muscle_test, id_treatment):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MuscleTestService:
"""Service class for muscle test related operations"""
def is_valid_muscle_test(muscle_test_id):
"""Checks if the specified muscle_test exists :param muscle_test_id: if of the muscle_test"""
Utils.validate_uuid(muscle_test_id)
if not MuscleTest.objects.filter(id... | the_stack_v2_python_sparse | backend/martin_helder/services/muscle_test_service.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
7ed3280b64944c8ae65bf69e47f47bf6852656a6 | [
"obj.save()\ngenerate_static_list_search_html.delay('list.html')\ngenerate_static_list_search_html.delay('search.html')",
"obj.delete()\ngenerate_static_list_search_html.delay('list.html')\ngenerate_static_list_search_html.delay('search.html')"
] | <|body_start_0|>
obj.save()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('search.html')
<|end_body_0|>
<|body_start_1|>
obj.delete()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('... | 自定义管理admin站点 -- 商品类别 | GoodsCategoryAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj.sav... | stack_v2_sparse_classes_36k_train_027185 | 3,322 | no_license | [
{
"docstring": "admin后台新增或修改了数据时调用",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "admin后台删除了数据时调用",
"name": "delete_model",
"signature": "def delete_model(self, request, obj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015774 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
自定义管理admin站点 -- 商品类别
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用 | Implement the Python class `GoodsCategoryAdmin` described below.
Class description:
自定义管理admin站点 -- 商品类别
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): admin后台新增或修改了数据时调用
- def delete_model(self, request, obj): admin后台删除了数据时调用
<|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理... | c841e7d1aa0616b070b10924f44b2c418f222cd8 | <|skeleton|>
class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
<|body_0|>
def delete_model(self, request, obj):
"""admin后台删除了数据时调用"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoodsCategoryAdmin:
"""自定义管理admin站点 -- 商品类别"""
def save_model(self, request, obj, form, change):
"""admin后台新增或修改了数据时调用"""
obj.save()
generate_static_list_search_html.delay('list.html')
generate_static_list_search_html.delay('search.html')
def delete_model(self, reques... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/goods/admin.py | Echo-xie/meiduo_mall | train | 0 |
1eeed0ac1c93e1a36c75a1ff5d56c65dae791608 | [
"variable_values = {'urn': urn, 'sourceType': source_type, 'operationType': operation_type, 'numAffectedRows': num_affected_rows}\nif partition is not None:\n variable_values['partition'] = partition\nif num_affected_rows is not None:\n variable_values['numAffectedRows'] = num_affected_rows\nif custom_propert... | <|body_start_0|>
variable_values = {'urn': urn, 'sourceType': source_type, 'operationType': operation_type, 'numAffectedRows': num_affected_rows}
if partition is not None:
variable_values['partition'] = partition
if num_affected_rows is not None:
variable_values['numAffec... | Operation | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Operation:
def report_operation(self, urn: str, source_type: str='DATA_PROCESS', operation_type: str='UPDATE', partition: Optional[str]=None, num_affected_rows: int=0, custom_properties: Optional[Dict[str, str]]=None) -> str:
"""Report operation metadata for a dataset. :param source_type... | stack_v2_sparse_classes_36k_train_027186 | 5,116 | permissive | [
{
"docstring": "Report operation metadata for a dataset. :param source_type: The source type to filter on. If not set it will accept any source type. Default value: DATA_PROCESS See valid types here: https://datahubproject.io/docs/graphql/enums#operationsourcetype :param operation_type: The operation type to fi... | 2 | null | Implement the Python class `Operation` described below.
Class description:
Implement the Operation class.
Method signatures and docstrings:
- def report_operation(self, urn: str, source_type: str='DATA_PROCESS', operation_type: str='UPDATE', partition: Optional[str]=None, num_affected_rows: int=0, custom_properties: ... | Implement the Python class `Operation` described below.
Class description:
Implement the Operation class.
Method signatures and docstrings:
- def report_operation(self, urn: str, source_type: str='DATA_PROCESS', operation_type: str='UPDATE', partition: Optional[str]=None, num_affected_rows: int=0, custom_properties: ... | 8cf299aeb43fa95afb22fefbc7728117c727f0b3 | <|skeleton|>
class Operation:
def report_operation(self, urn: str, source_type: str='DATA_PROCESS', operation_type: str='UPDATE', partition: Optional[str]=None, num_affected_rows: int=0, custom_properties: Optional[Dict[str, str]]=None) -> str:
"""Report operation metadata for a dataset. :param source_type... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Operation:
def report_operation(self, urn: str, source_type: str='DATA_PROCESS', operation_type: str='UPDATE', partition: Optional[str]=None, num_affected_rows: int=0, custom_properties: Optional[Dict[str, str]]=None) -> str:
"""Report operation metadata for a dataset. :param source_type: The source t... | the_stack_v2_python_sparse | metadata-ingestion/src/datahub/api/graphql/operation.py | RyanHolstien/datahub | train | 0 | |
258f7eab83b5b16548715c303c9cc5958e4ba538 | [
"if mode.passCount == 0:\n render_data = mode.cache.getData(self)\n if render_data is None:\n render_data = self.compile(mode)\n if not render_data:\n return\n texture, vert_vbo, index_vbo, shader, vertex_loc, mvp_matrix_loc = render_data\n if clear:\n glClear(GL_COLOR_BU... | <|body_start_0|>
if mode.passCount == 0:
render_data = mode.cache.getData(self)
if render_data is None:
render_data = self.compile(mode)
if not render_data:
return
texture, vert_vbo, index_vbo, shader, vertex_loc, mvp_matrix... | _CubeBackground | [
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CubeBackground:
def Render(self, mode, clear=1):
"""Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After it's finished, it clears the depth-buffer to make the geometry appear "behind" everything else."""
... | stack_v2_sparse_classes_36k_train_027187 | 7,125 | permissive | [
{
"docstring": "Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After it's finished, it clears the depth-buffer to make the geometry appear \"behind\" everything else.",
"name": "Render",
"signature": "def Render(self, mode, cl... | 2 | null | Implement the Python class `_CubeBackground` described below.
Class description:
Implement the _CubeBackground class.
Method signatures and docstrings:
- def Render(self, mode, clear=1): Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After ... | Implement the Python class `_CubeBackground` described below.
Class description:
Implement the _CubeBackground class.
Method signatures and docstrings:
- def Render(self, mode, clear=1): Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After ... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class _CubeBackground:
def Render(self, mode, clear=1):
"""Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After it's finished, it clears the depth-buffer to make the geometry appear "behind" everything else."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CubeBackground:
def Render(self, mode, clear=1):
"""Render the cube background This renders those of our cube-faces which are facing us, and which have a non-0 component-count. After it's finished, it clears the depth-buffer to make the geometry appear "behind" everything else."""
if mode.pas... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/cubebackground.py | alexus37/AugmentedRealityChess | train | 1 | |
2af4d76663ab5d8cbf063f6569f5e8dfe3733076 | [
"self.node_ids = node_ids\nself.target_sw_version = target_sw_version\nself.upgrade_all_free_nodes = upgrade_all_free_nodes\nself.upgrade_self = upgrade_self",
"if dictionary is None:\n return None\nnode_ids = dictionary.get('nodeIds')\ntarget_sw_version = dictionary.get('targetSwVersion')\nupgrade_all_free_no... | <|body_start_0|>
self.node_ids = node_ids
self.target_sw_version = target_sw_version
self.upgrade_all_free_nodes = upgrade_all_free_nodes
self.upgrade_self = upgrade_self
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
node_ids = dictionary... | Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free Nodes present on the same local network as the Node that the request was sent to. The I... | UpgradeNodeParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpgradeNodeParameters:
"""Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free Nodes present on the same local networ... | stack_v2_sparse_classes_36k_train_027188 | 3,097 | permissive | [
{
"docstring": "Constructor for the UpgradeNodeParameters class",
"name": "__init__",
"signature": "def __init__(self, node_ids=None, target_sw_version=None, upgrade_all_free_nodes=None, upgrade_self=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (... | 2 | stack_v2_sparse_classes_30k_train_008397 | Implement the Python class `UpgradeNodeParameters` described below.
Class description:
Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free... | Implement the Python class `UpgradeNodeParameters` described below.
Class description:
Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class UpgradeNodeParameters:
"""Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free Nodes present on the same local networ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpgradeNodeParameters:
"""Implementation of the 'UpgradeNodeParameters' model. Specifies the parameters needed for a Node upgrade request. Attributes: node_ids (list of long|int): Specifies a list of IDs of additional nodes to be upgraded. These must be free Nodes present on the same local network as the Node... | the_stack_v2_python_sparse | cohesity_management_sdk/models/upgrade_node_parameters.py | cohesity/management-sdk-python | train | 24 |
d33f5928e4414fbed5d4a09ae32baa2c6f413c19 | [
"super().__init__()\nassert attention_size % n_heads == 0\nself.hidden_size = hidden_size\nself.n_heads = n_heads\nself.head_size = attention_size // n_heads\nself.attention_size = attention_size\nself.hidden_to_query = nn.Linear(hidden_size, attention_size)\nself.hidden_to_key = nn.Linear(hidden_size, attention_si... | <|body_start_0|>
super().__init__()
assert attention_size % n_heads == 0
self.hidden_size = hidden_size
self.n_heads = n_heads
self.head_size = attention_size // n_heads
self.attention_size = attention_size
self.hidden_to_query = nn.Linear(hidden_size, attention_s... | Multihead self-attention | MultiHeadAttention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of hea... | stack_v2_sparse_classes_36k_train_027189 | 14,969 | permissive | [
{
"docstring": "Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of heads (attention heads) dropout (double): dropout rate device (string): cuda or cpu",
"name": "__init__",
"signature": "def __init__(self, hidden_size: int, attent... | 2 | stack_v2_sparse_classes_30k_train_016675 | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multihead self-attention
Method signatures and docstrings:
- def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str): Constructor Args: hidden_size (int): hidden size of the input. attentio... | Implement the Python class `MultiHeadAttention` described below.
Class description:
Multihead self-attention
Method signatures and docstrings:
- def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str): Constructor Args: hidden_size (int): hidden size of the input. attentio... | 5b4a61b5dd0bc259ffe68223877949ef4ebfa5e3 | <|skeleton|>
class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of hea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiHeadAttention:
"""Multihead self-attention"""
def __init__(self, hidden_size: int, attention_size: int, n_heads: int, dropout: float, device: str):
"""Constructor Args: hidden_size (int): hidden size of the input. attention_size (int): attention size n_heads (int): number of heads (attention... | the_stack_v2_python_sparse | src/models/anomalia/layers.py | maurony/ts-vrae | train | 1 |
c8d5530c1306f9d56ff03960f82add02036776c3 | [
"from tornado.ioloop import IOLoop\nfrom ..models import DBSession, EventObservationPlan\nplan = EventObservationPlan.query.filter_by(plan_name=request.payload['queue_name']).first()\nif plan is None:\n required_parameters = {'start_date', 'end_date', 'schedule_type', 'schedule_strategy', 'filter_strategy', 'exp... | <|body_start_0|>
from tornado.ioloop import IOLoop
from ..models import DBSession, EventObservationPlan
plan = EventObservationPlan.query.filter_by(plan_name=request.payload['queue_name']).first()
if plan is None:
required_parameters = {'start_date', 'end_date', 'schedule_typ... | An interface to MMA operations. | MMAAPI | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MMAAPI:
"""An interface to MMA operations."""
def submit(request):
"""Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan."""
<|body_0|>
def delete(request_id):
"""Delet... | stack_v2_sparse_classes_36k_train_027190 | 14,540 | permissive | [
{
"docstring": "Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan.",
"name": "submit",
"signature": "def submit(request)"
},
{
"docstring": "Delete an observation plan from list. Parameters ----------... | 2 | null | Implement the Python class `MMAAPI` described below.
Class description:
An interface to MMA operations.
Method signatures and docstrings:
- def submit(request): Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan.
- def dele... | Implement the Python class `MMAAPI` described below.
Class description:
An interface to MMA operations.
Method signatures and docstrings:
- def submit(request): Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan.
- def dele... | 2433d5ae0b2f41faac3c76ed4ae8d9a4da5522fb | <|skeleton|>
class MMAAPI:
"""An interface to MMA operations."""
def submit(request):
"""Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan."""
<|body_0|>
def delete(request_id):
"""Delet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MMAAPI:
"""An interface to MMA operations."""
def submit(request):
"""Generate an observation plan. Parameters ---------- request: skyportal.models.ObservationPlanRequest The request to generate the observation plan."""
from tornado.ioloop import IOLoop
from ..models import DBSess... | the_stack_v2_python_sparse | skyportal/facility_apis/observation_plan.py | dmitryduev/skyportal | train | 1 |
9efd2c2fa03dd092c0269a3975ec56c0777c6684 | [
"self._attr_name = name\nself._query = query\nself._attr_native_unit_of_measurement = unit\nself._template = value_template\nself._column_name = column\nself.sessionmaker = sessmaker\nself._attr_extra_state_attributes = {}",
"data = None\nself._attr_extra_state_attributes = {}\nsess: scoped_session = self.session... | <|body_start_0|>
self._attr_name = name
self._query = query
self._attr_native_unit_of_measurement = unit
self._template = value_template
self._column_name = column
self.sessionmaker = sessmaker
self._attr_extra_state_attributes = {}
<|end_body_0|>
<|body_start_1|... | Representation of an SQL sensor. | SQLSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLSensor:
"""Representation of an SQL sensor."""
def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None:
"""Initialize the SQL sensor."""
<|body_0|>
def update(self) -> None:
"... | stack_v2_sparse_classes_36k_train_027191 | 5,560 | permissive | [
{
"docstring": "Initialize the SQL sensor.",
"name": "__init__",
"signature": "def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None"
},
{
"docstring": "Retrieve sensor data from the query.",
"name": "upda... | 2 | null | Implement the Python class `SQLSensor` described below.
Class description:
Representation of an SQL sensor.
Method signatures and docstrings:
- def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None: Initialize the SQL sensor.
- def... | Implement the Python class `SQLSensor` described below.
Class description:
Representation of an SQL sensor.
Method signatures and docstrings:
- def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None: Initialize the SQL sensor.
- def... | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | <|skeleton|>
class SQLSensor:
"""Representation of an SQL sensor."""
def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None:
"""Initialize the SQL sensor."""
<|body_0|>
def update(self) -> None:
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLSensor:
"""Representation of an SQL sensor."""
def __init__(self, name: str, sessmaker: scoped_session, query: str, column: str, unit: str | None, value_template: Template | None) -> None:
"""Initialize the SQL sensor."""
self._attr_name = name
self._query = query
self.... | the_stack_v2_python_sparse | homeassistant/components/sql/sensor.py | JeffLIrion/home-assistant | train | 5 |
ddf049bfa7ab923bdbd8164c8b3a53fd3c8f7e4d | [
"def _mock_handle_style_error(self):\n pass\nchecker = CMakeChecker('foo.cmake', _mock_handle_style_error)\nself.assertEqual(checker._handle_style_error, _mock_handle_style_error)",
"errors = []\n\ndef _mock_handle_style_error(line_number, category, confidence, message):\n error = (line_number, category, co... | <|body_start_0|>
def _mock_handle_style_error(self):
pass
checker = CMakeChecker('foo.cmake', _mock_handle_style_error)
self.assertEqual(checker._handle_style_error, _mock_handle_style_error)
<|end_body_0|>
<|body_start_1|>
errors = []
def _mock_handle_style_error(l... | Tests CMakeChecker class. | CMakeCheckerTest | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CMakeCheckerTest:
"""Tests CMakeChecker class."""
def test_init(self):
"""Test __init__() method."""
<|body_0|>
def test_check(self):
"""Test check() method."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def _mock_handle_style_error(self):
... | stack_v2_sparse_classes_36k_train_027192 | 5,918 | permissive | [
{
"docstring": "Test __init__() method.",
"name": "test_init",
"signature": "def test_init(self)"
},
{
"docstring": "Test check() method.",
"name": "test_check",
"signature": "def test_check(self)"
}
] | 2 | null | Implement the Python class `CMakeCheckerTest` described below.
Class description:
Tests CMakeChecker class.
Method signatures and docstrings:
- def test_init(self): Test __init__() method.
- def test_check(self): Test check() method. | Implement the Python class `CMakeCheckerTest` described below.
Class description:
Tests CMakeChecker class.
Method signatures and docstrings:
- def test_init(self): Test __init__() method.
- def test_check(self): Test check() method.
<|skeleton|>
class CMakeCheckerTest:
"""Tests CMakeChecker class."""
def t... | 5442d418b87d0da161429ffa5cb83777e9b38e4d | <|skeleton|>
class CMakeCheckerTest:
"""Tests CMakeChecker class."""
def test_init(self):
"""Test __init__() method."""
<|body_0|>
def test_check(self):
"""Test check() method."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CMakeCheckerTest:
"""Tests CMakeChecker class."""
def test_init(self):
"""Test __init__() method."""
def _mock_handle_style_error(self):
pass
checker = CMakeChecker('foo.cmake', _mock_handle_style_error)
self.assertEqual(checker._handle_style_error, _mock_handl... | the_stack_v2_python_sparse | WebKit/Tools/Scripts/webkitpy/style/checkers/cmake_unittest.py | adzhou/oragle | train | 0 |
4eb42e5198377ae2a6325ce8594b31b9d5e9e608 | [
"caches = []\nactivations = features\nnum_layers = len(parameters) // 2\nfor layer in range(1, num_layers):\n previous_activations = activations\n activations, cache = self.linear_activation_forward(previous_activations, parameters[f'W{layer}'], parameters[f'b{layer}'], activation_func=relu)\n caches.appen... | <|body_start_0|>
caches = []
activations = features
num_layers = len(parameters) // 2
for layer in range(1, num_layers):
previous_activations = activations
activations, cache = self.linear_activation_forward(previous_activations, parameters[f'W{layer}'], parameter... | DidacticCourseraNetwork | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DidacticCourseraNetwork:
def forward(self, features, parameters):
"""Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Re... | stack_v2_sparse_classes_36k_train_027193 | 20,590 | permissive | [
{
"docstring": "Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- last post-activation value caches -- list of caches containing: ... | 3 | null | Implement the Python class `DidacticCourseraNetwork` described below.
Class description:
Implement the DidacticCourseraNetwork class.
Method signatures and docstrings:
- def forward(self, features, parameters): Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- dat... | Implement the Python class `DidacticCourseraNetwork` described below.
Class description:
Implement the DidacticCourseraNetwork class.
Method signatures and docstrings:
- def forward(self, features, parameters): Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- dat... | 8dc24817556c2a1932b6553175f7366ea31d1c74 | <|skeleton|>
class DidacticCourseraNetwork:
def forward(self, features, parameters):
"""Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DidacticCourseraNetwork:
def forward(self, features, parameters):
"""Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation Arguments: X -- data, numpy array of shape (input size, number of examples) parameters -- output of initialize_parameters_deep() Returns: AL -- l... | the_stack_v2_python_sparse | basic_ml/src/neural_networks/base/networks.py | jmetzz/ml-laboratory | train | 1 | |
84059e77611c3279dd00145891df7a9045b3a054 | [
"f = self.dtype_f(self.init)\nv = u.flatten()\nf.impl[:] = (self.A.dot(v) - 1.0 / self.eps ** 2 * v ** (self.nu + 1)).reshape(self.nvars)\nf.expl[:] = (1.0 / self.eps ** 2 * v).reshape(self.nvars)\nreturn f",
"u = self.dtype_u(u0).flatten()\nz = self.dtype_u(self.init, val=0.0).flatten()\nnu = self.nu\neps2 = sel... | <|body_start_0|>
f = self.dtype_f(self.init)
v = u.flatten()
f.impl[:] = (self.A.dot(v) - 1.0 / self.eps ** 2 * v ** (self.nu + 1)).reshape(self.nvars)
f.expl[:] = (1.0 / self.eps ** 2 * v).reshape(self.nvars)
return f
<|end_body_0|>
<|body_start_1|>
u = self.dtype_u(u0)... | Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting | allencahn_semiimplicit_v2 | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class allencahn_semiimplicit_v2:
"""Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting"""
def eval_f(self, u, t):
"""Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical solution. t :... | stack_v2_sparse_classes_36k_train_027194 | 19,427 | permissive | [
{
"docstring": "Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical solution. t : float Current time of the numerical solution is computed. Returns ------- f : dtype_f The right-hand side of the problem.",
"name": "eval_f",
"signature... | 2 | null | Implement the Python class `allencahn_semiimplicit_v2` described below.
Class description:
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
Method signatures and docstrings:
- def eval_f(self, u, t): Routine to evaluate the right-hand side of the problem. Parameters ---------- ... | Implement the Python class `allencahn_semiimplicit_v2` described below.
Class description:
Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting
Method signatures and docstrings:
- def eval_f(self, u, t): Routine to evaluate the right-hand side of the problem. Parameters ---------- ... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class allencahn_semiimplicit_v2:
"""Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting"""
def eval_f(self, u, t):
"""Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical solution. t :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class allencahn_semiimplicit_v2:
"""Example implementing the Allen-Cahn equation in 2D with finite differences, AC splitting"""
def eval_f(self, u, t):
"""Routine to evaluate the right-hand side of the problem. Parameters ---------- u : dtype_u Current values of the numerical solution. t : float Curren... | the_stack_v2_python_sparse | pySDC/implementations/problem_classes/AllenCahn_2D_FD.py | Parallel-in-Time/pySDC | train | 30 |
88d6034c9946a018c59cf6199e12a31f06ec303c | [
"tck_u, fp, ier, msg = splprep([x, y], s=s, k=k, nest=nest, full_output=1)\nif ier > 0:\n print('{}. ier={}'.format(msg, ier))\nreturn (tck_u, fp)",
"n_coords = len(x)\nn_len = n_coords * zoom\nx_ip, y_ip = splev(np.linspace(0, 1, n_len), tck)\nreturn (x_ip, y_ip)"
] | <|body_start_0|>
tck_u, fp, ier, msg = splprep([x, y], s=s, k=k, nest=nest, full_output=1)
if ier > 0:
print('{}. ier={}'.format(msg, ier))
return (tck_u, fp)
<|end_body_0|>
<|body_start_1|>
n_coords = len(x)
n_len = n_coords * zoom
x_ip, y_ip = splev(np.lins... | Splines | [
"LicenseRef-scancode-cecill-b-en",
"CECILL-B"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Splines:
def compSplineKnots(self, x, y, s, k, nest=-1):
"""Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness parameter :k - spline order :nest - estimate of number of knots needed (-1 = maximal)"""
<|body_... | stack_v2_sparse_classes_36k_train_027195 | 2,617 | permissive | [
{
"docstring": "Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness parameter :k - spline order :nest - estimate of number of knots needed (-1 = maximal)",
"name": "compSplineKnots",
"signature": "def compSplineKnots(self, x, y, s, ... | 2 | null | Implement the Python class `Splines` described below.
Class description:
Implement the Splines class.
Method signatures and docstrings:
- def compSplineKnots(self, x, y, s, k, nest=-1): Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness paramete... | Implement the Python class `Splines` described below.
Class description:
Implement the Splines class.
Method signatures and docstrings:
- def compSplineKnots(self, x, y, s, k, nest=-1): Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness paramete... | 008881bd836581c78834ded8f37905eb38f4d3cf | <|skeleton|>
class Splines:
def compSplineKnots(self, x, y, s, k, nest=-1):
"""Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness parameter :k - spline order :nest - estimate of number of knots needed (-1 = maximal)"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Splines:
def compSplineKnots(self, x, y, s, k, nest=-1):
"""Computed with Scipy splprep. Find the B-spline representation of an N-dimensional curve. Spline parameters: :s - smoothness parameter :k - spline order :nest - estimate of number of knots needed (-1 = maximal)"""
tck_u, fp, ier, msg =... | the_stack_v2_python_sparse | syspy/spatial/geometry_smoothing.py | systragroup/quetzal | train | 43 | |
5b25b6694ff4effeaa733a1b12c8410b17d15ba5 | [
"if not root:\n return None\nrootNode = TreeNode(root.val)\nqueue = deque([(rootNode, root)])\nwhile queue:\n parent, curr = queue.popleft()\n prevBNode = None\n headBNode = None\n for child in curr.children:\n newBNode = TreeNode(child.val)\n if prevBNode:\n prevBNode.right ... | <|body_start_0|>
if not root:
return None
rootNode = TreeNode(root.val)
queue = deque([(rootNode, root)])
while queue:
parent, curr = queue.popleft()
prevBNode = None
headBNode = None
for child in curr.children:
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_027196 | 6,979 | no_license | [
{
"docstring": "Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode",
"name": "encode",
"signature": "def encode(self, root)"
},
{
"docstring": "Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node",
"name": "decode",
"signature": "def decode... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, root): Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode
- def decode(self, data): Decodes your binary tree to an n-ary tree. :type data: TreeN... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
<|body_0|>
def decode(self, data):
"""Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, root):
"""Encodes an n-ary tree to a binary tree. :type root: Node :rtype: TreeNode"""
if not root:
return None
rootNode = TreeNode(root.val)
queue = deque([(rootNode, root)])
while queue:
parent, curr = queue.popleft()
... | the_stack_v2_python_sparse | Python/431_EncodeNaryTreetoBinaryTree.py | here0009/LeetCode | train | 1 | |
7f59b632406cdaeac308f2d1fc2b5c4cc42b836d | [
"CMAdb.log = log\nCMAdb.debug = debug\nCMAdb.debug = True\nCMAdb.io = io\nCMAdb.store = store\nself.db = db\nself.store: Store = store\nself.io = io\nself.debug = debug\nif cleanoutdb:\n CMAdb.log.info('Re-initializing the NEO4j database')\n print('Re-initializing the NEO4j database to empty', file=stderr)\n ... | <|body_start_0|>
CMAdb.log = log
CMAdb.debug = debug
CMAdb.debug = True
CMAdb.io = io
CMAdb.store = store
self.db = db
self.store: Store = store
self.io = io
self.debug = debug
if cleanoutdb:
CMAdb.log.info('Re-initializing the ... | The CMAinit class | CMAinit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CMAinit:
"""The CMAinit class"""
def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True):
"""Initialize and construct a global database instance"""
<|body_0|>
def uninit():
"""Undo initiali... | stack_v2_sparse_classes_36k_train_027197 | 22,305 | no_license | [
{
"docstring": "Initialize and construct a global database instance",
"name": "__init__",
"signature": "def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True)"
},
{
"docstring": "Undo initialization to make sure we aren't... | 3 | null | Implement the Python class `CMAinit` described below.
Class description:
The CMAinit class
Method signatures and docstrings:
- def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True): Initialize and construct a global database instance
- def un... | Implement the Python class `CMAinit` described below.
Class description:
The CMAinit class
Method signatures and docstrings:
- def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True): Initialize and construct a global database instance
- def un... | 9ac993317c6501cb1e1cf09025f43dbe1d015035 | <|skeleton|>
class CMAinit:
"""The CMAinit class"""
def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True):
"""Initialize and construct a global database instance"""
<|body_0|>
def uninit():
"""Undo initiali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CMAinit:
"""The CMAinit class"""
def __init__(self, io, db=None, store=None, log=None, cleanoutdb=False, debug=False, encryption_required=False, use_network=True):
"""Initialize and construct a global database instance"""
CMAdb.log = log
CMAdb.debug = debug
CMAdb.debug = T... | the_stack_v2_python_sparse | cma/cmainit.py | assimilation/assimilation-official | train | 52 |
b0885d3fa034851753d0eeb9698a7f22fb479700 | [
"if where_clause_type is WhereClauseTypes.Is:\n return '{}{}{} IS {}'.format('NOT ' if negation else '', table_name + '.' if table_name else '', column_name, values[0])\nelif where_clause_type is WhereClauseTypes.In:\n return '{}{}{} IN ({})'.format('NOT ' if negation else '', table_name + '.' if table_name e... | <|body_start_0|>
if where_clause_type is WhereClauseTypes.Is:
return '{}{}{} IS {}'.format('NOT ' if negation else '', table_name + '.' if table_name else '', column_name, values[0])
elif where_clause_type is WhereClauseTypes.In:
return '{}{}{} IN ({})'.format('NOT ' if negation ... | WhereClauseTypes | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked w... | stack_v2_sparse_classes_36k_train_027198 | 10,669 | permissive | [
{
"docstring": "Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked with the values. :type column_name: str :param where_clause_type: The type of the where clause. :type where_clause_type: WhereClauseTypes... | 2 | stack_v2_sparse_classes_30k_train_019502 | Implement the Python class `WhereClauseTypes` described below.
Class description:
Implement the WhereClauseTypes class.
Method signatures and docstrings:
- def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False): Converts a given type and values to a where clause stri... | Implement the Python class `WhereClauseTypes` described below.
Class description:
Implement the WhereClauseTypes class.
Method signatures and docstrings:
- def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False): Converts a given type and values to a where clause stri... | 09cecfb795cd9df33773a3095ff855d1c2eb396d | <|skeleton|>
class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhereClauseTypes:
def get_string_for_single_clause(column_name, where_clause_type, values, table_name=None, negation=False):
"""Converts a given type and values to a where clause string that can be used in sql_provider queries. :param column_name: The column name that should be checked with the values... | the_stack_v2_python_sparse | data_models/sql_provider/sql_interface_generic.py | imldresden/mcv-displaywall | train | 2 | |
87c93063155c54cd37c43f1f9723f6e8c987b1b4 | [
"self.db_file = DB_FILE\nself.include_param = False\nset_attributes(self, fw_spec, self.default_params)\nfw_env = fw_spec.get('_fw_env', {})\nif 'DISP_DB_FILE' in fw_env:\n self.db_file = fw_env['DISP_DB_FILE']\nself.logger.info(f'Using DISP_DB_FILE={self.db_file}')",
"self._init_parameters(fw_spec)\nstruct_na... | <|body_start_0|>
self.db_file = DB_FILE
self.include_param = False
set_attributes(self, fw_spec, self.default_params)
fw_env = fw_spec.get('_fw_env', {})
if 'DISP_DB_FILE' in fw_env:
self.db_file = fw_env['DISP_DB_FILE']
self.logger.info(f'Using DISP_DB_FILE={... | A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working directory. | DbRecordTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working dir... | stack_v2_sparse_classes_36k_train_027199 | 46,142 | permissive | [
{
"docstring": "Initialise the parameters",
"name": "_init_parameters",
"signature": "def _init_parameters(self, fw_spec)"
},
{
"docstring": "Save search results to the database Uses the information in fw_spec to read in the files and store them to the database defined under the 'db_file' entry.... | 2 | stack_v2_sparse_classes_30k_train_000402 | Implement the Python class `DbRecordTask` described below.
Class description:
A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file mus... | Implement the Python class `DbRecordTask` described below.
Class description:
A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file mus... | eb0338f5e326a41ed9aa944ee25c283fa99afa02 | <|skeleton|>
class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working dir... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DbRecordTask:
"""A task for storing a record to the database Insert a record into the database, includes the found structures and seed and the parameters. There must be the following keys in the spec: struct_name, project_name. The <struct_name>.res file must be present in the current working directory."""
... | the_stack_v2_python_sparse | disp/fws/tasks.py | zhubonan/disp | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.