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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eb607464bf4a290475e750e3e218a9925c788e6b | [
"if isinstance(value, str):\n return json.loads(value)\nreturn value",
"if isinstance(data, str):\n try:\n return json.loads(data)\n except ValueError as e:\n raise serializers.ValidationError(str(e)) from e\nreturn data",
"if isinstance(data, str):\n return json.loads(data)\nreturn da... | <|body_start_0|>
if isinstance(value, str):
return json.loads(value)
return value
<|end_body_0|>
<|body_start_1|>
if isinstance(data, str):
try:
return json.loads(data)
except ValueError as e:
raise serializers.ValidationError(... | Deserialize a string instance containing a JSON document to a Python object. | JsonField | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
<|body_0|>
def to_internal_value(self, data):
... | stack_v2_sparse_classes_36k_train_017700 | 1,166 | permissive | [
{
"docstring": "Deserialize ``value`` a `str` instance containing a JSON document to a Python object.",
"name": "to_representation",
"signature": "def to_representation(self, value)"
},
{
"docstring": "Deserialize ``value`` a `str` instance containing a JSON document to a Python object.",
"n... | 3 | stack_v2_sparse_classes_30k_train_002063 | Implement the Python class `JsonField` described below.
Class description:
Deserialize a string instance containing a JSON document to a Python object.
Method signatures and docstrings:
- def to_representation(self, value): Deserialize ``value`` a `str` instance containing a JSON document to a Python object.
- def to... | Implement the Python class `JsonField` described below.
Class description:
Deserialize a string instance containing a JSON document to a Python object.
Method signatures and docstrings:
- def to_representation(self, value): Deserialize ``value`` a `str` instance containing a JSON document to a Python object.
- def to... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
<|body_0|>
def to_internal_value(self, data):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JsonField:
"""Deserialize a string instance containing a JSON document to a Python object."""
def to_representation(self, value):
"""Deserialize ``value`` a `str` instance containing a JSON document to a Python object."""
if isinstance(value, str):
return json.loads(value)
... | the_stack_v2_python_sparse | onadata/libs/serializers/fields/json_field.py | onaio/onadata | train | 177 |
67df634a3a0f99574169ec946f9a51751f906cee | [
"self.dt, self.h = (dt, h)\nself.grid = c.shape[:]\nself.srcidx = srcidx[:]\nself.source = srcfunc()\nself.context = util.grabcontext(context)\nself.queue = cl.CommandQueue(self.context)\nt = Template(filename=self._kernel, output_encoding='ascii')\nself.fdcl = cl.Program(self.context, t.render(dim=self.grid, srcid... | <|body_start_0|>
self.dt, self.h = (dt, h)
self.grid = c.shape[:]
self.srcidx = srcidx[:]
self.source = srcfunc()
self.context = util.grabcontext(context)
self.queue = cl.CommandQueue(self.context)
t = Template(filename=self._kernel, output_encoding='ascii')
... | A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided. | Helmholtz | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initiali... | stack_v2_sparse_classes_36k_train_017701 | 24,055 | permissive | [
{
"docstring": "Initialize the sound-speed c, time step dt and spatial step h. The coroutine srcfunc should provide a time-dependent value that describes the incident pressure at index srcidx. The context, if provided, is a PyOpenCL context for a single device. If it is not provided, a default context will be c... | 4 | null | Implement the Python class `Helmholtz` described below.
Class description:
A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided.
Method signatures and docstrings:
- def __init__... | Implement the Python class `Helmholtz` described below.
Class description:
A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided.
Method signatures and docstrings:
- def __init__... | 5fabc9c1f410bf49b674bfb4427fe1f05ad251ed | <|skeleton|>
class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initiali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Helmholtz:
"""A class that works identically to the standard Helmholtz class but that uses PyOpenCL to accelerate computations. A desired context can be passed in, but one will be created if none is provided."""
def __init__(self, c, dt, h, srcfunc, srcidx, context=None):
"""Initialize the sound-... | the_stack_v2_python_sparse | pycwp/cltools/wavecl.py | ahesford/pycwp | train | 0 |
9e3a2d69bf08675a360d13676ed759a64d447d7f | [
"if self.hooked is None:\n self.hooked = {}\nif args_gen is None:\n args_gen = make_args_gen(func)\nif not isinstance(hooks, Sequence):\n hooks = [hooks]\nfor hook_cls in hooks:\n self.hooked[hook_cls] = (func, args_gen)",
"try:\n func, args_gen = self.hooked[type(hook)]\nexcept (KeyError, TypeErro... | <|body_start_0|>
if self.hooked is None:
self.hooked = {}
if args_gen is None:
args_gen = make_args_gen(func)
if not isinstance(hooks, Sequence):
hooks = [hooks]
for hook_cls in hooks:
self.hooked[hook_cls] = (func, args_gen)
<|end_body_0|>... | Baseclass of something that can be attached to a hook | Hookable | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks, func, args_gen=None):
"""Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should... | stack_v2_sparse_classes_36k_train_017702 | 7,429 | permissive | [
{
"docstring": "Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should be run on that Hook args_gen: Optionally specify the argument names that should be passed to func. If not given then use func.call_types.ke... | 2 | stack_v2_sparse_classes_30k_train_013228 | Implement the Python class `Hookable` described below.
Class description:
Baseclass of something that can be attached to a hook
Method signatures and docstrings:
- def register_hooked(self, hooks, func, args_gen=None): Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list o... | Implement the Python class `Hookable` described below.
Class description:
Baseclass of something that can be attached to a hook
Method signatures and docstrings:
- def register_hooked(self, hooks, func, args_gen=None): Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list o... | 0b856ee1113efdb42f2f3b15986f8ac5f9e1b35a | <|skeleton|>
class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks, func, args_gen=None):
"""Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hookable:
"""Baseclass of something that can be attached to a hook"""
def register_hooked(self, hooks, func, args_gen=None):
"""Register func to be run when any of the hooks are run by parent Args: hooks: A Hook class or list of Hook classes of interest func: The callable that should be run on th... | the_stack_v2_python_sparse | malcolm/core/hook.py | dinojugosloven/pymalcolm | train | 0 |
1f41b2ff53dceda45cacc7f853c6647e5ae570de | [
"if root == None:\n return False\n\ndef judge(root, sum):\n if root == None and sum != 0:\n return False\n if root.left == None and root.right == None and (root.val == sum):\n return True\n elif root.left == None and root.right != None:\n return judge(root.right, sum - root.val)\n ... | <|body_start_0|>
if root == None:
return False
def judge(root, sum):
if root == None and sum != 0:
return False
if root.left == None and root.right == None and (root.val == sum):
return True
elif root.left == None and root.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017703 | 1,940 | no_license | [
{
"docstring": ":type root: TreeNode :type sum: int :rtype: bool",
"name": "hasPathSum",
"signature": "def hasPathSum(self, root, sum)"
},
{
"docstring": ":type root: TreeNode :type sum: int :rtype: List[List[int]]",
"name": "pathSum",
"signature": "def pathSum(self, root, sum)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010165 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: bool
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: bool
- def pathSum(self, root, sum): :type root: TreeNode :type sum: int :rtype: List[List[int]]
<|s... | 2418b3eed1ab85cfd9cac039c6cfdc1a349ad345 | <|skeleton|>
class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: bool"""
<|body_0|>
def pathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum(self, root, sum):
""":type root: TreeNode :type sum: int :rtype: bool"""
if root == None:
return False
def judge(root, sum):
if root == None and sum != 0:
return False
if root.left == None and root.right == N... | the_stack_v2_python_sparse | leetcode-first_time/leetcode112(path sum).py | HopeCheung/leetcode | train | 0 | |
5a7e75a4c61d2388991933ac0fd091aa86d079ea | [
"check_type(session, RestSession, may_be_none=False)\nsuper(OrganizationsAPI, self).__init__()\nself._session = session\nself._object_factory = object_factory",
"check_type(max, int)\nparams = dict_from_items_with_values(request_parameters, max=max)\nitems = self._session.get_items(API_ENDPOINT, params=params)\nf... | <|body_start_0|>
check_type(session, RestSession, may_be_none=False)
super(OrganizationsAPI, self).__init__()
self._session = session
self._object_factory = object_factory
<|end_body_0|>
<|body_start_1|>
check_type(max, int)
params = dict_from_items_with_values(request_p... | Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects. | OrganizationsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationsAPI:
"""Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new OrganizationsAPI object with the provided RestSess... | stack_v2_sparse_classes_36k_train_017704 | 3,869 | permissive | [
{
"docstring": "Init a new OrganizationsAPI object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to the Cisco Spark service. Raises: TypeError: If the parameter types are incorrect.",
"name": "__init__",
"signature": "def __init__(self, se... | 3 | null | Implement the Python class `OrganizationsAPI` described below.
Class description:
Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Init... | Implement the Python class `OrganizationsAPI` described below.
Class description:
Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects.
Method signatures and docstrings:
- def __init__(self, session, object_factory): Init... | e0ab24a99791c3b25422a3208f02919cf98ca084 | <|skeleton|>
class OrganizationsAPI:
"""Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new OrganizationsAPI object with the provided RestSess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrganizationsAPI:
"""Cisco Spark Organizations API. Wraps the Cisco Spark Organizations API and exposes the API as native Python methods that return native Python objects."""
def __init__(self, session, object_factory):
"""Init a new OrganizationsAPI object with the provided RestSession. Args: se... | the_stack_v2_python_sparse | webex_integration/_trash/_ciscosparkapi/ciscosparkapi/ciscosparkapi/api/organizations.py | jurgeon018/snippets | train | 0 |
d7a41b5046a12fd68c7bcc4ec4525c6cbe068f45 | [
"symbol, name = command\nuser_level = self.ROLES.get(symbol, 1)\nraw.role = user_level\nraw.target = None\nresponse = await self.api.add_command(name, raw.split(maximum=3)[-1].json, user_level=user_level)\ndata = await response.json()\nif data['meta'].get('created'):\n return 'Added command !{}.'.format(name)\nr... | <|body_start_0|>
symbol, name = command
user_level = self.ROLES.get(symbol, 1)
raw.role = user_level
raw.target = None
response = await self.api.add_command(name, raw.split(maximum=3)[-1].json, user_level=user_level)
data = await response.json()
if data['meta'].ge... | Manage commands. | Meta | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
<|body_0|>
async def remove(self, name: '?command'):
"""Remove a command."""
<|body_1|>
async def list_commands(self)... | stack_v2_sparse_classes_36k_train_017705 | 3,086 | permissive | [
{
"docstring": "Add a command.",
"name": "add",
"signature": "async def add(self, command: '!?([+$]?)([\\\\w-]{1,32})', *response, raw: 'packet')"
},
{
"docstring": "Remove a command.",
"name": "remove",
"signature": "async def remove(self, name: '?command')"
},
{
"docstring": "L... | 6 | stack_v2_sparse_classes_30k_train_008906 | Implement the Python class `Meta` described below.
Class description:
Manage commands.
Method signatures and docstrings:
- async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'): Add a command.
- async def remove(self, name: '?command'): Remove a command.
- async def list_commands(self): Li... | Implement the Python class `Meta` described below.
Class description:
Manage commands.
Method signatures and docstrings:
- async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'): Add a command.
- async def remove(self, name: '?command'): Remove a command.
- async def list_commands(self): Li... | 6d035bf74bdc8f7fb3ee1e79f8d443f5b17e7ea5 | <|skeleton|>
class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
<|body_0|>
async def remove(self, name: '?command'):
"""Remove a command."""
<|body_1|>
async def list_commands(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Meta:
"""Manage commands."""
async def add(self, command: '!?([+$]?)([\\w-]{1,32})', *response, raw: 'packet'):
"""Add a command."""
symbol, name = command
user_level = self.ROLES.get(symbol, 1)
raw.role = user_level
raw.target = None
response = await self.... | the_stack_v2_python_sparse | cactusbot/commands/magic/command.py | CactusDev/CactusBot | train | 18 |
80de1261b3d77078d8170d185334f9fb64778e32 | [
"try:\n return_data = WorkFlowSimpleManager().create_workflow(nnid, wfver, request.data['type'])\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = NNCommonManager(... | <|body_start_0|>
try:
return_data = WorkFlowSimpleManager().create_workflow(nnid, wfver, request.data['type'])
return Response(json.dumps(return_data))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(retu... | WorkFlowInitSimple | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowInitSimple:
def post(self, request, nnid, wfver):
"""Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are several processes already designed --- # Class Name : WorkFlowInitSimple # Description: Set graph flow with gi... | stack_v2_sparse_classes_36k_train_017706 | 2,447 | permissive | [
{
"docstring": "Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are several processes already designed --- # Class Name : WorkFlowInitSimple # Description: Set graph flow with given name and data type",
"name": "post",
"signature": "def po... | 3 | stack_v2_sparse_classes_30k_train_021241 | Implement the Python class `WorkFlowInitSimple` described below.
Class description:
Implement the WorkFlowInitSimple class.
Method signatures and docstrings:
- def post(self, request, nnid, wfver): Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are sev... | Implement the Python class `WorkFlowInitSimple` described below.
Class description:
Implement the WorkFlowInitSimple class.
Method signatures and docstrings:
- def post(self, request, nnid, wfver): Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are sev... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowInitSimple:
def post(self, request, nnid, wfver):
"""Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are several processes already designed --- # Class Name : WorkFlowInitSimple # Description: Set graph flow with gi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkFlowInitSimple:
def post(self, request, nnid, wfver):
"""Simply initialize fixed graph flow which is preefined You can choose process with network id and data type There are several processes already designed --- # Class Name : WorkFlowInitSimple # Description: Set graph flow with given name and d... | the_stack_v2_python_sparse | api/views/workflow_init_simple.py | yurimkoo/tensormsa | train | 1 | |
a0250260b5cd4549a68514faaebdde48a46ee8cd | [
"self.output = list()\nself._permuteUnique(list(), nums)\nreturn self.output",
"mem = dict()\nif not nums:\n self.output.append(curr_arr)\n return\nfor i, v in enumerate(nums):\n if v in mem:\n continue\n else:\n mem[v] = 1\n new_arr = list(curr_arr)\n new_arr.append(v)\n ... | <|body_start_0|>
self.output = list()
self._permuteUnique(list(), nums)
return self.output
<|end_body_0|>
<|body_start_1|>
mem = dict()
if not nums:
self.output.append(curr_arr)
return
for i, v in enumerate(nums):
if v in mem:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def _permuteUnique(self, curr_arr, nums):
"""Helper method to compute permutations recursively using a local dict() to deal with duplicates"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017707 | 827 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permuteUnique",
"signature": "def permuteUnique(self, nums)"
},
{
"docstring": "Helper method to compute permutations recursively using a local dict() to deal with duplicates",
"name": "_permuteUnique",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_018708 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def _permuteUnique(self, curr_arr, nums): Helper method to compute permutations recursively using a... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permuteUnique(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def _permuteUnique(self, curr_arr, nums): Helper method to compute permutations recursively using a... | 43dbcc129de3092d1ef24b95eaf35e20363cbd93 | <|skeleton|>
class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def _permuteUnique(self, curr_arr, nums):
"""Helper method to compute permutations recursively using a local dict() to deal with duplicates"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def permuteUnique(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
self.output = list()
self._permuteUnique(list(), nums)
return self.output
def _permuteUnique(self, curr_arr, nums):
"""Helper method to compute permutations recursively usi... | the_stack_v2_python_sparse | permutations-ii.py | iyyuan/leetcode-practice | train | 0 | |
00a8f678151ee50bb3eea4ad0eaa7ce7959a874d | [
"query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}\nfinal_query_args = {k: v for k, v in query_args.items() if v is not None}\nreturn super().get_queryset().filter(**final_query_args)",
"query_args = {'user': user, 'stock': stock, 'brokerage_acco... | <|body_start_0|>
query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}
final_query_args = {k: v for k, v in query_args.items() if v is not None}
return super().get_queryset().filter(**final_query_args)
<|end_body_0|>
<|body_start_1... | StockSharesManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
<|body_0|>
def investment_sum(self, user=None, stock=None, brokerage_account=None, budget_account=None):
"... | stack_v2_sparse_classes_36k_train_017708 | 2,721 | permissive | [
{
"docstring": "find all shares in all accounts for a ticker",
"name": "find_all_shares",
"signature": "def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None)"
},
{
"docstring": "find sum of shares in accounts",
"name": "investment_sum",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_017105 | Implement the Python class `StockSharesManager` described below.
Class description:
Implement the StockSharesManager class.
Method signatures and docstrings:
- def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None): find all shares in all accounts for a ticker
- def investment_sum(se... | Implement the Python class `StockSharesManager` described below.
Class description:
Implement the StockSharesManager class.
Method signatures and docstrings:
- def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None): find all shares in all accounts for a ticker
- def investment_sum(se... | 585b036b1a2a1c356a366b94676042e4628f6773 | <|skeleton|>
class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
<|body_0|>
def investment_sum(self, user=None, stock=None, brokerage_account=None, budget_account=None):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockSharesManager:
def find_all_shares(self, user, stock=None, brokerage_account=None, budget_account=None):
"""find all shares in all accounts for a ticker"""
query_args = {'user': user, 'stock': stock, 'brokerage_account': brokerage_account, 'budget_account': budget_account}
final_q... | the_stack_v2_python_sparse | budgetbuddy/stocks/managers.py | michaelqknguyen/Budget-Buddy | train | 0 | |
4768a2cbac14372206f1b2a4917f8aea5979bd00 | [
"m = defaultdict(list)\nfor i, score in items:\n if len(m[i]) < 5:\n heapq.heappush(m[i], score)\n else:\n heapq.heappushpop(m[i], score)\nres = []\nfor i in sorted(m.keys()):\n print(m[i])\n res.append(sum(m[i]) // 5)\nreturn res",
"m = defaultdict(list)\nfor r in results:\n if len(m... | <|body_start_0|>
m = defaultdict(list)
for i, score in items:
if len(m[i]) < 5:
heapq.heappush(m[i], score)
else:
heapq.heappushpop(m[i], score)
res = []
for i in sorted(m.keys()):
print(m[i])
res.append(sum(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def highFiveLint(self, results):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
m = d... | stack_v2_sparse_classes_36k_train_017709 | 2,399 | no_license | [
{
"docstring": ":type items: List[List[int]] :rtype: List[List[int]]",
"name": "highFive",
"signature": "def highFive(self, items)"
},
{
"docstring": ":type items: List[List[int]] :rtype: List[List[int]]",
"name": "highFiveLint",
"signature": "def highFiveLint(self, results)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020079 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items): :type items: List[List[int]] :rtype: List[List[int]]
- def highFiveLint(self, results): :type items: List[List[int]] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def highFive(self, items): :type items: List[List[int]] :rtype: List[List[int]]
- def highFiveLint(self, results): :type items: List[List[int]] :rtype: List[List[int]]
<|skeleto... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def highFiveLint(self, results):
""":type items: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def highFive(self, items):
""":type items: List[List[int]] :rtype: List[List[int]]"""
m = defaultdict(list)
for i, score in items:
if len(m[i]) < 5:
heapq.heappush(m[i], score)
else:
heapq.heappushpop(m[i], score)
... | the_stack_v2_python_sparse | H/HighFive.py | bssrdf/pyleet | train | 2 | |
47345ea6f6e3c1be7961462dbf704fcec0504e9e | [
"res = {}\nfor line in self.browse(cr, uid, ids):\n res[line.id] = line.price_unit * line.product_qty\nreturn res",
"res = {}\nif price or qty:\n res = {'value': {'price_subtotal': price * qty}}\nreturn res"
] | <|body_start_0|>
res = {}
for line in self.browse(cr, uid, ids):
res[line.id] = line.price_unit * line.product_qty
return res
<|end_body_0|>
<|body_start_1|>
res = {}
if price or qty:
res = {'value': {'price_subtotal': price * qty}}
return res
<|e... | Manage the products of purchase inintail quotaion | pq_products | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
<|body_0|>
def subtotal(self, cr, uid, ids, price,... | stack_v2_sparse_classes_36k_train_017710 | 20,327 | no_license | [
{
"docstring": "Compute the price amount of each quotaion line. @return: dictionary of lines subtotal",
"name": "_amount_line",
"signature": "def _amount_line(self, cr, uid, ids, fields, arg, context)"
},
{
"docstring": "On change function to recompute the total price after changing product qty ... | 2 | stack_v2_sparse_classes_30k_train_008771 | Implement the Python class `pq_products` described below.
Class description:
Manage the products of purchase inintail quotaion
Method signatures and docstrings:
- def _amount_line(self, cr, uid, ids, fields, arg, context): Compute the price amount of each quotaion line. @return: dictionary of lines subtotal
- def sub... | Implement the Python class `pq_products` described below.
Class description:
Manage the products of purchase inintail quotaion
Method signatures and docstrings:
- def _amount_line(self, cr, uid, ids, fields, arg, context): Compute the price amount of each quotaion line. @return: dictionary of lines subtotal
- def sub... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
<|body_0|>
def subtotal(self, cr, uid, ids, price,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pq_products:
"""Manage the products of purchase inintail quotaion"""
def _amount_line(self, cr, uid, ids, fields, arg, context):
"""Compute the price amount of each quotaion line. @return: dictionary of lines subtotal"""
res = {}
for line in self.browse(cr, uid, ids):
... | the_stack_v2_python_sparse | v_7/GDS/shamil_v3/purchase_custom/quote.py | musabahmed/baba | train | 0 |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('token')\nsuper(CtaStrategyLoad, self).__init__()",
"args = self.parser.parse_args()\nengine = me.getApp('CtaStrategy')\nengine.loadSetting()\nl = [u'对冲策略']\nreturn {'result_code': 'success', 'data': l}"
] | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(CtaStrategyLoad, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
engine = me.getApp('CtaStrategy')
engine.loadSetting()
l = [u'对冲策略']
... | 加载策略 | CtaStrategyLoad | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CtaStrategyLoad:
"""加载策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(CtaStrategy... | stack_v2_sparse_classes_36k_train_017711 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "订阅",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003598 | Implement the Python class `CtaStrategyLoad` described below.
Class description:
加载策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅 | Implement the Python class `CtaStrategyLoad` described below.
Class description:
加载策略
Method signatures and docstrings:
- def __init__(self): 初始化
- def post(self): 订阅
<|skeleton|>
class CtaStrategyLoad:
"""加载策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class CtaStrategyLoad:
"""加载策略"""
def __init__(self):
"""初始化"""
<|body_0|>
def post(self):
"""订阅"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CtaStrategyLoad:
"""加载策略"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(CtaStrategyLoad, self).__init__()
def post(self):
"""订阅"""
args = self.parser.parse_args()
engine = me.getA... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
de9b77457cde931ca04c7adc90d54256fa19ce84 | [
"N, L, D = x.shape\nlen_keep = int(L * (1 - mask_ratio))\nnoise = importance.to(x.device)\nids_shuffle = torch.multinomial(noise, L, replacement=False)\nids_restore = torch.argsort(ids_shuffle, dim=1)\nids_keep = ids_shuffle[:, :len_keep]\nids_dump = ids_shuffle[:, len_keep:]\nx_masked = torch.gather(x, dim=1, inde... | <|body_start_0|>
N, L, D = x.shape
len_keep = int(L * (1 - mask_ratio))
noise = importance.to(x.device)
ids_shuffle = torch.multinomial(noise, L, replacement=False)
ids_restore = torch.argsort(ids_shuffle, dim=1)
ids_keep = ids_shuffle[:, :len_keep]
ids_dump = ids... | Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forward function and replace random masking with attention masking. | MILANViT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MILANViT:
"""Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forward function and replace random masking ... | stack_v2_sparse_classes_36k_train_017712 | 7,684 | permissive | [
{
"docstring": "Generate attention mask for MILAN. This is what is different from MAEViT, which uses random masking. Attention masking generates attention mask for MILAN, according to importance. The higher the importance, the more likely the patch is kept. Args: x (torch.Tensor): Input images, which is of shap... | 2 | null | Implement the Python class `MILANViT` described below.
Class description:
Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forwa... | Implement the Python class `MILANViT` described below.
Class description:
Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forwa... | d2ccc44a2c8e5d49bb26187aff42f2abc90aee28 | <|skeleton|>
class MILANViT:
"""Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forward function and replace random masking ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MILANViT:
"""Vision Transformer for MILAN pre-training. Implementation of the encoder for `MILAN: Masked Image Pretraining on Language Assisted Representation <https://arxiv.org/abs/2208.06049>`_. This module inherits from MAEViT and only overrides the forward function and replace random masking with attentio... | the_stack_v2_python_sparse | mmpretrain/models/selfsup/milan.py | open-mmlab/mmpretrain | train | 652 |
995a29b51527f3f5af158d561d54484b36c54931 | [
"self.test_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/tests/test_list.txt')\nself.path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/tests')\nself.output_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/tests/__out')\nos.makedirs(sel... | <|body_start_0|>
self.test_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/tests/test_list.txt')
self.path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/tests')
self.output_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dial... | This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests | TestManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestManager:
"""This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests"""
def __init__(self):
"""Create a new test manager"""
<|body_0|>
def loadTests(self):
"""Load the test instruction f... | stack_v2_sparse_classes_36k_train_017713 | 4,975 | permissive | [
{
"docstring": "Create a new test manager",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Load the test instruction file",
"name": "loadTests",
"signature": "def loadTests(self)"
},
{
"docstring": "Run test or tests with the given name",
"name": "ru... | 4 | stack_v2_sparse_classes_30k_train_017834 | Implement the Python class `TestManager` described below.
Class description:
This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests
Method signatures and docstrings:
- def __init__(self): Create a new test manager
- def loadTests(self): Load t... | Implement the Python class `TestManager` described below.
Class description:
This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests
Method signatures and docstrings:
- def __init__(self): Create a new test manager
- def loadTests(self): Load t... | 3a1b4540b1025fa73118d0e065c526437b37df12 | <|skeleton|>
class TestManager:
"""This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests"""
def __init__(self):
"""Create a new test manager"""
<|body_0|>
def loadTests(self):
"""Load the test instruction f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestManager:
"""This class is designed to validate evaluator funcionality for all the tracks. It loads a test instruction file and runs the tests"""
def __init__(self):
"""Create a new test manager"""
self.test_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dialent/... | the_stack_v2_python_sparse | scripts/functest.py | bond005/factRuEval-2016 | train | 1 |
eb83f960720951e9eea5a9c8b3c5fe1b9d71275d | [
"t1 = BinaryTree(3, BinaryTree(5, right=BinaryTree(2)))\nt2 = BinaryTree(4, BinaryTree(6), BinaryTree(7))\nt = BinaryTree(1, t1, t2)\nself.assertEqual(get_largest_height_difference(None), 0)\nself.assertEqual(get_largest_height_difference(t1), 2)\nself.assertEqual(get_largest_height_difference(t2), 0)\nself.assertE... | <|body_start_0|>
t1 = BinaryTree(3, BinaryTree(5, right=BinaryTree(2)))
t2 = BinaryTree(4, BinaryTree(6), BinaryTree(7))
t = BinaryTree(1, t1, t2)
self.assertEqual(get_largest_height_difference(None), 0)
self.assertEqual(get_largest_height_difference(t1), 2)
self.assertEq... | ExerciseTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExerciseTests:
def test_client_code(self):
"""Tests the client code to make sure the exercise passes it."""
<|body_0|>
def test_hidden(self):
"""The hidden test for students."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
t1 = BinaryTree(3, BinaryT... | stack_v2_sparse_classes_36k_train_017714 | 2,301 | no_license | [
{
"docstring": "Tests the client code to make sure the exercise passes it.",
"name": "test_client_code",
"signature": "def test_client_code(self)"
},
{
"docstring": "The hidden test for students.",
"name": "test_hidden",
"signature": "def test_hidden(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007172 | Implement the Python class `ExerciseTests` described below.
Class description:
Implement the ExerciseTests class.
Method signatures and docstrings:
- def test_client_code(self): Tests the client code to make sure the exercise passes it.
- def test_hidden(self): The hidden test for students. | Implement the Python class `ExerciseTests` described below.
Class description:
Implement the ExerciseTests class.
Method signatures and docstrings:
- def test_client_code(self): Tests the client code to make sure the exercise passes it.
- def test_hidden(self): The hidden test for students.
<|skeleton|>
class Exerci... | 556c5485e38ad81dae7bb14e312f2b081100245d | <|skeleton|>
class ExerciseTests:
def test_client_code(self):
"""Tests the client code to make sure the exercise passes it."""
<|body_0|>
def test_hidden(self):
"""The hidden test for students."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExerciseTests:
def test_client_code(self):
"""Tests the client code to make sure the exercise passes it."""
t1 = BinaryTree(3, BinaryTree(5, right=BinaryTree(2)))
t2 = BinaryTree(4, BinaryTree(6), BinaryTree(7))
t = BinaryTree(1, t1, t2)
self.assertEqual(get_largest_hei... | the_stack_v2_python_sparse | pyta/Week10_summer/test_ex7.py | Kevintjy/Python-Beginner | train | 1 | |
aad77fa08ebee5c88ed84b125e33fd88d8f566be | [
"query_db = TestDatabases.query.get(db_id)\nif not query_db:\n return api_result(code=400, message='db_id:{}数据不存在'.format(db_id))\nreturn api_result(code=200, message='操作成功', data=query_db.to_json())",
"data = request.get_json()\nname = data.get('name')\ndb_type = data.get('db_type')\ndb_connection = data.get(... | <|body_start_0|>
query_db = TestDatabases.query.get(db_id)
if not query_db:
return api_result(code=400, message='db_id:{}数据不存在'.format(db_id))
return api_result(code=200, message='操作成功', data=query_db.to_json())
<|end_body_0|>
<|body_start_1|>
data = request.get_json()
... | 用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除 | CaseDBApi | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CaseDBApi:
"""用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除"""
def get(self, db_id):
"""db详情"""
<|body_0|>
def post(self):
"""db新增"""
<|body_1|>
def put(self):
"""db编辑"""
<|body_2|>
def delete(self):
"""db删除"""
... | stack_v2_sparse_classes_36k_train_017715 | 4,337 | no_license | [
{
"docstring": "db详情",
"name": "get",
"signature": "def get(self, db_id)"
},
{
"docstring": "db新增",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "db编辑",
"name": "put",
"signature": "def put(self)"
},
{
"docstring": "db删除",
"name": "delete",
... | 4 | null | Implement the Python class `CaseDBApi` described below.
Class description:
用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除
Method signatures and docstrings:
- def get(self, db_id): db详情
- def post(self): db新增
- def put(self): db编辑
- def delete(self): db删除 | Implement the Python class `CaseDBApi` described below.
Class description:
用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除
Method signatures and docstrings:
- def get(self, db_id): db详情
- def post(self): db新增
- def put(self): db编辑
- def delete(self): db删除
<|skeleton|>
class CaseDBApi:
"""用例关联 db api GET:... | df76812885d7d7f3a5269e3f7c652db6a9f3c3ad | <|skeleton|>
class CaseDBApi:
"""用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除"""
def get(self, db_id):
"""db详情"""
<|body_0|>
def post(self):
"""db新增"""
<|body_1|>
def put(self):
"""db编辑"""
<|body_2|>
def delete(self):
"""db删除"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CaseDBApi:
"""用例关联 db api GET: db详情 POST: db新增 PUT: db编辑 DELETE: db删除"""
def get(self, db_id):
"""db详情"""
query_db = TestDatabases.query.get(db_id)
if not query_db:
return api_result(code=400, message='db_id:{}数据不存在'.format(db_id))
return api_result(code=200, m... | the_stack_v2_python_sparse | app/api/case_db_api/case_db_api.py | chengzizhen/ExileTestPlatformServer | train | 0 |
409a2f0e0b647a7af6c8add5e9189aee24b9b73d | [
"res = ''\nqueue = []\nqueue.append(root)\nwhile queue:\n root = queue.pop(0)\n if root:\n res += str(root.val)\n queue.append(root.left)\n queue.append(root.right)\n else:\n res += 'None'\n res += ','\nreturn res",
"tree = data.split(',')\nif tree[0] == 'None':\n return... | <|body_start_0|>
res = ''
queue = []
queue.append(root)
while queue:
root = queue.pop(0)
if root:
res += str(root.val)
queue.append(root.left)
queue.append(root.right)
else:
res += 'None'
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017716 | 1,598 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 013f6f222c6c2a617787b258f8a37003a9f51526 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
res = ''
queue = []
queue.append(root)
while queue:
root = queue.pop(0)
if root:
res += str(root.val)
queu... | the_stack_v2_python_sparse | other/codec.py | terrifyzhao/leetcode | train | 0 | |
00a69b6af28728d79da5e6119289f3efb4a5c5ac | [
"self._fetch_files(fetch_all)\nself.return_value['fetched'] = self.results_count\nreturn self.return_value",
"media = Media.objects.all()\nif not fetch_all:\n media = media.filter(image_file='')\nerror_messages = []\nfor media_obj in media:\n try:\n self._fetch_and_save_file(media_obj=media_obj, medi... | <|body_start_0|>
self._fetch_files(fetch_all)
self.return_value['fetched'] = self.results_count
return self.return_value
<|end_body_0|>
<|body_start_1|>
media = Media.objects.all()
if not fetch_all:
media = media.filter(image_file='')
error_messages = []
... | For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as opposed to MP4 Animated GIF files) will be discontinued from 2016-08-01. htt... | FetchFiles | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FetchFiles:
"""For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as opposed to MP4 Animated GIF files) wil... | stack_v2_sparse_classes_36k_train_017717 | 18,076 | permissive | [
{
"docstring": "Download and save original images for all Media objects (or just those that don't already have them). fetch_all -- Boolean. Fetch ALL images, even if we've already got them?",
"name": "fetch",
"signature": "def fetch(self, fetch_all=False)"
},
{
"docstring": "Download and save or... | 3 | stack_v2_sparse_classes_30k_train_007681 | Implement the Python class `FetchFiles` described below.
Class description:
For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as... | Implement the Python class `FetchFiles` described below.
Class description:
For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as... | 57ee6f6657b41705af71ef67924d8ef06c60ae4f | <|skeleton|>
class FetchFiles:
"""For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as opposed to MP4 Animated GIF files) wil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FetchFiles:
"""For fetching image files and Animated GIFs' MP4 files. Doesn't inherit from Fetch because it doesn't use the API or rely on having an Account object. Doesn't fetch MP4s (or other movie files) for videos because the URLs for MP4 video files (as opposed to MP4 Animated GIF files) will be disconti... | the_stack_v2_python_sparse | ditto/twitter/fetch/fetch.py | philgyford/django-ditto | train | 59 |
a40866d6c54c8c49b073fe2f3343e534348a004b | [
"annot_path = pathlib.Path(annot_path)\ncrowsetta.validation.validate_ext(annot_path, extension=cls.ext)\nannot_mat = scipy.io.loadmat(annot_path, squeeze_me=True)\naudio_paths = annot_mat['keys']\nannotations = annot_mat['elements']\nif len(audio_paths) != len(annotations):\n raise ValueError(f'list of filename... | <|body_start_0|>
annot_path = pathlib.Path(annot_path)
crowsetta.validation.validate_ext(annot_path, extension=cls.ext)
annot_mat = scipy.io.loadmat(annot_path, squeeze_me=True)
audio_paths = annot_mat['keys']
annotations = annot_mat['elements']
if len(audio_paths) != len... | Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. ext: str Extension of files in annotation format: ``'.mat'``. annotations : numpy.nda... | SongAnnotationGUI | [
"BSD-3-Clause",
"CC0-1.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SongAnnotationGUI:
"""Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. ext: str Extension of files in annotatio... | stack_v2_sparse_classes_36k_train_017718 | 7,983 | permissive | [
{
"docstring": "Load annotations from mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Parameters ---------- annot_path: str, pathlib.Path Path to .mat file with annotations.",
"name": "from_file",
"signature": "def from_file(cls, annot_path:... | 3 | stack_v2_sparse_classes_30k_train_017938 | Implement the Python class `SongAnnotationGUI` described below.
Class description:
Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. e... | Implement the Python class `SongAnnotationGUI` described below.
Class description:
Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. e... | 1a60ea50716acad401751e9512e7e09596417b81 | <|skeleton|>
class SongAnnotationGUI:
"""Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. ext: str Extension of files in annotatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SongAnnotationGUI:
"""Class that represents annotations from .mat files created by SongAnnotationGUI: https://github.com/yardencsGitHub/BirdSongBout/tree/master/helpers/GUI Attributes ---------- name: str Shorthand name for annotation format: ``'yarden'``. ext: str Extension of files in annotation format: ``'... | the_stack_v2_python_sparse | src/crowsetta/formats/seq/yarden.py | vocalpy/crowsetta | train | 29 |
32d673c9ca22a4d74c7671b269d1a971628d65eb | [
"self.n = len(words)\nself.word2idx = {}\nfor i in range(self.n):\n if words[i] not in self.word2idx:\n self.word2idx[words[i]] = [i]\n else:\n self.word2idx[words[i]] += [i]",
"shortestDis = self.n\nfor i in self.word2idx[word1]:\n for j in self.word2idx[word2]:\n if abs(i - j) < sh... | <|body_start_0|>
self.n = len(words)
self.word2idx = {}
for i in range(self.n):
if words[i] not in self.word2idx:
self.word2idx[words[i]] = [i]
else:
self.word2idx[words[i]] += [i]
<|end_body_0|>
<|body_start_1|>
shortestDis = self... | 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.n = len(words)
self.word... | stack_v2_sparse_classes_36k_train_017719 | 1,870 | 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:
... | 167a196a9c36f0eaf3d94b07919f4ed138cf4728 | <|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.n = len(words)
self.word2idx = {}
for i in range(self.n):
if words[i] not in self.word2idx:
self.word2idx[words[i]] = [i]
else:
self.word2idx[words... | the_stack_v2_python_sparse | shortestworddisii.py | tristaaa/lcproblems | train | 0 | |
09c1b253c7173fbf8244a6d3ff0ab5612943dbac | [
"dict.__init__(self)\nself.filename = filename\nf = open(self.filename, 'rU')\ntry:\n position = 0\n while True:\n line = f.readline()\n if not line:\n break\n if line.startswith('#'):\n continue\n record = Record(line)\n key = record.sid\n if ke... | <|body_start_0|>
dict.__init__(self)
self.filename = filename
f = open(self.filename, 'rU')
try:
position = 0
while True:
line = f.readline()
if not line:
break
if line.startswith('#'):
... | A CLA file indexed by SCOP identifiers, allowing rapid random access into a file. | Index | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Index:
"""A CLA file indexed by SCOP identifiers, allowing rapid random access into a file."""
def __init__(self, filename):
"""Arguments: filename -- The file to index"""
<|body_0|>
def __getitem__(self, key):
"""Return an item from the indexed file."""
... | stack_v2_sparse_classes_36k_train_017720 | 3,938 | permissive | [
{
"docstring": "Arguments: filename -- The file to index",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Return an item from the indexed file.",
"name": "__getitem__",
"signature": "def __getitem__(self, key)"
}
] | 2 | null | Implement the Python class `Index` described below.
Class description:
A CLA file indexed by SCOP identifiers, allowing rapid random access into a file.
Method signatures and docstrings:
- def __init__(self, filename): Arguments: filename -- The file to index
- def __getitem__(self, key): Return an item from the inde... | Implement the Python class `Index` described below.
Class description:
A CLA file indexed by SCOP identifiers, allowing rapid random access into a file.
Method signatures and docstrings:
- def __init__(self, filename): Arguments: filename -- The file to index
- def __getitem__(self, key): Return an item from the inde... | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | <|skeleton|>
class Index:
"""A CLA file indexed by SCOP identifiers, allowing rapid random access into a file."""
def __init__(self, filename):
"""Arguments: filename -- The file to index"""
<|body_0|>
def __getitem__(self, key):
"""Return an item from the indexed file."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Index:
"""A CLA file indexed by SCOP identifiers, allowing rapid random access into a file."""
def __init__(self, filename):
"""Arguments: filename -- The file to index"""
dict.__init__(self)
self.filename = filename
f = open(self.filename, 'rU')
try:
p... | the_stack_v2_python_sparse | bin/last_wrapper/Bio/SCOP/Cla.py | LyonsLab/coge | train | 41 |
157db2b34c1c4b1f3c163f13a9309f5e1b7f264b | [
"self.image_preprocessing_fn = vgg_preprocessing.preprocess_image\nself.is_training = is_training\nself.data_dir = data_dir\nself.batch_size = batch_size",
"keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, ''), 'image/format': tf.FixedLenFeature((), tf.string, 'jpeg'), 'image/class/label': t... | <|body_start_0|>
self.image_preprocessing_fn = vgg_preprocessing.preprocess_image
self.is_training = is_training
self.data_dir = data_dir
self.batch_size = batch_size
<|end_body_0|>
<|body_start_1|>
keys_to_features = {'image/encoded': tf.FixedLenFeature((), tf.string, ''), 'ima... | Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation data is in the same format bu... | ImageNetInput | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_36k_train_017721 | 12,252 | permissive | [
{
"docstring": "Constructor for ImageNetInput. Args: is_training: `bool` for whether the input is for training. data_dir: `str` for the directory of the training and validation data. batch_size: The global batch size to use.",
"name": "__init__",
"signature": "def __init__(self, is_training, data_dir, b... | 3 | null | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation d... | the_stack_v2_python_sparse | models/experimental/densenet_keras/densenet_keras_imagenet.py | tensorflow/tpu | train | 5,627 |
bdd9cdbd53ac365edfa72161f0a182bb0d11fb65 | [
"if value != None and (not isinstance(value, str)):\n value = repr(value)\nString.__init__(self, trait_name, value, is_enabled)",
"value = self._value.replace('.', '', 1)\np = self._text.palette()\nif value.isdigit():\n p.setColor(self._text.backgroundRole(), QtCore.Qt.white)\n self._is_valid = True\nels... | <|body_start_0|>
if value != None and (not isinstance(value, str)):
value = repr(value)
String.__init__(self, trait_name, value, is_enabled)
<|end_body_0|>
<|body_start_1|>
value = self._value.replace('.', '', 1)
p = self._text.palette()
if value.isdigit():
... | Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly. | Float | [
"LicenseRef-scancode-cecill-b-en"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Float:
"""Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly."""
def __init__(self, trait_name, value=None, is_enabled=True):
"""Method to initialize a File con... | stack_v2_sparse_classes_36k_train_017722 | 2,248 | permissive | [
{
"docstring": "Method to initialize a File control. Parameters ---------- trait_name: str (mandatory) the corresponding trait name value: str (optional) the default string is_enabled: bool (mandatory) parameter to activate or unactivate the control",
"name": "__init__",
"signature": "def __init__(self,... | 3 | stack_v2_sparse_classes_30k_train_015740 | Implement the Python class `Float` described below.
Class description:
Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly.
Method signatures and docstrings:
- def __init__(self, trait_name, valu... | Implement the Python class `Float` described below.
Class description:
Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly.
Method signatures and docstrings:
- def __init__(self, trait_name, valu... | c9745e339c24fc6a27d0adcc1e0c91b355588cac | <|skeleton|>
class Float:
"""Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly."""
def __init__(self, trait_name, value=None, is_enabled=True):
"""Method to initialize a File con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Float:
"""Control to enter a float. The properties "value" and "valid" contain the current value of the control and a bool set to True if the control is filled correctely respectivelly."""
def __init__(self, trait_name, value=None, is_enabled=True):
"""Method to initialize a File control. Paramet... | the_stack_v2_python_sparse | capsul/wip/apps_qt/base/controller/controls/Float.py | mathieubonnet/capsul | train | 0 |
16735da1a755908f562d3d59cf5ed009f837f213 | [
"with sjapi.connection() as db:\n sql = 'select count(0) as count from %s.%s where %s' % (bkjmc, tab, tj)\n rs = db.execute(sql)\n bxxl = rs.fetchone()\n csxx = {'id': get_uuid(), 'ssdxid': self.dxid, 'nr': bxxl['count'], 'jlsj': get_strftime2(), 'cjpzid': self.cjpzid, 'ip': self.zjip, 'cjmc': '%s.%s' %... | <|body_start_0|>
with sjapi.connection() as db:
sql = 'select count(0) as count from %s.%s where %s' % (bkjmc, tab, tj)
rs = db.execute(sql)
bxxl = rs.fetchone()
csxx = {'id': get_uuid(), 'ssdxid': self.dxid, 'nr': bxxl['count'], 'jlsj': get_strftime2(), 'cjpzid':... | Database | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW'):
"""获取数据表信息量"""
<|body_0|>
def get_bkjsyl(self, bkjmc='TSYW'):
"""获取某一数据表空间当前的使用率"""
<|body_1|>
def get_conversation(self):
"""获取数据库当前活动会话数"""
<|body_2|>
def get_zxsj(self):... | stack_v2_sparse_classes_36k_train_017723 | 16,132 | no_license | [
{
"docstring": "获取数据表信息量",
"name": "get_tabinf",
"signature": "def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW')"
},
{
"docstring": "获取某一数据表空间当前的使用率",
"name": "get_bkjsyl",
"signature": "def get_bkjsyl(self, bkjmc='TSYW')"
},
{
"docstring": "获取数据库当前活动会话数",
"name": "get_conver... | 4 | stack_v2_sparse_classes_30k_train_005257 | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW'): 获取数据表信息量
- def get_bkjsyl(self, bkjmc='TSYW'): 获取某一数据表空间当前的使用率
- def get_conversation(self): 获取数据库当前活动会话数
- def get_zxsj(self):... | Implement the Python class `Database` described below.
Class description:
Implement the Database class.
Method signatures and docstrings:
- def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW'): 获取数据表信息量
- def get_bkjsyl(self, bkjmc='TSYW'): 获取某一数据表空间当前的使用率
- def get_conversation(self): 获取数据库当前活动会话数
- def get_zxsj(self):... | 68ddf3df6d2cd731e6634b09d27aff4c22debd8e | <|skeleton|>
class Database:
def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW'):
"""获取数据表信息量"""
<|body_0|>
def get_bkjsyl(self, bkjmc='TSYW'):
"""获取某一数据表空间当前的使用率"""
<|body_1|>
def get_conversation(self):
"""获取数据库当前活动会话数"""
<|body_2|>
def get_zxsj(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Database:
def get_tabinf(self, tab, tj='1=1', bkjmc='TSYW'):
"""获取数据表信息量"""
with sjapi.connection() as db:
sql = 'select count(0) as count from %s.%s where %s' % (bkjmc, tab, tj)
rs = db.execute(sql)
bxxl = rs.fetchone()
csxx = {'id': get_uuid(),... | the_stack_v2_python_sparse | zh_manage/apps/_init/oa/yw_jkgl/yw_jkgl_001/yw_jkgl_001.py | yizhong120110/CPOS | train | 0 | |
76782d495114de1f1b7006976adf26f57a44c34d | [
"Bullet.__init__(self, lifetime, alpha, beta, x, y, True)\nself.width = width\nself.height = height\nself.vx = vx\nself.vy = vy\nself.angle = -atan2(self.vy, self.vx)",
"surface = pygame.transform.smoothscale(bomb_image, (self.width, self.height))\nsurface = pygame.transform.rotate(surface, 180 + self.angle * 180... | <|body_start_0|>
Bullet.__init__(self, lifetime, alpha, beta, x, y, True)
self.width = width
self.height = height
self.vx = vx
self.vy = vy
self.angle = -atan2(self.vy, self.vx)
<|end_body_0|>
<|body_start_1|>
surface = pygame.transform.smoothscale(bomb_image, (s... | Bomb | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы ... | stack_v2_sparse_classes_36k_train_017724 | 9,588 | no_license | [
{
"docstring": "Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы трения F = -av - bv^2 :param beta: параметр b в формуле силы трения F = -av - bv^2 :param width: длина бомбы :param height: толщина бомбы :param x: начальн... | 3 | stack_v2_sparse_classes_30k_train_008835 | Implement the Python class `Bomb` described below.
Class description:
Implement the Bomb class.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta): Конструктор класса бомб, которыми стреляет истре... | Implement the Python class `Bomb` described below.
Class description:
Implement the Bomb class.
Method signatures and docstrings:
- def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta): Конструктор класса бомб, которыми стреляет истре... | 19d00443e953a487e762676d6682579a537f55f0 | <|skeleton|>
class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Bomb:
def __init__(self, x=0, y=0, vx=0, vy=0, lifetime=bomb_lifetime, width=bomb_width, height=bomb_height, alpha=bomb_alpha, beta=bomb_beta):
"""Конструктор класса бомб, которыми стреляет истребитель :param lifetime: время жизни бомбы в секундах :param alpha: параметр a в формуле силы трения F = -av... | the_stack_v2_python_sparse | Лаба 8/modules/bullets.py | VladimirMolunov/molunov_infa_2021 | train | 0 | |
25900585b9a619017c521c8b488fc3e6d6d20728 | [
"self.ignore_index = ignore_index or nn.CrossEntropyLoss().ignore_index\nself.cross_entropy_loss = nn.CrossEntropyLoss(ignore_index=self.ignore_index)\nsuper().__init__(metric_fn=self.metric_fn, input_key=input_key, output_key=output_key, prefix=prefix)",
"cross_entropy = self.cross_entropy_loss(outputs, targets)... | <|body_start_0|>
self.ignore_index = ignore_index or nn.CrossEntropyLoss().ignore_index
self.cross_entropy_loss = nn.CrossEntropyLoss(ignore_index=self.ignore_index)
super().__init__(metric_fn=self.metric_fn, input_key=input_key, output_key=output_key, prefix=prefix)
<|end_body_0|>
<|body_start... | Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy. | PerplexityMetricCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PerplexityMetricCallback:
"""Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy."""
def __init__(self, input_key: str='targets', output_key: str='logits', prefix: str='perplexity', ignore_index: int=None):
"""Args: input_key (str): ... | stack_v2_sparse_classes_36k_train_017725 | 1,382 | permissive | [
{
"docstring": "Args: input_key (str): input key to use for perplexity calculation, target tokens output_key (str): output key to use for perplexity calculation, logits of the predicted tokens ignore_index (int): index to ignore, usually pad_index",
"name": "__init__",
"signature": "def __init__(self, i... | 2 | null | Implement the Python class `PerplexityMetricCallback` described below.
Class description:
Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy.
Method signatures and docstrings:
- def __init__(self, input_key: str='targets', output_key: str='logits', prefix: str='perp... | Implement the Python class `PerplexityMetricCallback` described below.
Class description:
Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy.
Method signatures and docstrings:
- def __init__(self, input_key: str='targets', output_key: str='logits', prefix: str='perp... | a35297ecab8d1a6c2f00b6435ea1d6d37ec9f441 | <|skeleton|>
class PerplexityMetricCallback:
"""Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy."""
def __init__(self, input_key: str='targets', output_key: str='logits', prefix: str='perplexity', ignore_index: int=None):
"""Args: input_key (str): ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PerplexityMetricCallback:
"""Perplexity is a very popular metric in NLP especially in Language Modeling task. It is 2^cross_entropy."""
def __init__(self, input_key: str='targets', output_key: str='logits', prefix: str='perplexity', ignore_index: int=None):
"""Args: input_key (str): input key to ... | the_stack_v2_python_sparse | catalyst/contrib/dl/callbacks/perplexity_metric.py | saswat0/catalyst | train | 2 |
bdd3363c9dad88e8cdee6abf7b898b41e8f4c08a | [
"if not builder:\n raise ValueError('Builder is not specified')\nself.__builder = builder",
"assert component, 'Software component is not specified'\nassert containerOsh, 'Software component container is not specified'\nosh = self.__builder.buildSoftwareComponent(component)\nosh.setContainer(containerOsh)\nret... | <|body_start_0|>
if not builder:
raise ValueError('Builder is not specified')
self.__builder = builder
<|end_body_0|>
<|body_start_1|>
assert component, 'Software component is not specified'
assert containerOsh, 'Software component container is not specified'
osh = s... | SoftwareComponentReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
<|body_0|>
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_017726 | 17,185 | no_license | [
{
"docstring": "@types: SoftwareComponentBuilder",
"name": "__init__",
"signature": "def __init__(self, builder)"
},
{
"docstring": "@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder",
"name": "reportSoftwareComponent",
"signature": "def reportSoftwareComponent(self, comp... | 2 | null | Implement the Python class `SoftwareComponentReporter` described below.
Class description:
Implement the SoftwareComponentReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: SoftwareComponentBuilder
- def reportSoftwareComponent(self, component, containerOsh): @types: SoftwareComp... | Implement the Python class `SoftwareComponentReporter` described below.
Class description:
Implement the SoftwareComponentReporter class.
Method signatures and docstrings:
- def __init__(self, builder): @types: SoftwareComponentBuilder
- def reportSoftwareComponent(self, component, containerOsh): @types: SoftwareComp... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
<|body_0|>
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareComponent, ObjectStateHolder -> ObjectStateHolder"""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftwareComponentReporter:
def __init__(self, builder):
"""@types: SoftwareComponentBuilder"""
if not builder:
raise ValueError('Builder is not specified')
self.__builder = builder
def reportSoftwareComponent(self, component, containerOsh):
"""@types: SoftwareC... | the_stack_v2_python_sparse | reference/ucmdb/discovery/sap_jee.py | madmonkyang/cda-record | train | 0 | |
014dc163b2a8134cfdfe59d769dc34a957bbdaec | [
"max_profit, min_price = (0, float('inf'))\nfor price in prices:\n min_price = min(min_price, price)\n profit = price - min_price\n max_profit = max(max_profit, profit)\nreturn max_profit",
"maxCur = 0\nmaxSoFar = 0\nfor i in range(1, len(prices)):\n maxCur = max(0, maxCur + prices[i] - prices[i - 1])... | <|body_start_0|>
max_profit, min_price = (0, float('inf'))
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
<|end_body_0|>
<|body_start_1|>
maxCur = 0
maxS... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
"""Kadane's algorithm."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_profit, min_price = (0, float('inf'))
for pr... | stack_v2_sparse_classes_36k_train_017727 | 1,372 | permissive | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": "Kadane's algorithm.",
"name": "maxProfit2",
"signature": "def maxProfit2(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009031 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): Kadane's algorithm. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit2(self, prices): Kadane's algorithm.
<|skeleton|>
class Solution:
def maxProfit(self, prices... | 980af3442afeef459468b381ec3a5505a4275a2e | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, prices):
"""Kadane's algorithm."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
max_profit, min_price = (0, float('inf'))
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
... | the_stack_v2_python_sparse | DP/Stock_Buy_Sell_1.py | anilpai/leetcode | train | 0 | |
a92d5741e02670332d1d67ead19c9254d0d9b5d3 | [
"if type(permission) == type(''):\n if permission in discord_permission_values:\n return discord_permission_values[permission]\n return None\nelif type(permission) == type(0):\n for perm in discord_permission_values:\n if discord_permission_values[perm] == permission:\n return perm... | <|body_start_0|>
if type(permission) == type(''):
if permission in discord_permission_values:
return discord_permission_values[permission]
return None
elif type(permission) == type(0):
for perm in discord_permission_values:
if discord_p... | Misc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Misc:
def convert(permission):
"""Get's the permission integer value from a string or vice-versa"""
<|body_0|>
def get_list(permission, member, state='all', perm_list=[]):
"""Gets a list of permissions the user has or doesn't have"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_017728 | 3,720 | no_license | [
{
"docstring": "Get's the permission integer value from a string or vice-versa",
"name": "convert",
"signature": "def convert(permission)"
},
{
"docstring": "Gets a list of permissions the user has or doesn't have",
"name": "get_list",
"signature": "def get_list(permission, member, state... | 2 | stack_v2_sparse_classes_30k_train_006583 | Implement the Python class `Misc` described below.
Class description:
Implement the Misc class.
Method signatures and docstrings:
- def convert(permission): Get's the permission integer value from a string or vice-versa
- def get_list(permission, member, state='all', perm_list=[]): Gets a list of permissions the user... | Implement the Python class `Misc` described below.
Class description:
Implement the Misc class.
Method signatures and docstrings:
- def convert(permission): Get's the permission integer value from a string or vice-versa
- def get_list(permission, member, state='all', perm_list=[]): Gets a list of permissions the user... | 7a045e038956f3fe966ae8a2b822be15ea7cb209 | <|skeleton|>
class Misc:
def convert(permission):
"""Get's the permission integer value from a string or vice-versa"""
<|body_0|>
def get_list(permission, member, state='all', perm_list=[]):
"""Gets a list of permissions the user has or doesn't have"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Misc:
def convert(permission):
"""Get's the permission integer value from a string or vice-versa"""
if type(permission) == type(''):
if permission in discord_permission_values:
return discord_permission_values[permission]
return None
elif type(pe... | the_stack_v2_python_sparse | data/types/discord/permissions.py | Alkali-Metal/disco-base | train | 0 | |
e2f04afe564524ab8906255f7cd3ff943862de48 | [
"if not root:\n return root\nleftmost = root\nwhile leftmost.left:\n head = leftmost\n while head:\n head.left.next = head.right\n if head.next:\n head.right.next = head.next.left\n head = head.next\n leftmost = leftmost.left\nif not root:\n return root\nqueue = collec... | <|body_start_0|>
if not root:
return root
leftmost = root
while leftmost.left:
head = leftmost
while head:
head.left.next = head.right
if head.next:
head.right.next = head.next.left
head = hea... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
<|body_0|>
def lowestCommon... | stack_v2_sparse_classes_36k_train_017729 | 4,318 | no_license | [
{
"docstring": "117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。",
"name": "connect",
"signature": "def connect(self, root: 'Node') -> 'Node'"
},
{
"docstri... | 5 | stack_v2_sparse_classes_30k_train_014724 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': 117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: 'Node') -> 'Node': 117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一... | 330330ef6bc42eeb17f4dea53c30d230506b4e8f | <|skeleton|>
class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
<|body_0|>
def lowestCommon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root: 'Node') -> 'Node':
"""117. 填充每个节点的下一个右侧节点指针 给定一个(完美)二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。 如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。"""
if not root:
return root
l... | the_stack_v2_python_sparse | Code/leetcode_everyday/0305.py | NiceToMeeetU/ToGetReady | train | 0 | |
7cfb27f500ba0605e13b6e9eb6396401bb21b758 | [
"parser.add_argument('--organization', required=True, metavar='ORGANIZATION_ID', completer=completers.OrganizationCompleter, help='Organization to update Logs Router CMEK settings for.')\ngroup = parser.add_mutually_exclusive_group(required=True)\nkms_resource_args.AddKmsKeyResourceArg(group, resource='logs being p... | <|body_start_0|>
parser.add_argument('--organization', required=True, metavar='ORGANIZATION_ID', completer=completers.OrganizationCompleter, help='Organization to update Logs Router CMEK settings for.')
group = parser.add_mutually_exclusive_group(required=True)
kms_resource_args.AddKmsKeyResourc... | Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK) for the Logs Router can currentl... | Update | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK... | stack_v2_sparse_classes_36k_train_017730 | 3,721 | permissive | [
{
"docstring": "Register flags for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: The updated... | 2 | stack_v2_sparse_classes_30k_train_021260 | Implement the Python class `Update` described below.
Class description:
Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it.... | Implement the Python class `Update` described below.
Class description:
Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it.... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Update:
"""Updates the CMEK settings for the Stackdriver Logs Router. Use this command to update the *--kms-key-name* associated with the Stackdriver Logs Router. The Cloud KMS key must already exist and Stackdriver Logging must have permission to access it. Customer-managed encryption keys (CMEK) for the Log... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/logging/cmek_settings/update.py | bopopescu/socialliteapp | train | 0 |
0fe8abbf993d8d64343ad52f50bc7398638d179f | [
"ret = {}\nfor s in strs:\n m = [0] * 26\n for c in s:\n m[ord(c) - 97] += 1\n m = tuple(m)\n ret[m] = ret.get(m, []) + [s]\nreturn list(ret.values())",
"ret = {}\nfor s in strs:\n m = [0] * 26\n for c in s:\n m[ord(c) - 97] += 1\n m = hash(tuple(m))\n ret[m] = ret.get(m, [])... | <|body_start_0|>
ret = {}
for s in strs:
m = [0] * 26
for c in s:
m[ord(c) - 97] += 1
m = tuple(m)
ret[m] = ret.get(m, []) + [s]
return list(ret.values())
<|end_body_0|>
<|body_start_1|>
ret = {}
for s in strs:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams1(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ret = {}
... | stack_v2_sparse_classes_36k_train_017731 | 954 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams",
"signature": "def groupAnagrams(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: List[List[str]]",
"name": "groupAnagrams1",
"signature": "def groupAnagrams1(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams1(self, strs): :type strs: List[str] :rtype: List[List[str]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def groupAnagrams(self, strs): :type strs: List[str] :rtype: List[List[str]]
- def groupAnagrams1(self, strs): :type strs: List[str] :rtype: List[List[str]]
<|skeleton|>
class S... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_0|>
def groupAnagrams1(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def groupAnagrams(self, strs):
""":type strs: List[str] :rtype: List[List[str]]"""
ret = {}
for s in strs:
m = [0] * 26
for c in s:
m[ord(c) - 97] += 1
m = tuple(m)
ret[m] = ret.get(m, []) + [s]
return li... | the_stack_v2_python_sparse | python/leetcode/49_Group_Anagrams.py | bobcaoge/my-code | train | 0 | |
9a11e0062eaee8538df61e85f21095dd8a9df916 | [
"if not root:\n return False\nsum -= root.val\nif not root.left and (not root.right):\n return sum == 0\nreturn self.has_path_sum_(root.left, sum) or self.has_path_sum_(root.right, sum)",
"if not root:\n return False\nelse:\n stack = [(root, sum - root.val)]\nwhile stack:\n node, curr_sum = stack.p... | <|body_start_0|>
if not root:
return False
sum -= root.val
if not root.left and (not root.right):
return sum == 0
return self.has_path_sum_(root.left, sum) or self.has_path_sum_(root.right, sum)
<|end_body_0|>
<|body_start_1|>
if not root:
ret... | Tree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tree:
def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:"""
<|body_0|>
def has_path_sum(self, root: 'TreeNode', sum: int) -> bool:
"""Approach: Iteration Time Comp... | stack_v2_sparse_classes_36k_train_017732 | 1,316 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:",
"name": "has_path_sum_",
"signature": "def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool"
},
{
"docstring": "Approach: Iteration Time Complexity: O(N) Space Complexity: O(N) :pa... | 2 | null | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool: Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:
- def has_path_sum(self, root: 'Tr... | Implement the Python class `Tree` described below.
Class description:
Implement the Tree class.
Method signatures and docstrings:
- def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool: Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:
- def has_path_sum(self, root: 'Tr... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Tree:
def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:"""
<|body_0|>
def has_path_sum(self, root: 'TreeNode', sum: int) -> bool:
"""Approach: Iteration Time Comp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tree:
def has_path_sum_(self, root: 'TreeNode', sum: int) -> bool:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(log N) :param root: :return:"""
if not root:
return False
sum -= root.val
if not root.left and (not root.right):
return su... | the_stack_v2_python_sparse | revisited_2021/tree/path_sum.py | Shiv2157k/leet_code | train | 1 | |
92662f364e4058d30601a53b578256be30ee4dfb | [
"try:\n s3 = boto3.resource('s3')\n buckets = s3.buckets.all()\n return buckets\nexcept:\n e = sys.exc_info()\n flash('S3 connection error, get all object failed')",
"try:\n s3 = boto3.client('s3')\n s3.delete_object(Bucket=bucket_id, Key=key_id)\nexcept:\n e = sys.exc_info()\n flash('S... | <|body_start_0|>
try:
s3 = boto3.resource('s3')
buckets = s3.buckets.all()
return buckets
except:
e = sys.exc_info()
flash('S3 connection error, get all object failed')
<|end_body_0|>
<|body_start_1|>
try:
s3 = boto3.client... | S3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3:
def getAlls3Bucket():
"""get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection"""
<|body_0|>
def deleteFileFromBucket(bucket_id, key_id):
"""get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection"... | stack_v2_sparse_classes_36k_train_017733 | 1,777 | no_license | [
{
"docstring": "get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection",
"name": "getAlls3Bucket",
"signature": "def getAlls3Bucket()"
},
{
"docstring": "get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection",
"name": "delete... | 4 | stack_v2_sparse_classes_30k_train_014890 | Implement the Python class `S3` described below.
Class description:
Implement the S3 class.
Method signatures and docstrings:
- def getAlls3Bucket(): get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection
- def deleteFileFromBucket(bucket_id, key_id): get all ec2 instance from AWS :re... | Implement the Python class `S3` described below.
Class description:
Implement the S3 class.
Method signatures and docstrings:
- def getAlls3Bucket(): get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection
- def deleteFileFromBucket(bucket_id, key_id): get all ec2 instance from AWS :re... | d583390c104462e365934075f0466717769ba56e | <|skeleton|>
class S3:
def getAlls3Bucket():
"""get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection"""
<|body_0|>
def deleteFileFromBucket(bucket_id, key_id):
"""get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3:
def getAlls3Bucket():
"""get all ec2 instance from AWS :return: ec2 instances list. type ec2.instancesCollection"""
try:
s3 = boto3.resource('s3')
buckets = s3.buckets.all()
return buckets
except:
e = sys.exc_info()
flash(... | the_stack_v2_python_sparse | app/S3FileManager.py | collinwzw/ECE1779A2 | train | 0 | |
7fcc698b6c771a1afea52e4e73bb32e81cd34003 | [
"super().__init__(event_data, covariates, 1)\nself.time_horizon = time_horizon\nself.interp_covariates = None\nself.break_points = None\nself.intensity_param_idx = [0, 1]\nself.co_param_idx = [2]\nself.zero_bound_idx_intensity = [1]\nself.zero_bound_idx_co = [0]",
"idx = bs.bisect_left(self.event_data[:, 0], time... | <|body_start_0|>
super().__init__(event_data, covariates, 1)
self.time_horizon = time_horizon
self.interp_covariates = None
self.break_points = None
self.intensity_param_idx = [0, 1]
self.co_param_idx = [2]
self.zero_bound_idx_intensity = [1]
self.zero_bou... | Class for point process model. | Model_intraday | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model_intraday:
"""Class for point process model."""
def __init__(self, event_data, covariates, time_horizon):
"""Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely observed factor, which need to be interpolated (all data exc... | stack_v2_sparse_classes_36k_train_017734 | 2,421 | permissive | [
{
"docstring": "Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely observed factor, which need to be interpolated (all data except for point process data) time_horizon: time horizon for point process data",
"name": "__init__",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_020832 | Implement the Python class `Model_intraday` described below.
Class description:
Class for point process model.
Method signatures and docstrings:
- def __init__(self, event_data, covariates, time_horizon): Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely obs... | Implement the Python class `Model_intraday` described below.
Class description:
Class for point process model.
Method signatures and docstrings:
- def __init__(self, event_data, covariates, time_horizon): Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely obs... | 7359f387534063080cf415feee241b3eda22bf91 | <|skeleton|>
class Model_intraday:
"""Class for point process model."""
def __init__(self, event_data, covariates, time_horizon):
"""Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely observed factor, which need to be interpolated (all data exc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model_intraday:
"""Class for point process model."""
def __init__(self, event_data, covariates, time_horizon):
"""Constructor of model event_data: data of point process (timestamps) covariates: exogenous data for completely observed factor, which need to be interpolated (all data except for point... | the_stack_v2_python_sparse | model_selfexciting/model_specs.py | an-kramer/exo-intraday | train | 1 |
1b7f7a781a846c0a13ccfe7431fbc1f0d264326f | [
"self._init_fn = jax.jit(init_fn, device=self._device, static_argnums=2)\nself._apply_fn = apply_fn\nself._sample_fn = jax.jit(self._sample, device=self._device, static_argnums=4)",
"batch_size, sample_len = x.shape\n\ndef one_step(params, state, rng, i, x):\n step_sample = jax.lax.dynamic_slice(x, [0, i], [ba... | <|body_start_0|>
self._init_fn = jax.jit(init_fn, device=self._device, static_argnums=2)
self._apply_fn = apply_fn
self._sample_fn = jax.jit(self._sample, device=self._device, static_argnums=4)
<|end_body_0|>
<|body_start_1|>
batch_size, sample_len = x.shape
def one_step(params... | Sampling from the Graph2Text TransformerXL model. | Graph2TextTransformerSampler | [
"CC-BY-SA-4.0",
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Graph2TextTransformerSampler:
"""Sampling from the Graph2Text TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
<|body_0|>
def _sample(self, params: Mapping[str, Any], state: Mapping... | stack_v2_sparse_classes_36k_train_017735 | 12,853 | permissive | [
{
"docstring": "Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`.",
"name": "_jit_model",
"signature": "def _jit_model(self, init_fn, apply_fn)"
},
{
"docstring": "Generate samples conditioned on the bag-of-words reprensation of graph. Args: params: parameters of the transforme... | 3 | null | Implement the Python class `Graph2TextTransformerSampler` described below.
Class description:
Sampling from the Graph2Text TransformerXL model.
Method signatures and docstrings:
- def _jit_model(self, init_fn, apply_fn): Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`.
- def _sample(self, params: M... | Implement the Python class `Graph2TextTransformerSampler` described below.
Class description:
Sampling from the Graph2Text TransformerXL model.
Method signatures and docstrings:
- def _jit_model(self, init_fn, apply_fn): Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`.
- def _sample(self, params: M... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class Graph2TextTransformerSampler:
"""Sampling from the Graph2Text TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
<|body_0|>
def _sample(self, params: Mapping[str, Any], state: Mapping... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Graph2TextTransformerSampler:
"""Sampling from the Graph2Text TransformerXL model."""
def _jit_model(self, init_fn, apply_fn):
"""Jit `init_fn` and `apply_fn`, the latter is used in `self._sample`."""
self._init_fn = jax.jit(init_fn, device=self._device, static_argnums=2)
self._ap... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/sampler.py | sethuramanio/deepmind-research | train | 1 |
a57637e13030d2d006ca9a225a2765a675b9785e | [
"super().__init__()\nself.value = CriticNet(state_dim, action_dim=None, hidden_dims=hidden_dims)\nself.advantage = policies.DiagGuassianPolicy(state_dim, action_spec, hidden_dims=hidden_dims)\nself.log_alpha = tf.Variable(0.0, dtype=tf.float32, trainable=True)",
"value = self.value(states)\nadvantage = self.advan... | <|body_start_0|>
super().__init__()
self.value = CriticNet(state_dim, action_dim=None, hidden_dims=hidden_dims)
self.advantage = policies.DiagGuassianPolicy(state_dim, action_spec, hidden_dims=hidden_dims)
self.log_alpha = tf.Variable(0.0, dtype=tf.float32, trainable=True)
<|end_body_0|>... | A soft critic network that estimates a dual Q-function. | SoftCriticNet | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SoftCriticNet:
"""A soft critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
<|b... | stack_v2_sparse_classes_36k_train_017736 | 10,984 | permissive | [
{
"docstring": "Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_spec, hidden_dims=(256, 256))"
},
{
"docstring": "Returns Q-value estimate for given ... | 2 | null | Implement the Python class `SoftCriticNet` described below.
Class description:
A soft critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_spec: Action specificatio... | Implement the Python class `SoftCriticNet` described below.
Class description:
A soft critic network that estimates a dual Q-function.
Method signatures and docstrings:
- def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)): Creates networks. Args: state_dim: State size. action_spec: Action specificatio... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class SoftCriticNet:
"""A soft critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SoftCriticNet:
"""A soft critic network that estimates a dual Q-function."""
def __init__(self, state_dim, action_spec, hidden_dims=(256, 256)):
"""Creates networks. Args: state_dim: State size. action_spec: Action specification. hidden_dims: List of hidden dimensions."""
super().__init__... | the_stack_v2_python_sparse | rl_repr/batch_rl/critic.py | Jimmy-INL/google-research | train | 1 |
096fa7e4c7281f285b1cd2bfac2fd032353feace | [
"self.whofor = whofor\nself.toppings = []\nself.valid_toppings = ['pepperoni', 'mushrooms', 'green peppers', 'sausage', 'ham', 'bacon']",
"if self.toppingOK(topping):\n self.toppings.append(topping)\nelse:\n print('You have asked to add an invalid topic; please try again: ')",
"if self.toppingOK(topping):... | <|body_start_0|>
self.whofor = whofor
self.toppings = []
self.valid_toppings = ['pepperoni', 'mushrooms', 'green peppers', 'sausage', 'ham', 'bacon']
<|end_body_0|>
<|body_start_1|>
if self.toppingOK(topping):
self.toppings.append(topping)
else:
print('Yo... | "A Virtual representation of a pizza | Pizza | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pizza:
""""A Virtual representation of a pizza"""
def __init__(self, whofor):
"""Constructor for the pizza class"""
<|body_0|>
def addTopping(self, topping):
"""Adds a topping to the pizza"""
<|body_1|>
def removeTopping(self, topping):
"""Re... | stack_v2_sparse_classes_36k_train_017737 | 1,015 | no_license | [
{
"docstring": "Constructor for the pizza class",
"name": "__init__",
"signature": "def __init__(self, whofor)"
},
{
"docstring": "Adds a topping to the pizza",
"name": "addTopping",
"signature": "def addTopping(self, topping)"
},
{
"docstring": "Removes a topping from the pizza"... | 4 | stack_v2_sparse_classes_30k_train_000451 | Implement the Python class `Pizza` described below.
Class description:
"A Virtual representation of a pizza
Method signatures and docstrings:
- def __init__(self, whofor): Constructor for the pizza class
- def addTopping(self, topping): Adds a topping to the pizza
- def removeTopping(self, topping): Removes a topping... | Implement the Python class `Pizza` described below.
Class description:
"A Virtual representation of a pizza
Method signatures and docstrings:
- def __init__(self, whofor): Constructor for the pizza class
- def addTopping(self, topping): Adds a topping to the pizza
- def removeTopping(self, topping): Removes a topping... | 7a331478914c6cafd79d8b3c6b18afb95429d52f | <|skeleton|>
class Pizza:
""""A Virtual representation of a pizza"""
def __init__(self, whofor):
"""Constructor for the pizza class"""
<|body_0|>
def addTopping(self, topping):
"""Adds a topping to the pizza"""
<|body_1|>
def removeTopping(self, topping):
"""Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pizza:
""""A Virtual representation of a pizza"""
def __init__(self, whofor):
"""Constructor for the pizza class"""
self.whofor = whofor
self.toppings = []
self.valid_toppings = ['pepperoni', 'mushrooms', 'green peppers', 'sausage', 'ham', 'bacon']
def addTopping(self... | the_stack_v2_python_sparse | week_04-05_lectures/Testing_Your_Classes/classes/pizza.py | sbrohl3/projects | train | 0 |
161f2a74ca7be6d3a43c2102b9499cdcc129fc8c | [
"super().__init__()\nself.clip_delta = clip_delta\nself.reduction = reduction or 'none'",
"diff = target - output\ndiff_abs = torch.abs(diff)\nquadratic_part = torch.clamp(diff_abs, max=self.clip_delta)\nlinear_part = diff_abs - quadratic_part\nloss = 0.5 * quadratic_part ** 2 + self.clip_delta * linear_part\nif ... | <|body_start_0|>
super().__init__()
self.clip_delta = clip_delta
self.reduction = reduction or 'none'
<|end_body_0|>
<|body_start_1|>
diff = target - output
diff_abs = torch.abs(diff)
quadratic_part = torch.clamp(diff_abs, max=self.clip_delta)
linear_part = diff_... | @TODO: Docs. Contribution is welcome. | HuberLossV0 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HuberLossV0:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, clip_delta=1.0, reduction='mean'):
"""@TODO: Docs. Contribution is welcome."""
<|body_0|>
def forward(self, output: torch.Tensor, target: torch.Tensor, weights=None) -> torch.Tensor:
"""@... | stack_v2_sparse_classes_36k_train_017738 | 4,457 | permissive | [
{
"docstring": "@TODO: Docs. Contribution is welcome.",
"name": "__init__",
"signature": "def __init__(self, clip_delta=1.0, reduction='mean')"
},
{
"docstring": "@TODO: Docs. Contribution is welcome.",
"name": "forward",
"signature": "def forward(self, output: torch.Tensor, target: torc... | 2 | stack_v2_sparse_classes_30k_val_000494 | Implement the Python class `HuberLossV0` described below.
Class description:
@TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, clip_delta=1.0, reduction='mean'): @TODO: Docs. Contribution is welcome.
- def forward(self, output: torch.Tensor, target: torch.Tensor, weights=Non... | Implement the Python class `HuberLossV0` described below.
Class description:
@TODO: Docs. Contribution is welcome.
Method signatures and docstrings:
- def __init__(self, clip_delta=1.0, reduction='mean'): @TODO: Docs. Contribution is welcome.
- def forward(self, output: torch.Tensor, target: torch.Tensor, weights=Non... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class HuberLossV0:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, clip_delta=1.0, reduction='mean'):
"""@TODO: Docs. Contribution is welcome."""
<|body_0|>
def forward(self, output: torch.Tensor, target: torch.Tensor, weights=None) -> torch.Tensor:
"""@... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HuberLossV0:
"""@TODO: Docs. Contribution is welcome."""
def __init__(self, clip_delta=1.0, reduction='mean'):
"""@TODO: Docs. Contribution is welcome."""
super().__init__()
self.clip_delta = clip_delta
self.reduction = reduction or 'none'
def forward(self, output: to... | the_stack_v2_python_sparse | catalyst/contrib/losses/regression.py | catalyst-team/catalyst | train | 3,038 |
a471c50bc35df60e8decaa965b1a9f6cfea2631e | [
"if self.chunk_size is None:\n return None\nchunk_size = self.chunk_size\nd = {k: coords[k].size for k in self._dims}\ns = reduce(mul, d.values(), 1)\nfor dim in coords.dims[::-1]:\n if dim in self._dims:\n continue\n n = chunk_size // s\n if n == 0:\n d[dim] = 1\n elif n < coords[dim].... | <|body_start_0|>
if self.chunk_size is None:
return None
chunk_size = self.chunk_size
d = {k: coords[k].size for k in self._dims}
s = reduce(mul, d.values(), 1)
for dim in coords.dims[::-1]:
if dim in self._dims:
continue
n = ch... | Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the node must iterate through the Coor... | Reduce2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the... | stack_v2_sparse_classes_36k_train_017739 | 27,208 | permissive | [
{
"docstring": "Shape of chunks for parallel processing or large arrays that do not fit in memory. Returns ------- list List of integers giving the shape of each chunk.",
"name": "_get_chunk_shape",
"signature": "def _get_chunk_shape(self, coords)"
},
{
"docstring": "Generator for the chunks of ... | 3 | stack_v2_sparse_classes_30k_train_020057 | Implement the Python class `Reduce2` described below.
Class description:
Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For ... | Implement the Python class `Reduce2` described below.
Class description:
Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For ... | 0a96a9b3726aee9bb6208244ae96ed685667e16c | <|skeleton|>
class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Reduce2:
"""Extended Reduce class that enables chunks that are smaller than the reduced output array. The base Reduce node ensures that each chunk is at least as big as the reduced output, which works for statistics that can be calculated in O(1) space. For statistics that require O(n) space, the node must it... | the_stack_v2_python_sparse | podpac/core/algorithm/stats.py | ccuadrado/podpac | train | 0 |
4f1dfe232bfb65c38d1284180f2fdf6d777d1845 | [
"total = 0\nfor i in xrange(0, len(nums), 1):\n total += nums[i]\n nums[i] = total\nself.nums = nums",
"delta = self.nums[i] - (self.nums[i - 1] if i > 0 else 0) - val\nfor m in xrange(i, len(self.nums), 1):\n self.nums[m] -= delta",
"max_total = self.nums[j]\nmin_total = self.nums[i - 1] if i > 0 else... | <|body_start_0|>
total = 0
for i in xrange(0, len(nums), 1):
total += nums[i]
nums[i] = total
self.nums = nums
<|end_body_0|>
<|body_start_1|>
delta = self.nums[i] - (self.nums[i - 1] if i > 0 else 0) - val
for m in xrange(i, len(self.nums), 1):
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""Arguments: nums {[list]} -- [数组]"""
<|body_0|>
def update(self, i, val):
"""[更新序号为i的元素值为val] Arguments: i {[int]} -- [序号] val {[int]} -- [数值]"""
<|body_1|>
def sumRange(self, i, j):
"""[返回序号i到序号j的元素总和,i<=j] ... | stack_v2_sparse_classes_36k_train_017740 | 1,398 | no_license | [
{
"docstring": "Arguments: nums {[list]} -- [数组]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "[更新序号为i的元素值为val] Arguments: i {[int]} -- [序号] val {[int]} -- [数值]",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": "[返回序号... | 3 | stack_v2_sparse_classes_30k_train_009153 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): Arguments: nums {[list]} -- [数组]
- def update(self, i, val): [更新序号为i的元素值为val] Arguments: i {[int]} -- [序号] val {[int]} -- [数值]
- def sumRange(self, i, j... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): Arguments: nums {[list]} -- [数组]
- def update(self, i, val): [更新序号为i的元素值为val] Arguments: i {[int]} -- [序号] val {[int]} -- [数值]
- def sumRange(self, i, j... | 70a580603d996d9843cda3c167c6e63c29df6656 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""Arguments: nums {[list]} -- [数组]"""
<|body_0|>
def update(self, i, val):
"""[更新序号为i的元素值为val] Arguments: i {[int]} -- [序号] val {[int]} -- [数值]"""
<|body_1|>
def sumRange(self, i, j):
"""[返回序号i到序号j的元素总和,i<=j] ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""Arguments: nums {[list]} -- [数组]"""
total = 0
for i in xrange(0, len(nums), 1):
total += nums[i]
nums[i] = total
self.nums = nums
def update(self, i, val):
"""[更新序号为i的元素值为val] Arguments: i {[int]} -- [序... | the_stack_v2_python_sparse | src/code/code_307.py | fanzijian/leet-code-practice | train | 1 | |
64b46bd4a7bea407ade903ffea07f9604be1bffb | [
"super(PublishingDelayTimeMetric, self).__init__()\nself.logger = logging.getLogger(__name__)\nself.accumulated_tuple_delay_time = self.current_metric",
"self.processed_instances += 1\nlast_delay = self.accumulated_tuple_delay_time\ntuple_timestamp = record_pair.anonymized_record.timestamp\nself.accumulated_tuple... | <|body_start_0|>
super(PublishingDelayTimeMetric, self).__init__()
self.logger = logging.getLogger(__name__)
self.accumulated_tuple_delay_time = self.current_metric
<|end_body_0|>
<|body_start_1|>
self.processed_instances += 1
last_delay = self.accumulated_tuple_delay_time
... | Class implementing a publishing delay estimator, measuring the average delay of published tuples | PublishingDelayTimeMetric | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
<|body_0|>
def update_estimation(self, time, record_pair, cluster=None):
... | stack_v2_sparse_classes_36k_train_017741 | 1,999 | no_license | [
{
"docstring": "Class constructor - initialization",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Update the publishing delay of current published tuple. :param time: Current time step in stream (last assigned tuple). :param record_pair: Pair of original instance and ... | 3 | stack_v2_sparse_classes_30k_test_000459 | Implement the Python class `PublishingDelayTimeMetric` described below.
Class description:
Class implementing a publishing delay estimator, measuring the average delay of published tuples
Method signatures and docstrings:
- def __init__(self): Class constructor - initialization
- def update_estimation(self, time, rec... | Implement the Python class `PublishingDelayTimeMetric` described below.
Class description:
Class implementing a publishing delay estimator, measuring the average delay of published tuples
Method signatures and docstrings:
- def __init__(self): Class constructor - initialization
- def update_estimation(self, time, rec... | b66862bd469bf078ca12bdb692e39675d40c96b8 | <|skeleton|>
class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
<|body_0|>
def update_estimation(self, time, record_pair, cluster=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PublishingDelayTimeMetric:
"""Class implementing a publishing delay estimator, measuring the average delay of published tuples"""
def __init__(self):
"""Class constructor - initialization"""
super(PublishingDelayTimeMetric, self).__init__()
self.logger = logging.getLogger(__name__... | the_stack_v2_python_sparse | PerformanceEstimators/ExecutionTimeMetric/PublishingDelayTimeMetric.py | Navypowder/MiDiPSA-for-non-stationary-streams | train | 0 |
b29c49d96a74347b0855977fb82301bef2bdf075 | [
"params = NoticesForm(data=request.GET)\nparams.is_valid(raise_exception=True)\ncursor = params.data.get('cursor')\nlimit = params.data.get('limit')\nresponse = dict()\nboard_categories = notices_service.get_categories()\ncategories = NoticeCategorySerializer(board_categories, many=True)\nif cursor == 1:\n respo... | <|body_start_0|>
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
response = dict()
board_categories = notices_service.get_categories()
categories = NoticeCategorySeria... | NoticeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""공지사항"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
... | stack_v2_sparse_classes_36k_train_017742 | 2,349 | no_license | [
{
"docstring": "공지사항 리스트",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "공지사항",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004610 | Implement the Python class `NoticeView` described below.
Class description:
Implement the NoticeView class.
Method signatures and docstrings:
- def list(self, request): 공지사항 리스트
- def retrieve(self, request, pk=None): 공지사항 | Implement the Python class `NoticeView` described below.
Class description:
Implement the NoticeView class.
Method signatures and docstrings:
- def list(self, request): 공지사항 리스트
- def retrieve(self, request, pk=None): 공지사항
<|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|... | 0edc046f57a1c171c10be5dfa4b4e26f440847be | <|skeleton|>
class NoticeView:
def list(self, request):
"""공지사항 리스트"""
<|body_0|>
def retrieve(self, request, pk=None):
"""공지사항"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NoticeView:
def list(self, request):
"""공지사항 리스트"""
params = NoticesForm(data=request.GET)
params.is_valid(raise_exception=True)
cursor = params.data.get('cursor')
limit = params.data.get('limit')
response = dict()
board_categories = notices_service.get_... | the_stack_v2_python_sparse | backends/api/v2/notices.py | jmp7786/coins | train | 0 | |
4e963525e51b001b90bccb5bb3440636654b9a70 | [
"ret = 'NONE'\nif self == self.ADC0:\n ret = 'ADC0'\nelif self == self.ADC1:\n ret = 'ADC1'\nelif self == self.ADC2:\n ret = 'ADC2'\nelif self == self.IMU_ACCEL:\n ret = 'IMU_ACCEL'\nelif self == self.IMU_GYRO:\n ret = 'IMU_GYRO'\nelif self == self.IMU_TEMP:\n ret = 'IMU_TEMP'\nreturn ret",
"ret... | <|body_start_0|>
ret = 'NONE'
if self == self.ADC0:
ret = 'ADC0'
elif self == self.ADC1:
ret = 'ADC1'
elif self == self.ADC2:
ret = 'ADC2'
elif self == self.IMU_ACCEL:
ret = 'IMU_ACCEL'
elif self == self.IMU_GYRO:
... | This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31 | f_sensors | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class f_sensors:
"""This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31"""
def __str__(self):
"""Returns the stringified version of this enum. Args: None Returns: String representing the enum ... | stack_v2_sparse_classes_36k_train_017743 | 13,308 | no_license | [
{
"docstring": "Returns the stringified version of this enum. Args: None Returns: String representing the enum data.",
"name": "__str__",
"signature": "def __str__(self)"
},
{
"docstring": "Returns sampling rate associated with the sensor associated with the enum. Args: None Returns: Integer rep... | 3 | stack_v2_sparse_classes_30k_train_018468 | Implement the Python class `f_sensors` described below.
Class description:
This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31
Method signatures and docstrings:
- def __str__(self): Returns the stringified version of thi... | Implement the Python class `f_sensors` described below.
Class description:
This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31
Method signatures and docstrings:
- def __str__(self): Returns the stringified version of thi... | 30ac8bb8ad1a6dbfa7c2181949f468213a6ae717 | <|skeleton|>
class f_sensors:
"""This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31"""
def __str__(self):
"""Returns the stringified version of this enum. Args: None Returns: String representing the enum ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class f_sensors:
"""This class defines sensors. Add to this class when defining a new digital sensor. ADC0-2 can be used to identify analog channels. @author: sdmay18-31"""
def __str__(self):
"""Returns the stringified version of this enum. Args: None Returns: String representing the enum data."""
... | the_stack_v2_python_sparse | src/front_end/mdl_firmware.py | tdemps/CyDAQ | train | 0 |
d65a58daf2b0ddcab9a40becf5fc6b01532cc9f4 | [
"self.pre = [i for i in range(n)]\ngroup = n\nfor link in s:\n x, y = link\n root1 = self.unionsearch(x)\n root2 = self.unionsearch(y)\n if root1 != root2:\n self.pre[root1] = root2\n group -= 1\nreturn group",
"son = root\nwhile root != self.pre[root]:\n root = self.pre[root]\nwhile ... | <|body_start_0|>
self.pre = [i for i in range(n)]
group = n
for link in s:
x, y = link
root1 = self.unionsearch(x)
root2 = self.unionsearch(y)
if root1 != root2:
self.pre[root1] = root2
group -= 1
return grou... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def union(self, n, s):
"""n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图"""
<|body_0|>
def unionsearch(self, root):
"""找到最终上级"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pre = [i for i in range(n)]
group = n
for link in s:
... | stack_v2_sparse_classes_36k_train_017744 | 1,527 | no_license | [
{
"docstring": "n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图",
"name": "union",
"signature": "def union(self, n, s)"
},
{
"docstring": "找到最终上级",
"name": "unionsearch",
"signature": "def unionsearch(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def union(self, n, s): n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图
- def unionsearch(self, root): 找到最终上级 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def union(self, n, s): n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图
- def unionsearch(self, root): 找到最终上级
<|skeleton|>
class Solution:
def union(self, n, s):
"""n:节点总个数 s: ... | 5b55e35f15c7bf098203a6aabbb7aad6b14579fa | <|skeleton|>
class Solution:
def union(self, n, s):
"""n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图"""
<|body_0|>
def unionsearch(self, root):
"""找到最终上级"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def union(self, n, s):
"""n:节点总个数 s: 所有的连接 return:返回有多少个独立连通子图"""
self.pre = [i for i in range(n)]
group = n
for link in s:
x, y = link
root1 = self.unionsearch(x)
root2 = self.unionsearch(y)
if root1 != root2:
... | the_stack_v2_python_sparse | gatherAlgorithms/并查集.py | queryor/algorithms | train | 0 | |
f4e845e2e6deec553fedf1ea26a72774e6ad7a34 | [
"left, right = (0, len(s) - 1)\nwhile left < right:\n s[left], s[right] = (s[right], s[left])\n left, right = (left + 1, right - 1)",
"a = list(s)\nfor i in range(0, len(a), 2 * k):\n a[i:i + k] = reversed(a[i:i + k])\nreturn ''.join(a)"
] | <|body_start_0|>
left, right = (0, len(s) - 1)
while left < right:
s[left], s[right] = (s[right], s[left])
left, right = (left + 1, right - 1)
<|end_body_0|>
<|body_start_1|>
a = list(s)
for i in range(0, len(a), 2 * k):
a[i:i + k] = reversed(a[i:i + ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseString(self, s: List[str]) -> None:
"""344.反转字符串 https://leetcode-cn.com/problems/reverse-string/"""
<|body_0|>
def reverseStr(self, s: str, k: int) -> str:
"""541.反转字符串II https://leetcode-cn.com/problems/reverse-string-ii/"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_017745 | 835 | no_license | [
{
"docstring": "344.反转字符串 https://leetcode-cn.com/problems/reverse-string/",
"name": "reverseString",
"signature": "def reverseString(self, s: List[str]) -> None"
},
{
"docstring": "541.反转字符串II https://leetcode-cn.com/problems/reverse-string-ii/",
"name": "reverseStr",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_val_000718 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s: List[str]) -> None: 344.反转字符串 https://leetcode-cn.com/problems/reverse-string/
- def reverseStr(self, s: str, k: int) -> str: 541.反转字符串II https://leetc... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseString(self, s: List[str]) -> None: 344.反转字符串 https://leetcode-cn.com/problems/reverse-string/
- def reverseStr(self, s: str, k: int) -> str: 541.反转字符串II https://leetc... | 6580c7fd9a62494f82cedf69edda793865b5bd2d | <|skeleton|>
class Solution:
def reverseString(self, s: List[str]) -> None:
"""344.反转字符串 https://leetcode-cn.com/problems/reverse-string/"""
<|body_0|>
def reverseStr(self, s: str, k: int) -> str:
"""541.反转字符串II https://leetcode-cn.com/problems/reverse-string-ii/"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseString(self, s: List[str]) -> None:
"""344.反转字符串 https://leetcode-cn.com/problems/reverse-string/"""
left, right = (0, len(s) - 1)
while left < right:
s[left], s[right] = (s[right], s[left])
left, right = (left + 1, right - 1)
def rever... | the_stack_v2_python_sparse | Week_09/344.reverse-string.py | ZGingko/algorithm008-class02 | train | 0 | |
1c22dff6c226306eadd52f91308b86874652c0a4 | [
"host = settings['EMAIL']['HOST']\nif not host:\n raise ValueError('no email server host defined')\ntry:\n port = settings['EMAIL']['PORT']\nexcept KeyError:\n self.server = smtplib.SMTP(host)\nelse:\n self.server = smtplib.SMTP(host, port=port)\nif settings['EMAIL'].get('TLS'):\n self.server.starttl... | <|body_start_0|>
host = settings['EMAIL']['HOST']
if not host:
raise ValueError('no email server host defined')
try:
port = settings['EMAIL']['PORT']
except KeyError:
self.server = smtplib.SMTP(host)
else:
self.server = smtplib.SMTP... | A connection to an email server for sending emails. | EmailServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailServer:
"""A connection to an email server for sending emails."""
def __init__(self):
"""Open the connection to the email server. Raise ValueError if no email server host has been defined."""
<|body_0|>
def __del__(self):
"""Close the connection to the email... | stack_v2_sparse_classes_36k_train_017746 | 14,137 | permissive | [
{
"docstring": "Open the connection to the email server. Raise ValueError if no email server host has been defined.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Close the connection to the email server.",
"name": "__del__",
"signature": "def __del__(self)"
... | 3 | stack_v2_sparse_classes_30k_train_006679 | Implement the Python class `EmailServer` described below.
Class description:
A connection to an email server for sending emails.
Method signatures and docstrings:
- def __init__(self): Open the connection to the email server. Raise ValueError if no email server host has been defined.
- def __del__(self): Close the co... | Implement the Python class `EmailServer` described below.
Class description:
A connection to an email server for sending emails.
Method signatures and docstrings:
- def __init__(self): Open the connection to the email server. Raise ValueError if no email server host has been defined.
- def __del__(self): Close the co... | ff391d647a5569c0aa4aadf626b35ad3520cdbdf | <|skeleton|>
class EmailServer:
"""A connection to an email server for sending emails."""
def __init__(self):
"""Open the connection to the email server. Raise ValueError if no email server host has been defined."""
<|body_0|>
def __del__(self):
"""Close the connection to the email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailServer:
"""A connection to an email server for sending emails."""
def __init__(self):
"""Open the connection to the email server. Raise ValueError if no email server host has been defined."""
host = settings['EMAIL']['HOST']
if not host:
raise ValueError('no email... | the_stack_v2_python_sparse | publications/utils.py | Hammarn/Publications | train | 0 |
22ac13741c8a4799b0a5370147dc262018e261d6 | [
"super(Json, self).start(**kwargs)\nflat = self.GETARGS.get('json_flat', JSON_FLAT)\nself._first_row = True\nself.open_fd()\nbegin = '' if flat else '['\nself._fd.write(begin)",
"super(Json, self).stop(**kwargs)\nflat = self.GETARGS.get('json_flat', JSON_FLAT)\nself.do_export_schema()\nend = '' if flat else '\\n]... | <|body_start_0|>
super(Json, self).start(**kwargs)
flat = self.GETARGS.get('json_flat', JSON_FLAT)
self._first_row = True
self.open_fd()
begin = '' if flat else '['
self._fd.write(begin)
<|end_body_0|>
<|body_start_1|>
super(Json, self).stop(**kwargs)
fla... | Pass. | Json | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Json:
"""Pass."""
def start(self, **kwargs):
"""Create jsonstream and associated file descriptor."""
<|body_0|>
def stop(self, **kwargs):
"""Close jsonstream and associated file descriptor."""
<|body_1|>
def process_row(self, row):
"""Write r... | stack_v2_sparse_classes_36k_train_017747 | 2,074 | permissive | [
{
"docstring": "Create jsonstream and associated file descriptor.",
"name": "start",
"signature": "def start(self, **kwargs)"
},
{
"docstring": "Close jsonstream and associated file descriptor.",
"name": "stop",
"signature": "def stop(self, **kwargs)"
},
{
"docstring": "Write row... | 5 | stack_v2_sparse_classes_30k_train_009472 | Implement the Python class `Json` described below.
Class description:
Pass.
Method signatures and docstrings:
- def start(self, **kwargs): Create jsonstream and associated file descriptor.
- def stop(self, **kwargs): Close jsonstream and associated file descriptor.
- def process_row(self, row): Write row to jsonstrea... | Implement the Python class `Json` described below.
Class description:
Pass.
Method signatures and docstrings:
- def start(self, **kwargs): Create jsonstream and associated file descriptor.
- def stop(self, **kwargs): Close jsonstream and associated file descriptor.
- def process_row(self, row): Write row to jsonstrea... | 09fd564d62f0ddf7aa44db14a509eaafaf0c930f | <|skeleton|>
class Json:
"""Pass."""
def start(self, **kwargs):
"""Create jsonstream and associated file descriptor."""
<|body_0|>
def stop(self, **kwargs):
"""Close jsonstream and associated file descriptor."""
<|body_1|>
def process_row(self, row):
"""Write r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Json:
"""Pass."""
def start(self, **kwargs):
"""Create jsonstream and associated file descriptor."""
super(Json, self).start(**kwargs)
flat = self.GETARGS.get('json_flat', JSON_FLAT)
self._first_row = True
self.open_fd()
begin = '' if flat else '['
... | the_stack_v2_python_sparse | axonius_api_client/api/asset_callbacks/base_json.py | geransmith/axonius_api_client | train | 0 |
34c9390051b20e4ba71c6b229863dabac924e83a | [
"super(SourceLoss, self).__init__()\nself.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1)\nself.loss = nn.MSELoss()",
"spectral_envelope = self.cheaptrick.forward(x, f0)\nzeros = torch.zeros_like(spect... | <|body_start_0|>
super(SourceLoss, self).__init__()
self.cheaptrick = CheapTrick(sampling_rate=sampling_rate, hop_size=hop_size, fft_size=fft_size, f0_floor=f0_floor, f0_ceil=f0_ceil, uv_threshold=uv_threshold, q1=q1)
self.loss = nn.MSELoss()
<|end_body_0|>
<|body_start_1|>
spectral_env... | SourceLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
<|bo... | stack_v2_sparse_classes_36k_train_017748 | 1,728 | permissive | [
{
"docstring": "Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type.",
"name": "__init__",
"signature": "def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0... | 2 | stack_v2_sparse_classes_30k_train_017179 | Implement the Python class `SourceLoss` described below.
Class description:
Implement the SourceLoss class.
Method signatures and docstrings:
- def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i... | Implement the Python class `SourceLoss` described below.
Class description:
Implement the SourceLoss class.
Method signatures and docstrings:
- def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15): Initialize source loss module. Args: fft_size (int): FFT size. hop_size (i... | 67331ddb5d6a7227120818842c61b6e07de52ba7 | <|skeleton|>
class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SourceLoss:
def __init__(self, sampling_rate, hop_size, fft_size, f0_floor, f0_ceil, uv_threshold=0, q1=-0.15):
"""Initialize source loss module. Args: fft_size (int): FFT size. hop_size (int): Hop size. win_length (int): Window length. window (str): Window function type."""
super(SourceLoss, ... | the_stack_v2_python_sparse | usfgan/losses/source_loss.py | hendrikTpl/UnifiedSourceFilterGAN | train | 0 | |
c8faa2f64b9e0e13c9d227e605dee78ff2b5a6a5 | [
"curate_data_structure = CurateDataStructure(name=validated_data['name'], template=validated_data['template'], form_string=validated_data['form_string'] if 'form_string' in validated_data else None, user=str(self.context['request'].user.id), data=validated_data['data'] if 'data' in validated_data else None, data_st... | <|body_start_0|>
curate_data_structure = CurateDataStructure(name=validated_data['name'], template=validated_data['template'], form_string=validated_data['form_string'] if 'form_string' in validated_data else None, user=str(self.context['request'].user.id), data=validated_data['data'] if 'data' in validated_dat... | CurateDataStructure Serializer | CurateDataStructureSerializer | [
"BSD-3-Clause",
"NIST-Software"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CurateDataStructureSerializer:
"""CurateDataStructure Serializer"""
def create(self, validated_data):
"""Create and return a new `CurateDataStructure` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and retu... | stack_v2_sparse_classes_36k_train_017749 | 2,131 | permissive | [
{
"docstring": "Create and return a new `CurateDataStructure` instance, given the validated data.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update and return an existing `CurateDataStructure` instance, given the validated data.",
"name": "update",... | 2 | stack_v2_sparse_classes_30k_test_000761 | Implement the Python class `CurateDataStructureSerializer` described below.
Class description:
CurateDataStructure Serializer
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `CurateDataStructure` instance, given the validated data.
- def update(self, instance, validated_d... | Implement the Python class `CurateDataStructureSerializer` described below.
Class description:
CurateDataStructure Serializer
Method signatures and docstrings:
- def create(self, validated_data): Create and return a new `CurateDataStructure` instance, given the validated data.
- def update(self, instance, validated_d... | 77e9faf6b930d8bb84175a8c2de486b0536582ba | <|skeleton|>
class CurateDataStructureSerializer:
"""CurateDataStructure Serializer"""
def create(self, validated_data):
"""Create and return a new `CurateDataStructure` instance, given the validated data."""
<|body_0|>
def update(self, instance, validated_data):
"""Update and retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CurateDataStructureSerializer:
"""CurateDataStructure Serializer"""
def create(self, validated_data):
"""Create and return a new `CurateDataStructure` instance, given the validated data."""
curate_data_structure = CurateDataStructure(name=validated_data['name'], template=validated_data['t... | the_stack_v2_python_sparse | core_curate_app/rest/curate_data_structure/serializers.py | usnistgov/core_curate_app | train | 0 |
54355e4e8a3a8e1b299ed2b0ca905fe8f5053dd3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn AppManagementConfiguration()",
"from .key_credential_configuration import KeyCredentialConfiguration\nfrom .password_credential_configuration import PasswordCredentialConfiguration\nfrom .key_credential_configuration import KeyCredenti... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return AppManagementConfiguration()
<|end_body_0|>
<|body_start_1|>
from .key_credential_configuration import KeyCredentialConfiguration
from .password_credential_configuration import PasswordC... | AppManagementConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppManagementConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppManagementConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and... | stack_v2_sparse_classes_36k_train_017750 | 3,632 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: AppManagementConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_discri... | 3 | null | Implement the Python class `AppManagementConfiguration` described below.
Class description:
Implement the AppManagementConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppManagementConfiguration: Creates a new instance of the appropr... | Implement the Python class `AppManagementConfiguration` described below.
Class description:
Implement the AppManagementConfiguration class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppManagementConfiguration: Creates a new instance of the appropr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class AppManagementConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppManagementConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppManagementConfiguration:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> AppManagementConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | the_stack_v2_python_sparse | msgraph/generated/models/app_management_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
5fa072b812c652cfbaef5c51691709aac47560f5 | [
"super(RelativeTransformerLayers, self).__init__(name=name, **kwargs)\nif intermediate_size is None:\n intermediate_size = 4 * hidden_size\nself.hidden_size = hidden_size\nself.num_hidden_layers = num_hidden_layers\nself.num_attention_heads = num_attention_heads\nself.intermediate_size = intermediate_size\nself.... | <|body_start_0|>
super(RelativeTransformerLayers, self).__init__(name=name, **kwargs)
if intermediate_size is None:
intermediate_size = 4 * hidden_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_h... | A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` instead. We just include this layer as a convenience s... | RelativeTransformerLayers | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` i... | stack_v2_sparse_classes_36k_train_017751 | 27,776 | permissive | [
{
"docstring": "Init. Args: hidden_size: Size of the output hidden dimension. Must match the input hidden dimension size. num_hidden_layers: Number of Transformer layers. Each layer includes both an attention sublayer and a feed-forward sublayer. num_attention_heads: Number of attention heads. Must evenly divid... | 2 | null | Implement the Python class `RelativeTransformerLayers` described below.
Class description:
A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ET... | Implement the Python class `RelativeTransformerLayers` described below.
Class description:
A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ET... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RelativeTransformerLayers:
"""A sequence of Transformer encoder layers with optional relative attention. Just like the original Transformer, this layer uses full attention and scales quadratically with the input length. To efficiently handle large inputs, ETC uses `GlobalLocalTransformerLayers` instead. We ju... | the_stack_v2_python_sparse | etcmodel/layers/transformer.py | Jimmy-INL/google-research | train | 1 |
486627b352ed8cae16d3814d8150e2ac4d9c1770 | [
"if field_name in data:\n data = data.copy()\n try:\n data[field_name] = ','.join(data.getlist(field_name))\n except AttributeError:\n data[field_name] = ','.join(data[field_name])\nreturn super(MultiSelectField, self).field_from_native(data, files, field_name, into)",
"for val in value.spl... | <|body_start_0|>
if field_name in data:
data = data.copy()
try:
data[field_name] = ','.join(data.getlist(field_name))
except AttributeError:
data[field_name] = ','.join(data[field_name])
return super(MultiSelectField, self).field_from_n... | MultiSelectField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
<|body_0|>
def valid_value(self, value):
"""checks for each item if is a valid value"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_36k_train_017752 | 6,326 | no_license | [
{
"docstring": "convert multiselect data into comma separated string",
"name": "field_from_native",
"signature": "def field_from_native(self, data, files, field_name, into)"
},
{
"docstring": "checks for each item if is a valid value",
"name": "valid_value",
"signature": "def valid_value... | 2 | stack_v2_sparse_classes_30k_train_019488 | Implement the Python class `MultiSelectField` described below.
Class description:
Implement the MultiSelectField class.
Method signatures and docstrings:
- def field_from_native(self, data, files, field_name, into): convert multiselect data into comma separated string
- def valid_value(self, value): checks for each i... | Implement the Python class `MultiSelectField` described below.
Class description:
Implement the MultiSelectField class.
Method signatures and docstrings:
- def field_from_native(self, data, files, field_name, into): convert multiselect data into comma separated string
- def valid_value(self, value): checks for each i... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
<|body_0|>
def valid_value(self, value):
"""checks for each item if is a valid value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
if field_name in data:
data = data.copy()
try:
data[field_name] = ','.join(data.getlist(field_name))
exce... | the_stack_v2_python_sparse | controller/apps/api/serializers.py | m00dy/vct-controller | train | 2 | |
c6a8bf052bd1d377565c9aeb15e3dcde937a35ec | [
"self.to = to\nself.mfrom = mfrom\nself.application_id = application_id\nself.scope = scope\nself.message = message\nself.digits = digits",
"if dictionary is None:\n return None\nto = dictionary.get('to')\nmfrom = dictionary.get('from')\napplication_id = dictionary.get('applicationId')\nmessage = dictionary.ge... | <|body_start_0|>
self.to = to
self.mfrom = mfrom
self.application_id = application_id
self.scope = scope
self.message = message
self.digits = digits
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
to = dictionary.get('to')
... | Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The application unique ID, obtained from Bandwidth. scope (st... | TwoFactorCodeRequestSchema | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The app... | stack_v2_sparse_classes_36k_train_017753 | 3,300 | permissive | [
{
"docstring": "Constructor for the TwoFactorCodeRequestSchema class",
"name": "__init__",
"signature": "def __init__(self, to=None, mfrom=None, application_id=None, message=None, digits=None, scope=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (d... | 2 | null | Implement the Python class `TwoFactorCodeRequestSchema` described below.
Class description:
Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa... | Implement the Python class `TwoFactorCodeRequestSchema` described below.
Class description:
Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa... | 447df3cc8cb7acaf3361d842630c432a9c31ce6e | <|skeleton|>
class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The app... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoFactorCodeRequestSchema:
"""Implementation of the 'TwoFactorCodeRequestSchema' model. TODO: type model description here. Attributes: to (string): The phone number to send the 2fa code to. mfrom (string): The application phone number, the sender of the 2fa code. application_id (string): The application uniq... | the_stack_v2_python_sparse | bandwidth/multifactorauth/models/two_factor_code_request_schema.py | Bandwidth/python-sdk | train | 10 |
9925506ab95035bcea21340f1e9e8e1c86d3fb95 | [
"self.count_of_processed = 0\nself.queueHandler = AsyncQueues.AsyncServerQueueDropin() if queueHandler is None else queueHandler\nself.processor = Processor() if processor is None else processor\nsuper().__init__()",
"if environment.SLACK_NOTIFY:\n slack_heartbeat(self.count_of_processed)\nif self.limit is not... | <|body_start_0|>
self.count_of_processed = 0
self.queueHandler = AsyncQueues.AsyncServerQueueDropin() if queueHandler is None else queueHandler
self.processor = Processor() if processor is None else processor
super().__init__()
<|end_body_0|>
<|body_start_1|>
if environment.SLAC... | Control | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Control:
def __init__(self, queueHandler=None, processor=None):
""":type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck"""
<|body_0|>
def is_over_limit(self):
"""Check if we are over limit. Issues StopIteration si... | stack_v2_sparse_classes_36k_train_017754 | 3,119 | permissive | [
{
"docstring": ":type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck",
"name": "__init__",
"signature": "def __init__(self, queueHandler=None, processor=None)"
},
{
"docstring": "Check if we are over limit. Issues StopIteration since this won... | 4 | stack_v2_sparse_classes_30k_train_014198 | Implement the Python class `Control` described below.
Class description:
Implement the Control class.
Method signatures and docstrings:
- def __init__(self, queueHandler=None, processor=None): :type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck
- def is_over_limi... | Implement the Python class `Control` described below.
Class description:
Implement the Control class.
Method signatures and docstrings:
- def __init__(self, queueHandler=None, processor=None): :type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck
- def is_over_limi... | 8c5dc7a57eac611b555058736d609f2f204cb836 | <|skeleton|>
class Control:
def __init__(self, queueHandler=None, processor=None):
""":type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck"""
<|body_0|>
def is_over_limit(self):
"""Check if we are over limit. Issues StopIteration si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Control:
def __init__(self, queueHandler=None, processor=None):
""":type queueHandler: Service class which puts the word in the queue to be saved, so that's not a bottleneck"""
self.count_of_processed = 0
self.queueHandler = AsyncQueues.AsyncServerQueueDropin() if queueHandler is None ... | the_stack_v2_python_sparse | DataAnalysis/ProcessingTools/Controllers/AsyncControl.py | AdamSwenson/TwitterProject | train | 0 | |
8b973bec3947f7f40e9933976e9dceade79e22ef | [
"data = request.data.copy()\ndata['user'] = request.user.id\nadd_accept = bool(request.data.get('add_accept', False))\nfood = FoodRecipe.objects.get(pk=data['foodrecipe'])\nif add_accept != True:\n warning = FoodRecipeService.check_healthy(food, request.user)\n if warning:\n return Response({'warning':... | <|body_start_0|>
data = request.data.copy()
data['user'] = request.user.id
add_accept = bool(request.data.get('add_accept', False))
food = FoodRecipe.objects.get(pk=data['foodrecipe'])
if add_accept != True:
warning = FoodRecipeService.check_healthy(food, request.user... | CartViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartViewSet:
def create(self, request, *args, **kwargs):
"""@apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android... | stack_v2_sparse_classes_36k_train_017755 | 5,351 | no_license | [
{
"docstring": "@apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IOS tablet, 7: Mobile web, tablet web, 8: Desktop web) @... | 2 | stack_v2_sparse_classes_30k_train_019424 | Implement the Python class `CartViewSet` described below.
Class description:
Implement the CartViewSet class.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): @apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHead... | Implement the Python class `CartViewSet` described below.
Class description:
Implement the CartViewSet class.
Method signatures and docstrings:
- def create(self, request, *args, **kwargs): @apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHead... | b5c5bd25fb05965621615d09439bf79fa1b8d5e8 | <|skeleton|>
class CartViewSet:
def create(self, request, *args, **kwargs):
"""@apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartViewSet:
def create(self, request, *args, **kwargs):
"""@apiVersion 1.0.0 @api {POST} /cart create food recipe for cart @apiName Cart @apiGroup FoodRecipes @apiPermission User @apiHeader {number} Type Device type (1: Mobile, 2: Android phone, 3: IOS phone, 4: Window phone, 5: Android tablet, 6: IO... | the_stack_v2_python_sparse | src/kitchenrock_api/views/api/cart.py | thqbop/kitchenrock | train | 0 | |
aa9f874d91f387fdb9d6a3cf81577ba7a367c620 | [
"assert isinstance(mc, ModelConfiguration)\nconf = mc.get('conf')\nself.conf = conf\nself.env = mc['env']\nself.filter_states = conf['states']\nself.filter_rewards = conf['rewards']",
"with torch.no_grad():\n if self.filter_states:\n if 'unfiltered_states' not in trajectory:\n trajectory['unf... | <|body_start_0|>
assert isinstance(mc, ModelConfiguration)
conf = mc.get('conf')
self.conf = conf
self.env = mc['env']
self.filter_states = conf['states']
self.filter_rewards = conf['rewards']
<|end_body_0|>
<|body_start_1|>
with torch.no_grad():
if s... | Represents a simple filter operator using the integrated filter from the environment. | FilterOperator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterOperator:
"""Represents a simple filter operator using the integrated filter from the environment."""
def __init__(self, mc):
"""Initializes a new filter operator :param mc: The model configuration to use."""
<|body_0|>
def transform(self, trajectory):
"""T... | stack_v2_sparse_classes_36k_train_017756 | 1,595 | permissive | [
{
"docstring": "Initializes a new filter operator :param mc: The model configuration to use.",
"name": "__init__",
"signature": "def __init__(self, mc)"
},
{
"docstring": "Transform a trajectory with the current instance of the evaluation operator. :param trajectory: trajectory to transform.",
... | 2 | stack_v2_sparse_classes_30k_train_008261 | Implement the Python class `FilterOperator` described below.
Class description:
Represents a simple filter operator using the integrated filter from the environment.
Method signatures and docstrings:
- def __init__(self, mc): Initializes a new filter operator :param mc: The model configuration to use.
- def transform... | Implement the Python class `FilterOperator` described below.
Class description:
Represents a simple filter operator using the integrated filter from the environment.
Method signatures and docstrings:
- def __init__(self, mc): Initializes a new filter operator :param mc: The model configuration to use.
- def transform... | 13038a1a5a93c78374ba869c9e75221c2b73d290 | <|skeleton|>
class FilterOperator:
"""Represents a simple filter operator using the integrated filter from the environment."""
def __init__(self, mc):
"""Initializes a new filter operator :param mc: The model configuration to use."""
<|body_0|>
def transform(self, trajectory):
"""T... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterOperator:
"""Represents a simple filter operator using the integrated filter from the environment."""
def __init__(self, mc):
"""Initializes a new filter operator :param mc: The model configuration to use."""
assert isinstance(mc, ModelConfiguration)
conf = mc.get('conf')
... | the_stack_v2_python_sparse | src/abstract_rl/operator/filter_operator.py | kosmitive/abstract_rl | train | 2 |
3ac28933a25890697c8d82a3083e285620e3a959 | [
"from collections import deque\nif not root:\n return True\nlevel = [root.left, root.right]\nwhile any(level):\n next_level = deque()\n i, j = (0, len(level) - 1)\n while i < j:\n if level[i] and level[j]:\n if level[i].val != level[j].val:\n return False\n el... | <|body_start_0|>
from collections import deque
if not root:
return True
level = [root.left, root.right]
while any(level):
next_level = deque()
i, j = (0, len(level) - 1)
while i < j:
if level[i] and level[j]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric_1(self, root: TreeNode) -> bool:
"""层序遍历,每层的值列表应该对称"""
<|body_0|>
def isSymmetric(self, root: TreeNode) -> bool:
"""问题转换成两棵树是否为镜像"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from collections import deque
if not ... | stack_v2_sparse_classes_36k_train_017757 | 2,863 | no_license | [
{
"docstring": "层序遍历,每层的值列表应该对称",
"name": "isSymmetric_1",
"signature": "def isSymmetric_1(self, root: TreeNode) -> bool"
},
{
"docstring": "问题转换成两棵树是否为镜像",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root: TreeNode) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_001603 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric_1(self, root: TreeNode) -> bool: 层序遍历,每层的值列表应该对称
- def isSymmetric(self, root: TreeNode) -> bool: 问题转换成两棵树是否为镜像 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric_1(self, root: TreeNode) -> bool: 层序遍历,每层的值列表应该对称
- def isSymmetric(self, root: TreeNode) -> bool: 问题转换成两棵树是否为镜像
<|skeleton|>
class Solution:
def isSymmetric... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def isSymmetric_1(self, root: TreeNode) -> bool:
"""层序遍历,每层的值列表应该对称"""
<|body_0|>
def isSymmetric(self, root: TreeNode) -> bool:
"""问题转换成两棵树是否为镜像"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric_1(self, root: TreeNode) -> bool:
"""层序遍历,每层的值列表应该对称"""
from collections import deque
if not root:
return True
level = [root.left, root.right]
while any(level):
next_level = deque()
i, j = (0, len(level) - 1)
... | the_stack_v2_python_sparse | .leetcode/101.对称二叉树.py | xiaoruijiang/algorithm | train | 0 | |
5ab76e85008c3b12d55efd6e87e7d61bd71e994b | [
"response = await session.request(method='GET', url=url)\njson_dict = await response.json()\nreturn json_dict",
"try:\n url = 'https://pokeapi.co/api/v2/'\n if request.mode == Mode.POKEMON:\n mode = 'pokemon/'\n elif request.mode == Mode.MOVE:\n mode = 'move/'\n elif request.mode == Mode... | <|body_start_0|>
response = await session.request(method='GET', url=url)
json_dict = await response.json()
return json_dict
<|end_body_0|>
<|body_start_1|>
try:
url = 'https://pokeapi.co/api/v2/'
if request.mode == Mode.POKEMON:
mode = 'pokemon/'
... | This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object | Handler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object"""
async def get_request_data_with_url(session: ClientSession, url: str) -> dict:
"""Gets data dict with provided url. :param url: url of api :param... | stack_v2_sparse_classes_36k_train_017758 | 4,475 | no_license | [
{
"docstring": "Gets data dict with provided url. :param url: url of api :param session ClientSession :return api response dict from json",
"name": "get_request_data_with_url",
"signature": "async def get_request_data_with_url(session: ClientSession, url: str) -> dict"
},
{
"docstring": "An asyn... | 6 | null | Implement the Python class `Handler` described below.
Class description:
This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object
Method signatures and docstrings:
- async def get_request_data_with_url(session: ClientSession, url: str) -> dict: Gets d... | Implement the Python class `Handler` described below.
Class description:
This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object
Method signatures and docstrings:
- async def get_request_data_with_url(session: ClientSession, url: str) -> dict: Gets d... | c1736d33d0535502c65de86affe1c4ea151c09cb | <|skeleton|>
class Handler:
"""This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object"""
async def get_request_data_with_url(session: ClientSession, url: str) -> dict:
"""Gets data dict with provided url. :param url: url of api :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Handler:
"""This class is for: - Create an aiohttp session and execute requests - Parse the JSON and instantiate the appropriate object"""
async def get_request_data_with_url(session: ClientSession, url: str) -> dict:
"""Gets data dict with provided url. :param url: url of api :param session Clie... | the_stack_v2_python_sparse | Assignments/Assignment3/pokeretriever/handler.py | Bmeimei/3532_A01075487 | train | 1 |
ab5388bafe4cf4118042c3fd2f85c331dc3d9d1d | [
"self.il_co = imu_lidar_coefficient\nself.odo_co = odometry_coefficient\nself.vo_co = vo_coefficient\nself.normalise_coefficionets()",
"sum = self.il_co + self.odo_co + self.vo_co\nself.il_co /= sum\nself.odo_co /= sum\nself.vo_co /= sum",
"x = self.il_co * il_data[0] + self.odo_co * odo_data[0] + self.vo_co * ... | <|body_start_0|>
self.il_co = imu_lidar_coefficient
self.odo_co = odometry_coefficient
self.vo_co = vo_coefficient
self.normalise_coefficionets()
<|end_body_0|>
<|body_start_1|>
sum = self.il_co + self.odo_co + self.vo_co
self.il_co /= sum
self.odo_co /= sum
... | ComplementaryFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplementaryFilter:
def __init__(self, imu_lidar_coefficient=0.02, odometry_coefficient=0.96, vo_coefficient=0.02):
"""Filter for trajectory data FUSION :param imu_lidar_coefficient: importance of data from this source :param dcam_lidar_coefficient: importance of data from this source :... | stack_v2_sparse_classes_36k_train_017759 | 1,435 | permissive | [
{
"docstring": "Filter for trajectory data FUSION :param imu_lidar_coefficient: importance of data from this source :param dcam_lidar_coefficient: importance of data from this source :param vo_coefficient: importance of data from this source",
"name": "__init__",
"signature": "def __init__(self, imu_lid... | 3 | stack_v2_sparse_classes_30k_test_000726 | Implement the Python class `ComplementaryFilter` described below.
Class description:
Implement the ComplementaryFilter class.
Method signatures and docstrings:
- def __init__(self, imu_lidar_coefficient=0.02, odometry_coefficient=0.96, vo_coefficient=0.02): Filter for trajectory data FUSION :param imu_lidar_coefficie... | Implement the Python class `ComplementaryFilter` described below.
Class description:
Implement the ComplementaryFilter class.
Method signatures and docstrings:
- def __init__(self, imu_lidar_coefficient=0.02, odometry_coefficient=0.96, vo_coefficient=0.02): Filter for trajectory data FUSION :param imu_lidar_coefficie... | 7115f55799d9a81fdb214e20c4cdd8520dceb48e | <|skeleton|>
class ComplementaryFilter:
def __init__(self, imu_lidar_coefficient=0.02, odometry_coefficient=0.96, vo_coefficient=0.02):
"""Filter for trajectory data FUSION :param imu_lidar_coefficient: importance of data from this source :param dcam_lidar_coefficient: importance of data from this source :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ComplementaryFilter:
def __init__(self, imu_lidar_coefficient=0.02, odometry_coefficient=0.96, vo_coefficient=0.02):
"""Filter for trajectory data FUSION :param imu_lidar_coefficient: importance of data from this source :param dcam_lidar_coefficient: importance of data from this source :param vo_coeff... | the_stack_v2_python_sparse | MORSEProject/classes/ComplementaryFilter.py | Kecz/MORSE-SLAM | train | 2 | |
013b6165b9870fd51b03f42109baa36b9e875e62 | [
"result = [0]\n\ndef find(nums, i, MIN, MAX, target):\n if i >= len(nums):\n return\n if min(MIN, nums[i]) + max(MAX, nums[i]) <= target:\n result[0] += 1\n find(nums, i + 1, min(MIN, nums[i]), max(MAX, nums[i]), target)\n find(nums, i + 1, MIN, MAX, target)\nMIN = target\nMAX = 0\nfind(nu... | <|body_start_0|>
result = [0]
def find(nums, i, MIN, MAX, target):
if i >= len(nums):
return
if min(MIN, nums[i]) + max(MAX, nums[i]) <= target:
result[0] += 1
find(nums, i + 1, min(MIN, nums[i]), max(MAX, nums[i]), target)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubseq(self, nums, target):
"""递归 :type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def numSubseq2(self, nums, target):
"""排序+递归+记忆化"""
<|body_1|>
def numSubseq3(self, nums, target):
"""排序+双指针"""
<|body_2|... | stack_v2_sparse_classes_36k_train_017760 | 2,560 | no_license | [
{
"docstring": "递归 :type nums: List[int] :type target: int :rtype: int",
"name": "numSubseq",
"signature": "def numSubseq(self, nums, target)"
},
{
"docstring": "排序+递归+记忆化",
"name": "numSubseq2",
"signature": "def numSubseq2(self, nums, target)"
},
{
"docstring": "排序+双指针",
"n... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubseq(self, nums, target): 递归 :type nums: List[int] :type target: int :rtype: int
- def numSubseq2(self, nums, target): 排序+递归+记忆化
- def numSubseq3(self, nums, target): 排序... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubseq(self, nums, target): 递归 :type nums: List[int] :type target: int :rtype: int
- def numSubseq2(self, nums, target): 排序+递归+记忆化
- def numSubseq3(self, nums, target): 排序... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def numSubseq(self, nums, target):
"""递归 :type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def numSubseq2(self, nums, target):
"""排序+递归+记忆化"""
<|body_1|>
def numSubseq3(self, nums, target):
"""排序+双指针"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubseq(self, nums, target):
"""递归 :type nums: List[int] :type target: int :rtype: int"""
result = [0]
def find(nums, i, MIN, MAX, target):
if i >= len(nums):
return
if min(MIN, nums[i]) + max(MAX, nums[i]) <= target:
... | the_stack_v2_python_sparse | 竞赛/195场/满足条件的子序列数目_M.py | 2226171237/Algorithmpractice | train | 0 | |
dce9bab653d331efdb7f3babd0564a446a3255c7 | [
"super().__init__(capacity)\nself.n_steps = n_steps\nself.gamma = gamma\nself.history = deque(maxlen=self.n_steps)\nself.exp_history_queue = deque()",
"self.update_history_queue(exp)\nwhile self.exp_history_queue:\n experiences = self.exp_history_queue.popleft()\n last_exp_state, tail_experiences = self.spl... | <|body_start_0|>
super().__init__(capacity)
self.n_steps = n_steps
self.gamma = gamma
self.history = deque(maxlen=self.n_steps)
self.exp_history_queue = deque()
<|end_body_0|>
<|body_start_1|>
self.update_history_queue(exp)
while self.exp_history_queue:
... | N Step Replay Buffer. | MultiStepBuffer | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiStepBuffer:
"""N Step Replay Buffer."""
def __init__(self, capacity: int, n_steps: int=1, gamma: float=0.99) -> None:
"""Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps used for calculating discounted reward/experience gamma: ... | stack_v2_sparse_classes_36k_train_017761 | 10,953 | permissive | [
{
"docstring": "Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps used for calculating discounted reward/experience gamma: discount factor when calculating n_step discounted reward of the experience being stored in buffer",
"name": "__init__",
"signatur... | 5 | null | Implement the Python class `MultiStepBuffer` described below.
Class description:
N Step Replay Buffer.
Method signatures and docstrings:
- def __init__(self, capacity: int, n_steps: int=1, gamma: float=0.99) -> None: Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps ... | Implement the Python class `MultiStepBuffer` described below.
Class description:
N Step Replay Buffer.
Method signatures and docstrings:
- def __init__(self, capacity: int, n_steps: int=1, gamma: float=0.99) -> None: Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps ... | bdf311369b236c1e3d0336c7ed4ba249854f8606 | <|skeleton|>
class MultiStepBuffer:
"""N Step Replay Buffer."""
def __init__(self, capacity: int, n_steps: int=1, gamma: float=0.99) -> None:
"""Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps used for calculating discounted reward/experience gamma: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiStepBuffer:
"""N Step Replay Buffer."""
def __init__(self, capacity: int, n_steps: int=1, gamma: float=0.99) -> None:
"""Args: capacity: max number of experiences that will be stored in the buffer n_steps: number of steps used for calculating discounted reward/experience gamma: discount fact... | the_stack_v2_python_sparse | src/pl_bolts/models/rl/common/memory.py | Lightning-Universe/lightning-bolts | train | 76 |
5af3f90962a0bd9f925ea7b2a3cc00b162e0f378 | [
"require_version('spacy>=3.5.3')\nrequire_version('spacy-transformers')\nself.update_transformer = update_transformer\nsuper().__init__(**kwargs)",
"from spacy.cli.init_config import init_config\nself.config = init_config(lang=self.language, pipeline=self._pipeline, optimize=self.optimize, gpu=True)\nself.config[... | <|body_start_0|>
require_version('spacy>=3.5.3')
require_version('spacy-transformers')
self.update_transformer = update_transformer
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
from spacy.cli.init_config import init_config
self.config = init_config(lang=sel... | ArgillaSpaCyTransformersTrainer | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgillaSpaCyTransformersTrainer:
def __init__(self, update_transformer: bool=True, **kwargs) -> None:
"""Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: update_transformer: A `bool` indicating whether to update the transformer weights during the training. Defaults to True. ... | stack_v2_sparse_classes_36k_train_017762 | 16,356 | permissive | [
{
"docstring": "Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: update_transformer: A `bool` indicating whether to update the transformer weights during the training. Defaults to True. **kwargs: The `ArgillaSpaCyTrainerBase` arguments.",
"name": "__init__",
"signature": "def __init__(self,... | 2 | stack_v2_sparse_classes_30k_train_007955 | Implement the Python class `ArgillaSpaCyTransformersTrainer` described below.
Class description:
Implement the ArgillaSpaCyTransformersTrainer class.
Method signatures and docstrings:
- def __init__(self, update_transformer: bool=True, **kwargs) -> None: Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: u... | Implement the Python class `ArgillaSpaCyTransformersTrainer` described below.
Class description:
Implement the ArgillaSpaCyTransformersTrainer class.
Method signatures and docstrings:
- def __init__(self, update_transformer: bool=True, **kwargs) -> None: Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: u... | 7c1b2368b444b7b7a281d37ad51bcb2d8e92acf5 | <|skeleton|>
class ArgillaSpaCyTransformersTrainer:
def __init__(self, update_transformer: bool=True, **kwargs) -> None:
"""Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: update_transformer: A `bool` indicating whether to update the transformer weights during the training. Defaults to True. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArgillaSpaCyTransformersTrainer:
def __init__(self, update_transformer: bool=True, **kwargs) -> None:
"""Initialize the `ArgillaSpaCyTransformersTrainer` class. Args: update_transformer: A `bool` indicating whether to update the transformer weights during the training. Defaults to True. **kwargs: The ... | the_stack_v2_python_sparse | src/argilla/training/spacy.py | argilla-io/argilla | train | 1,085 | |
529935f211eb3aa73a984785b5b312837159ac2a | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('CancelTask', params, headers=headers)\n response = json.loads(body)\n model = models.CancelTaskResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if isinstance(e,... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('CancelTask', params, headers=headers)
response = json.loads(body)
model = models.CancelTaskResponse()
model._deserialize(response['Response'])
... | AmsClient | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmsClient:
def CancelTask(self, request):
"""This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate limit: **20 requests/sec**. :param request: Request instance for CancelTask. :type request: :class:`t... | stack_v2_sparse_classes_36k_train_017763 | 7,623 | no_license | [
{
"docstring": "This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate limit: **20 requests/sec**. :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.ams.v20201229.models.CancelTaskRequest` :... | 4 | null | Implement the Python class `AmsClient` described below.
Class description:
Implement the AmsClient class.
Method signatures and docstrings:
- def CancelTask(self, request): This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate lim... | Implement the Python class `AmsClient` described below.
Class description:
Implement the AmsClient class.
Method signatures and docstrings:
- def CancelTask(self, request): This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate lim... | 042b4d7fb609d4d240728197901b46008b35d4b0 | <|skeleton|>
class AmsClient:
def CancelTask(self, request):
"""This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate limit: **20 requests/sec**. :param request: Request instance for CancelTask. :type request: :class:`t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmsClient:
def CancelTask(self, request):
"""This API is used to cancel a moderation task. If it returns `RequestId`, the task has been canceled successfully.<br>Default API request rate limit: **20 requests/sec**. :param request: Request instance for CancelTask. :type request: :class:`tencentcloud.am... | the_stack_v2_python_sparse | tencentcloud/ams/v20201229/ams_client.py | TencentCloud/tencentcloud-sdk-python-intl-en | train | 4 | |
9cbf39ce399de6fa40b2ca1408bde875c2e80a08 | [
"self.device = device\nself.alpha = alpha\nself.model = model.to(self.device)\nself.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad}\nself._means = {}\nself._precision_matrices = {}\nfor n, p in deepcopy(self.params).items():\n p.data.zero_()\n self._precision_matrices[n] = p.data.... | <|body_start_0|>
self.device = device
self.alpha = alpha
self.model = model.to(self.device)
self.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad}
self._means = {}
self._precision_matrices = {}
for n, p in deepcopy(self.params).items():
... | OnlineEWC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OnlineEWC:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5):
"""OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (string): the device to run the model on alpha (in [0,1) ): The online learning hyper-parameter"""
... | stack_v2_sparse_classes_36k_train_017764 | 3,611 | no_license | [
{
"docstring": "OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (string): the device to run the model on alpha (in [0,1) ): The online learning hyper-parameter",
"name": "__init__",
"signature": "def __init__(self, model: nn.Module, device='cuda:0... | 3 | stack_v2_sparse_classes_30k_train_011572 | Implement the Python class `OnlineEWC` described below.
Class description:
Implement the OnlineEWC class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5): OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (stri... | Implement the Python class `OnlineEWC` described below.
Class description:
Implement the OnlineEWC class.
Method signatures and docstrings:
- def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5): OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (stri... | f1f9e9f4f85c7eb076e3c15e2390c9d612adabdf | <|skeleton|>
class OnlineEWC:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5):
"""OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (string): the device to run the model on alpha (in [0,1) ): The online learning hyper-parameter"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OnlineEWC:
def __init__(self, model: nn.Module, device='cuda:0', alpha=0.5):
"""OnlineEWC is the class for implementing the online EWC method. Inputs: model : a Pytorch NN model device (string): the device to run the model on alpha (in [0,1) ): The online learning hyper-parameter"""
self.devic... | the_stack_v2_python_sparse | utils/ewc_utils/onlineEWC.py | lihr04/corel2m | train | 0 | |
056225fae8253466fcbe8820d96d20941a6e3aa0 | [
"super().__init__(hass=hass, logger=_LOGGER, name=NAME, update_interval=INTERVAL_SLOW)\nself.device = device\nself.unique_id = format_mac(device.mac)",
"try:\n state = await self.device.get_state()\nexcept JvcProjectorConnectError as err:\n raise UpdateFailed(f'Unable to connect to {self.device.host}') from... | <|body_start_0|>
super().__init__(hass=hass, logger=_LOGGER, name=NAME, update_interval=INTERVAL_SLOW)
self.device = device
self.unique_id = format_mac(device.mac)
<|end_body_0|>
<|body_start_1|>
try:
state = await self.device.get_state()
except JvcProjectorConnectEr... | Data update coordinator for the JVC Projector integration. | JvcProjectorDataUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JvcProjectorDataUpdateCoordinator:
"""Data update coordinator for the JVC Projector integration."""
def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None:
"""Initialize the coordinator."""
<|body_0|>
async def _async_update_data(self) -> dict[str, str]:
... | stack_v2_sparse_classes_36k_train_017765 | 1,941 | permissive | [
{
"docstring": "Initialize the coordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None"
},
{
"docstring": "Get the latest state data.",
"name": "_async_update_data",
"signature": "async def _async_update_data(self) -> dict[st... | 2 | stack_v2_sparse_classes_30k_train_012753 | Implement the Python class `JvcProjectorDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the JVC Projector integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None: Initialize the coordinator.
- async def _async_update... | Implement the Python class `JvcProjectorDataUpdateCoordinator` described below.
Class description:
Data update coordinator for the JVC Projector integration.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None: Initialize the coordinator.
- async def _async_update... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class JvcProjectorDataUpdateCoordinator:
"""Data update coordinator for the JVC Projector integration."""
def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None:
"""Initialize the coordinator."""
<|body_0|>
async def _async_update_data(self) -> dict[str, str]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JvcProjectorDataUpdateCoordinator:
"""Data update coordinator for the JVC Projector integration."""
def __init__(self, hass: HomeAssistant, device: JvcProjector) -> None:
"""Initialize the coordinator."""
super().__init__(hass=hass, logger=_LOGGER, name=NAME, update_interval=INTERVAL_SLOW... | the_stack_v2_python_sparse | homeassistant/components/jvc_projector/coordinator.py | home-assistant/core | train | 35,501 |
7c6e8b23f0a5942c17e27522ebf808b0310ca1fa | [
"allure.dynamic.title('Testing length function where head = None')\nallure.dynamic.severity(allure.severity_level.NORMAL)\nallure.dynamic.description_html('<h3>Codewars badge:</h3><img src=\"https://www.codewars.com/users/myFirstCode/badges/large\"><h3>Test Description:</h3><p></p>')\nwith allure.step('Enter test n... | <|body_start_0|>
allure.dynamic.title('Testing length function where head = None')
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.description_html('<h3>Codewars badge:</h3><img src="https://www.codewars.com/users/myFirstCode/badges/large"><h3>Test Description:</h3><p></p>')... | Testing length function | LengthTestCase | [
"Unlicense",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LengthTestCase:
"""Testing length function"""
def test_length_none(self):
"""Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:"""
<|body_0|>
def test_length(self):
"""Test... | stack_v2_sparse_classes_36k_train_017766 | 2,506 | permissive | [
{
"docstring": "Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:",
"name": "test_length_none",
"signature": "def test_length_none(self)"
},
{
"docstring": "Testing length function The method length, whic... | 2 | null | Implement the Python class `LengthTestCase` described below.
Class description:
Testing length function
Method signatures and docstrings:
- def test_length_none(self): Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:
- def te... | Implement the Python class `LengthTestCase` described below.
Class description:
Testing length function
Method signatures and docstrings:
- def test_length_none(self): Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:
- def te... | ba3ea81125b6082d867f0ae34c6c9be15e153966 | <|skeleton|>
class LengthTestCase:
"""Testing length function"""
def test_length_none(self):
"""Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:"""
<|body_0|>
def test_length(self):
"""Test... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LengthTestCase:
"""Testing length function"""
def test_length_none(self):
"""Testing length function where head = None The method length, which accepts a linked list (head), and returns the length of the list. :return:"""
allure.dynamic.title('Testing length function where head = None')
... | the_stack_v2_python_sparse | kyu_7/fun_with_lists_length/test_length.py | qamine-test/codewars | train | 0 |
acf82c9c0e0dc7bfe950ad459fca57ad56f83f24 | [
"path = '/'.join([self.SCOPE_BASEURL, account, 'scopes', quote_plus(scope)])\nurl = build_url(choice(self.list_hosts), path=path)\nr = self._send_request(url, type_='POST')\nif r.status_code == codes.created:\n return True\nelse:\n exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status... | <|body_start_0|>
path = '/'.join([self.SCOPE_BASEURL, account, 'scopes', quote_plus(scope)])
url = build_url(choice(self.list_hosts), path=path)
r = self._send_request(url, type_='POST')
if r.status_code == codes.created:
return True
else:
exc_cls, exc_msg... | Scope client class for working with rucio scopes | ScopeClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created s... | stack_v2_sparse_classes_36k_train_017767 | 3,206 | permissive | [
{
"docstring": "Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created successfully. :raises Duplicate: if scope already exists. :raises AccountNotFound: if account doesn't exist.",
"name"... | 3 | stack_v2_sparse_classes_30k_train_004781 | Implement the Python class `ScopeClient` described below.
Class description:
Scope client class for working with rucio scopes
Method signatures and docstrings:
- def add_scope(self, account, scope): Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the na... | Implement the Python class `ScopeClient` described below.
Class description:
Scope client class for working with rucio scopes
Method signatures and docstrings:
- def add_scope(self, account, scope): Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the na... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScopeClient:
"""Scope client class for working with rucio scopes"""
def add_scope(self, account, scope):
"""Sends the request to add a new scope. :param account: the name of the account to add the scope to. :param scope: the name of the new scope. :return: True if scope was created successfully. ... | the_stack_v2_python_sparse | lib/rucio/client/scopeclient.py | rucio/rucio | train | 232 |
a9c3ba960690756f88d22e81291e4d283be26e16 | [
"self.counter = 0\nself.lr = lr\nself.b1 = b1\nself.b2 = b2\nself.num_params = num_params\nself.momentum = [0 for _ in range(num_params)]\nself.velocity = [0 for _ in range(num_params)]",
"new_params = []\nself.counter += 1\nfor i in range(self.num_params):\n self.momentum[i] = self.b1 * self.momentum[i] + (1 ... | <|body_start_0|>
self.counter = 0
self.lr = lr
self.b1 = b1
self.b2 = b2
self.num_params = num_params
self.momentum = [0 for _ in range(num_params)]
self.velocity = [0 for _ in range(num_params)]
<|end_body_0|>
<|body_start_1|>
new_params = []
sel... | Adam | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adam:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.999):
"""Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The expon... | stack_v2_sparse_classes_36k_train_017768 | 10,861 | no_license | [
{
"docstring": "Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential decay rate for the first moment(integer/float), default is 0.9 b2 : The ... | 2 | stack_v2_sparse_classes_30k_train_006604 | Implement the Python class `Adam` described below.
Class description:
Implement the Adam class.
Method signatures and docstrings:
- def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.999): Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate w... | Implement the Python class `Adam` described below.
Class description:
Implement the Adam class.
Method signatures and docstrings:
- def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.999): Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate w... | 9406b21aef9b2d94091d570e809f88a752277e30 | <|skeleton|>
class Adam:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.999):
"""Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The expon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adam:
def __init__(self, num_params, lr=0.00146, b1=0.9, b2=0.999):
"""Initializer for Adam optimizer inputs: num params: number of parameters which are ought to be passed lr: The learning rate with which the gradient step should be taken(integer/float), default is 0.00146 b1 : The exponential decay r... | the_stack_v2_python_sparse | optimizers.py | viswambhar-yasa/AuToDiFf | train | 0 | |
c278e7c0dc287ce0e2acbc6cdd3e8cbf04cd52f3 | [
"if self.result is utils.MISSING:\n raise exc.FutureResultNotSet(self)\nreturn self.result",
"if self.result is not utils.MISSING and (not overwrite):\n raise exc.FutureResultAlreadySet(self)\nself.__dict__['result'] = result"
] | <|body_start_0|>
if self.result is utils.MISSING:
raise exc.FutureResultNotSet(self)
return self.result
<|end_body_0|>
<|body_start_1|>
if self.result is not utils.MISSING and (not overwrite):
raise exc.FutureResultAlreadySet(self)
self.__dict__['result'] = resul... | Helper so that we can clone futures while still retaining their behavior. | FutureResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FutureResult:
"""Helper so that we can clone futures while still retaining their behavior."""
def get(self) -> Any:
"""Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet"""
<|body_0|>
def set(self, result: Any, overwrite: bool=False) -... | stack_v2_sparse_classes_36k_train_017769 | 20,564 | permissive | [
{
"docstring": "Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet",
"name": "get",
"signature": "def get(self) -> Any"
},
{
"docstring": "Set the result, raising exc.FutureResultAlreadySet if it has already been set",
"name": "set",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_val_000310 | Implement the Python class `FutureResult` described below.
Class description:
Helper so that we can clone futures while still retaining their behavior.
Method signatures and docstrings:
- def get(self) -> Any: Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet
- def set(self, resul... | Implement the Python class `FutureResult` described below.
Class description:
Helper so that we can clone futures while still retaining their behavior.
Method signatures and docstrings:
- def get(self) -> Any: Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet
- def set(self, resul... | 6d127ed48265e2e072fbb26486458a4b28a333ec | <|skeleton|>
class FutureResult:
"""Helper so that we can clone futures while still retaining their behavior."""
def get(self) -> Any:
"""Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet"""
<|body_0|>
def set(self, result: Any, overwrite: bool=False) -... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FutureResult:
"""Helper so that we can clone futures while still retaining their behavior."""
def get(self) -> Any:
"""Get the result of the future, raising exc.FutureResultNotSet if it hasn't been set yet"""
if self.result is utils.MISSING:
raise exc.FutureResultNotSet(self)
... | the_stack_v2_python_sparse | statey/syms/impl.py | cfeenstra67/statey | train | 8 |
dc12b70e917bb37106704c6059efc1f325368d92 | [
"self.items = sorted(items) if items else []\nself.sorted = False\nself.sorting_parameters = sorting_parameters",
"if not newitem in self.items:\n self.items.append(newitem)\n self.sorted = False",
"if not self.sorted:\n self.items.sort(**self.sorting_parameters)\n self.sorted = True"
] | <|body_start_0|>
self.items = sorted(items) if items else []
self.sorted = False
self.sorting_parameters = sorting_parameters
<|end_body_0|>
<|body_start_1|>
if not newitem in self.items:
self.items.append(newitem)
self.sorted = False
<|end_body_1|>
<|body_start... | Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique. | OrderedSet | [
"BSD-3-Clause",
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderedSet:
"""Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique."""
def __init__(self, items=None, **sorting_parameters):
"""Initialize the set with a ... | stack_v2_sparse_classes_36k_train_017770 | 1,239 | permissive | [
{
"docstring": "Initialize the set with a list of items, or not at all. They will be sorted automatically. items = list of initial items sorting_parameters = keyword arguments which will be passed to sort",
"name": "__init__",
"signature": "def __init__(self, items=None, **sorting_parameters)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_009013 | Implement the Python class `OrderedSet` described below.
Class description:
Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique.
Method signatures and docstrings:
- def __init__(self, item... | Implement the Python class `OrderedSet` described below.
Class description:
Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique.
Method signatures and docstrings:
- def __init__(self, item... | 9a85b997ddf0a3d7c50ab109cb3b91e71743c7a3 | <|skeleton|>
class OrderedSet:
"""Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique."""
def __init__(self, items=None, **sorting_parameters):
"""Initialize the set with a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrderedSet:
"""Loose Python equivalent of std::set. makes sure list is sorted when it is accessed (searched, iterated over, etc.), but not until then. Basically, sort lazily. Items are also unique."""
def __init__(self, items=None, **sorting_parameters):
"""Initialize the set with a list of items... | the_stack_v2_python_sparse | mobile/pcap2har/orderedset.py | jpvincent/WPT-server | train | 17 |
183329baeb369ba0f99e78ef9ab0f19a40cd78b9 | [
"super(VideoCaptureView, self).__init__(parent)\nself.pixmap = None\nself.item = None\nself.capture = cv2.VideoCapture(0)\nif self.capture.isOpened() is False:\n raise IOError('failed in opening VideoCapture')\nself.scene = QGraphicsScene()\nself.setScene(self.scene)\nself.setVideoImage()\nself.timer = QTimer(se... | <|body_start_0|>
super(VideoCaptureView, self).__init__(parent)
self.pixmap = None
self.item = None
self.capture = cv2.VideoCapture(0)
if self.capture.isOpened() is False:
raise IOError('failed in opening VideoCapture')
self.scene = QGraphicsScene()
se... | ビデオキャプチャ | VideoCaptureView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VideoCaptureView:
"""ビデオキャプチャ"""
def __init__(self, parent=None):
"""コンストラクタ(インスタンスが生成される時に呼び出される)"""
<|body_0|>
def setVideoImage(self):
"""ビデオの画像を取得して表示"""
<|body_1|>
def processing(self, src):
"""画像処理"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_017771 | 3,223 | no_license | [
{
"docstring": "コンストラクタ(インスタンスが生成される時に呼び出される)",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "ビデオの画像を取得して表示",
"name": "setVideoImage",
"signature": "def setVideoImage(self)"
},
{
"docstring": "画像処理",
"name": "processing",
"signature... | 3 | stack_v2_sparse_classes_30k_train_017002 | Implement the Python class `VideoCaptureView` described below.
Class description:
ビデオキャプチャ
Method signatures and docstrings:
- def __init__(self, parent=None): コンストラクタ(インスタンスが生成される時に呼び出される)
- def setVideoImage(self): ビデオの画像を取得して表示
- def processing(self, src): 画像処理 | Implement the Python class `VideoCaptureView` described below.
Class description:
ビデオキャプチャ
Method signatures and docstrings:
- def __init__(self, parent=None): コンストラクタ(インスタンスが生成される時に呼び出される)
- def setVideoImage(self): ビデオの画像を取得して表示
- def processing(self, src): 画像処理
<|skeleton|>
class VideoCaptureView:
"""ビデオキャプチャ... | fc76c7f29e7d1459058bde5736d6ee75561a25b6 | <|skeleton|>
class VideoCaptureView:
"""ビデオキャプチャ"""
def __init__(self, parent=None):
"""コンストラクタ(インスタンスが生成される時に呼び出される)"""
<|body_0|>
def setVideoImage(self):
"""ビデオの画像を取得して表示"""
<|body_1|>
def processing(self, src):
"""画像処理"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VideoCaptureView:
"""ビデオキャプチャ"""
def __init__(self, parent=None):
"""コンストラクタ(インスタンスが生成される時に呼び出される)"""
super(VideoCaptureView, self).__init__(parent)
self.pixmap = None
self.item = None
self.capture = cv2.VideoCapture(0)
if self.capture.isOpened() is False:
... | the_stack_v2_python_sparse | 05_1024_cv/it_day5/test.py | 278Mt/taniguchi | train | 0 |
469e0e29b911be5f460ecc9d42428e326ec54a78 | [
"QMainWindow.__init__(self, parent)\nself.setupUi(self)\npixmap = PyQt4.QtGui.QPixmap('CIE_1976_UCS.png')\nPP = PyQt4.QtGui.QImage(pixmap)\nself.CIE1976_Label.setPixmap(pixmap)",
"PlotDemo()\npixmap = PyQt4.QtGui.QPixmap('a.png')\nPP = PyQt4.QtGui.QImage(pixmap)\nself.Intensity_Label.setPixmap(pixmap)"
] | <|body_start_0|>
QMainWindow.__init__(self, parent)
self.setupUi(self)
pixmap = PyQt4.QtGui.QPixmap('CIE_1976_UCS.png')
PP = PyQt4.QtGui.QImage(pixmap)
self.CIE1976_Label.setPixmap(pixmap)
<|end_body_0|>
<|body_start_1|>
PlotDemo()
pixmap = PyQt4.QtGui.QPixmap('a... | Class documentation goes here. | MainWindow | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MainWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_clicked(self):
"""Slot documentation goes here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
QMainWindow.__init__... | stack_v2_sparse_classes_36k_train_017772 | 2,420 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Slot documentation goes here.",
"name": "on_pushButton_clicked",
"signature": "def on_pushButton_clicked(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012410 | Implement the Python class `MainWindow` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def on_pushButton_clicked(self): Slot documentation goes here. | Implement the Python class `MainWindow` described below.
Class description:
Class documentation goes here.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def on_pushButton_clicked(self): Slot documentation goes here.
<|skeleton|>
class MainWindow:
"""Class documentation goes h... | 64017dbc1f050a46e58d0800fae458fe3e4802c9 | <|skeleton|>
class MainWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def on_pushButton_clicked(self):
"""Slot documentation goes here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MainWindow:
"""Class documentation goes here."""
def __init__(self, parent=None):
"""Constructor"""
QMainWindow.__init__(self, parent)
self.setupUi(self)
pixmap = PyQt4.QtGui.QPixmap('CIE_1976_UCS.png')
PP = PyQt4.QtGui.QImage(pixmap)
self.CIE1976_Label.set... | the_stack_v2_python_sparse | ChromatisityDataAnalyze/CDAMain.py | simonhdl/PythonProject | train | 0 |
489580bddaec197759876c5efc0c5963b9f5383c | [
"try:\n automl_run(nnid)\n return Response(json.dumps([True]))\nexcept Exception as e:\n return_data = {'status': '404', 'result': str(e)}\n return Response(json.dumps(return_data))",
"try:\n return_data = ''\n return Response(json.dumps(return_data))\nexcept Exception as e:\n return_data = {... | <|body_start_0|>
try:
automl_run(nnid)
return Response(json.dumps([True]))
except Exception as e:
return_data = {'status': '404', 'result': str(e)}
return Response(json.dumps(return_data))
<|end_body_0|>
<|body_start_1|>
try:
return_da... | RunManagerAutoTrain | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check ... | stack_v2_sparse_classes_36k_train_017773 | 3,403 | permissive | [
{
"docstring": "Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check result of each generation with UI/UX (7) Select Best model you ... | 4 | null | Implement the Python class `RunManagerAutoTrain` described below.
Class description:
Implement the RunManagerAutoTrain class.
Method signatures and docstrings:
- def post(self, request, nnid): Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Selec... | Implement the Python class `RunManagerAutoTrain` described below.
Class description:
Implement the RunManagerAutoTrain class.
Method signatures and docstrings:
- def post(self, request, nnid): Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Selec... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunManagerAutoTrain:
def post(self, request, nnid):
"""Bellow is the process of running automl on our framework (1) Define AutoML Graph definition (2) Select Type of Data (3) Select Type of Anal algorithm (4) Select range of hyper parameters (5) Run - AutoML (<- for this step) (6) Check result of each... | the_stack_v2_python_sparse | api/views/runmanager_auto_train.py | yurimkoo/tensormsa | train | 1 | |
88167f930bf05728aaca3011c4f09ec983957656 | [
"def arrayToBST(ls):\n l = len(ls)\n if len(ls) < 1:\n return None\n mid = (l - 1) // 2\n nd = TreeNode(ls[mid])\n nd.left = arrayToBST(ls[0:mid])\n nd.right = arrayToBST(ls[mid + 1:l])\n return nd\nls = []\nwhile head:\n ls.append(head.val)\n head = head.next\nreturn arrayToBST(ls... | <|body_start_0|>
def arrayToBST(ls):
l = len(ls)
if len(ls) < 1:
return None
mid = (l - 1) // 2
nd = TreeNode(ls[mid])
nd.left = arrayToBST(ls[0:mid])
nd.right = arrayToBST(ls[mid + 1:l])
return nd
ls = [... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedListToBST1(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedListToBST2(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def arrayToBST(ls):
... | stack_v2_sparse_classes_36k_train_017774 | 1,941 | no_license | [
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST1",
"signature": "def sortedListToBST1(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: TreeNode",
"name": "sortedListToBST2",
"signature": "def sortedListToBST2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010653 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST1(self, head): :type head: ListNode :rtype: TreeNode
- def sortedListToBST2(self, head): :type head: ListNode :rtype: TreeNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedListToBST1(self, head): :type head: ListNode :rtype: TreeNode
- def sortedListToBST2(self, head): :type head: ListNode :rtype: TreeNode
<|skeleton|>
class Solution:
... | d3e8669f932fc2e22711e8b7590d3365d020e189 | <|skeleton|>
class Solution:
def sortedListToBST1(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_0|>
def sortedListToBST2(self, head):
""":type head: ListNode :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedListToBST1(self, head):
""":type head: ListNode :rtype: TreeNode"""
def arrayToBST(ls):
l = len(ls)
if len(ls) < 1:
return None
mid = (l - 1) // 2
nd = TreeNode(ls[mid])
nd.left = arrayToBST(ls[0:mi... | the_stack_v2_python_sparse | leetcode/109.py | liuweilin17/algorithm | train | 3 | |
693fd3732eed403f711a30592f0e608ed85eba5f | [
"try:\n return version_manager_api.get(pk)\nexcept exceptions.DoesNotExist:\n raise Http404",
"try:\n template_version_manager_object = self.get_object(pk)\n serializer = TemplateVersionManagerSerializer(template_version_manager_object)\n return Response(serializer.data)\nexcept Http404:\n conte... | <|body_start_0|>
try:
return version_manager_api.get(pk)
except exceptions.DoesNotExist:
raise Http404
<|end_body_0|>
<|body_start_1|>
try:
template_version_manager_object = self.get_object(pk)
serializer = TemplateVersionManagerSerializer(templat... | Retrieve a TemplateVersionManager | TemplateVersionManagerDetail | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateVersionManagerDetail:
"""Retrieve a TemplateVersionManager"""
def get_object(self, pk):
"""Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager"""
<|body_0|>
def get(self, request, pk):
"""Retrieve a TemplateVersionManager... | stack_v2_sparse_classes_36k_train_017775 | 9,786 | permissive | [
{
"docstring": "Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager",
"name": "get_object",
"signature": "def get_object(self, pk)"
},
{
"docstring": "Retrieve a TemplateVersionManager Args: request: HTTP request pk: ObjectId Returns: - code: 200 content: Templa... | 2 | stack_v2_sparse_classes_30k_train_012083 | Implement the Python class `TemplateVersionManagerDetail` described below.
Class description:
Retrieve a TemplateVersionManager
Method signatures and docstrings:
- def get_object(self, pk): Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager
- def get(self, request, pk): Retrieve a T... | Implement the Python class `TemplateVersionManagerDetail` described below.
Class description:
Retrieve a TemplateVersionManager
Method signatures and docstrings:
- def get_object(self, pk): Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager
- def get(self, request, pk): Retrieve a T... | 568cb75a40ccff1d74a1a757866112535efd769a | <|skeleton|>
class TemplateVersionManagerDetail:
"""Retrieve a TemplateVersionManager"""
def get_object(self, pk):
"""Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager"""
<|body_0|>
def get(self, request, pk):
"""Retrieve a TemplateVersionManager... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TemplateVersionManagerDetail:
"""Retrieve a TemplateVersionManager"""
def get_object(self, pk):
"""Get TemplateVersionManager from db Args: pk: ObjectId Returns: TemplateVersionManager"""
try:
return version_manager_api.get(pk)
except exceptions.DoesNotExist:
... | the_stack_v2_python_sparse | core_main_app/rest/template_version_manager/views.py | adilmania/core_main_app | train | 0 |
72340638ade9752291fe9777c32a082104b07a78 | [
"res = []\nqueue = []\nfor num in nums:\n if len(queue) < k:\n queue.append(num)\n if len(queue) == k:\n res.append(max(queue))\n queue.pop(0)\nreturn res",
"res = []\nqueue = []\nfor i, num in enumerate(nums):\n if queue and i - queue[0] == k:\n queue.pop(0)\n while queue ... | <|body_start_0|>
res = []
queue = []
for num in nums:
if len(queue) < k:
queue.append(num)
if len(queue) == k:
res.append(max(queue))
queue.pop(0)
return res
<|end_body_0|>
<|body_start_1|>
res = []
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_017776 | 1,338 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxInWindows",
"signature": "def maxInWindows(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: List[int]",
"name": "maxInWindows",
"signature": "def maxInWindows(self, nums, k)"
... | 2 | stack_v2_sparse_classes_30k_train_004038 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
- def maxInWindows(self, nums, k): :type nums: List[int] :type k: int :rtype: List[int]
<|s... | 967b0fbb40ae491b552bc3365a481e66324cb6f2 | <|skeleton|>
class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxInWindows(self, nums, k):
""":type nums: List[int] :type k: int :rtype: List[int]"""
res = []
queue = []
for num in nums:
if len(queue) < k:
queue.append(num)
if len(queue) == k:
res.append(max(queue))
... | the_stack_v2_python_sparse | jianzhi_offer/57_滑动窗口的最大值.py | ryanatgz/data_structure_and_algorithm | train | 0 | |
61a2a57e26e5b45bb80975e2c906f7f806e02376 | [
"self.dev = dev\nself.metadata = metadata\nself.fs_type = get_filesystem_type(fs_stream)\nif self.fs_type == 'EXT4':\n self.metadata.set_module('ext4-reserved-gdt-blocks')\n self.fs = EXT4ReservedGDTBlocks(fs_stream, dev)\nelse:\n raise NotImplementedError()",
"LOGGER.info('Write')\nif filename is not No... | <|body_start_0|>
self.dev = dev
self.metadata = metadata
self.fs_type = get_filesystem_type(fs_stream)
if self.fs_type == 'EXT4':
self.metadata.set_module('ext4-reserved-gdt-blocks')
self.fs = EXT4ReservedGDTBlocks(fs_stream, dev)
else:
raise N... | This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique | ReservedGDTBlocks | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReservedGDTBlocks:
"""This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique"""
def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None):
""":param dev: Path to filesystem :param fs_stream: Stream of filesystem :param... | stack_v2_sparse_classes_36k_train_017777 | 4,406 | permissive | [
{
"docstring": ":param dev: Path to filesystem :param fs_stream: Stream of filesystem :param metadata: Metadata object",
"name": "__init__",
"signature": "def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None)"
},
{
"docstring": "writes data from instream into reserved GD... | 6 | null | Implement the Python class `ReservedGDTBlocks` described below.
Class description:
This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique
Method signatures and docstrings:
- def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None): :param dev: Path to... | Implement the Python class `ReservedGDTBlocks` described below.
Class description:
This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique
Method signatures and docstrings:
- def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None): :param dev: Path to... | b602e90ddecb8e469a28e092da3ca7fec514e3dc | <|skeleton|>
class ReservedGDTBlocks:
"""This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique"""
def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None):
""":param dev: Path to filesystem :param fs_stream: Stream of filesystem :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReservedGDTBlocks:
"""This class wraps the filesystem specific implementation of the reserved GDT blocks hiding technique"""
def __init__(self, fs_stream: typ.BinaryIO, metadata: Metadata, dev: str=None):
""":param dev: Path to filesystem :param fs_stream: Stream of filesystem :param metadata: Me... | the_stack_v2_python_sparse | src/wrapper/reserved_gdt_blocks.py | VanirLab/weever | train | 3 |
40e198602353e77b64080812be3ba2809408dbbe | [
"super().__init__(**kwargs)\ntry:\n from InstructorEmbedding import INSTRUCTOR\n self.client = INSTRUCTOR(self.model_name)\nexcept ImportError as e:\n raise ValueError('Dependencies for InstructorEmbedding not found.') from e",
"instruction_pairs = [[self.embed_instruction, text] for text in texts]\nembe... | <|body_start_0|>
super().__init__(**kwargs)
try:
from InstructorEmbedding import INSTRUCTOR
self.client = INSTRUCTOR(self.model_name)
except ImportError as e:
raise ValueError('Dependencies for InstructorEmbedding not found.') from e
<|end_body_0|>
<|body_sta... | Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkunlp/instructor-large" hf = HuggingFaceInstruc... | HuggingFaceInstructEmbeddings | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HuggingFaceInstructEmbeddings:
"""Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model... | stack_v2_sparse_classes_36k_train_017778 | 4,545 | permissive | [
{
"docstring": "Initialize the sentence_transformer.",
"name": "__init__",
"signature": "def __init__(self, **kwargs: Any)"
},
{
"docstring": "Compute doc embeddings using a HuggingFace instruct model. Args: texts: The list of texts to embed. Returns: List of embeddings, one for each text.",
... | 3 | null | Implement the Python class `HuggingFaceInstructEmbeddings` described below.
Class description:
Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings imp... | Implement the Python class `HuggingFaceInstructEmbeddings` described below.
Class description:
Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings imp... | b8f29af7f3c24cf3a4554bebfa2053064467fbdb | <|skeleton|>
class HuggingFaceInstructEmbeddings:
"""Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HuggingFaceInstructEmbeddings:
"""Wrapper around sentence_transformers embedding models. To use, you should have the ``sentence_transformers`` and ``InstructorEmbedding`` python package installed. Example: .. code-block:: python from langchain.embeddings import HuggingFaceInstructEmbeddings model_name = "hkun... | the_stack_v2_python_sparse | langchain/embeddings/huggingface.py | microsoft/MM-REACT | train | 705 |
e5b98006f2d47e4b0183060427ccf1be69609c21 | [
"self.error = ftol\nself.iterationMax = iterations_max\nself.trials = trials\nself.correct_factor = correct_factor",
"iteration = state['iteration']\nold_value = state['old_value']\nnew_value = state['new_value']\nold_parameters = state['old_parameters']\nnew_parameters = state['new_parameters']\nif not 'trial' i... | <|body_start_0|>
self.error = ftol
self.iterationMax = iterations_max
self.trials = trials
self.correct_factor = correct_factor
<|end_body_0|>
<|body_start_1|>
iteration = state['iteration']
old_value = state['old_value']
new_value = state['new_value']
ol... | The Akaike information criterion with several trials authorized | ModifiedAICCriterion | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the r... | stack_v2_sparse_classes_36k_train_017779 | 2,400 | permissive | [
{
"docstring": "Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the relative tolerance of the AIC criterion - trials indicates how many time the criterion will return false when in fact the criterion was true - correct_factor is the modifiying fact... | 2 | stack_v2_sparse_classes_30k_train_019472 | Implement the Python class `ModifiedAICCriterion` described below.
Class description:
The Akaike information criterion with several trials authorized
Method signatures and docstrings:
- def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5): Initializes the criterion with a max number of iterations an... | Implement the Python class `ModifiedAICCriterion` described below.
Class description:
The Akaike information criterion with several trials authorized
Method signatures and docstrings:
- def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5): Initializes the criterion with a max number of iterations an... | 3d298e908ff55340cd3612078508be0c791f63a8 | <|skeleton|>
class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModifiedAICCriterion:
"""The Akaike information criterion with several trials authorized"""
def __init__(self, ftol, iterations_max, correct_factor=1.0, trials=5):
"""Initializes the criterion with a max number of iterations and an error fraction for the monotony test - ftol is the relative toler... | the_stack_v2_python_sparse | PyDSTool/Toolbox/optimizers/criterion/information_criteria.py | mdlama/pydstool | train | 2 |
a09d7fcd85c38398535f08efde9d7a3c2c9b5f0d | [
"if not mr.auth.user_id:\n return {'error': 'User is not logged in.'}\njson_data = {}\nwith self.profiler.Phase('page processing'):\n json_data.update(self._GatherProjects(mr))\nreturn json_data",
"with self.profiler.Phase('GetUserProjects'):\n project_lists = sitewide_helpers.GetUserProjects(mr.cnxn, se... | <|body_start_0|>
if not mr.auth.user_id:
return {'error': 'User is not logged in.'}
json_data = {}
with self.profiler.Phase('page processing'):
json_data.update(self._GatherProjects(mr))
return json_data
<|end_body_0|>
<|body_start_1|>
with self.profiler.... | Servlet to get all of a user's projects in JSON format. | ProjectsJsonFeed | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsJsonFeed:
"""Servlet to get all of a user's projects in JSON format."""
def HandleRequest(self, mr):
"""Retrieve list of a user's projects for the "My projects" menu. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON format"""
... | stack_v2_sparse_classes_36k_train_017780 | 1,870 | permissive | [
{
"docstring": "Retrieve list of a user's projects for the \"My projects\" menu. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON format",
"name": "HandleRequest",
"signature": "def HandleRequest(self, mr)"
},
{
"docstring": "Return a dict of project... | 2 | null | Implement the Python class `ProjectsJsonFeed` described below.
Class description:
Servlet to get all of a user's projects in JSON format.
Method signatures and docstrings:
- def HandleRequest(self, mr): Retrieve list of a user's projects for the "My projects" menu. Args: mr: common information parsed from the HTTP re... | Implement the Python class `ProjectsJsonFeed` described below.
Class description:
Servlet to get all of a user's projects in JSON format.
Method signatures and docstrings:
- def HandleRequest(self, mr): Retrieve list of a user's projects for the "My projects" menu. Args: mr: common information parsed from the HTTP re... | 09064105713603f7bf75c772e8354800a1bfa256 | <|skeleton|>
class ProjectsJsonFeed:
"""Servlet to get all of a user's projects in JSON format."""
def HandleRequest(self, mr):
"""Retrieve list of a user's projects for the "My projects" menu. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON format"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectsJsonFeed:
"""Servlet to get all of a user's projects in JSON format."""
def HandleRequest(self, mr):
"""Retrieve list of a user's projects for the "My projects" menu. Args: mr: common information parsed from the HTTP request. Returns: Results dictionary in JSON format"""
if not mr... | the_stack_v2_python_sparse | appengine/monorail/sitewide/userprojects.py | mcgreevy/chromium-infra | train | 1 |
2d3478abd0ad40cf1591f5d6dc129290a99e87fd | [
"length = len(postorder)\nif length <= 0:\n return True\nroot = postorder[length - 1]\nlIndex = 0\nfor i in range(length - 1):\n if postorder[i] > root:\n break\n lIndex += 1\nrIndex = 0\nfor i in range(lIndex, length - 1):\n if postorder[i] < root:\n return False\n rIndex += 1\nleft = ... | <|body_start_0|>
length = len(postorder)
if length <= 0:
return True
root = postorder[length - 1]
lIndex = 0
for i in range(length - 1):
if postorder[i] > root:
break
lIndex += 1
rIndex = 0
for i in range(lIndex,... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
"""剑指Offer:判断有点繁琐"""
<|body_0|>
def verifyPostorder1(self, postorder: List[int]) -> bool:
"""递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti... | stack_v2_sparse_classes_36k_train_017781 | 2,707 | permissive | [
{
"docstring": "剑指Offer:判断有点繁琐",
"name": "verifyPostorder",
"signature": "def verifyPostorder(self, postorder: List[int]) -> bool"
},
{
"docstring": "递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6... | 2 | stack_v2_sparse_classes_30k_train_019970 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPostorder(self, postorder: List[int]) -> bool: 剑指Offer:判断有点繁琐
- def verifyPostorder1(self, postorder: List[int]) -> bool: 递归分治:https://leetcode-cn.com/problems/er-cha-s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def verifyPostorder(self, postorder: List[int]) -> bool: 剑指Offer:判断有点繁琐
- def verifyPostorder1(self, postorder: List[int]) -> bool: 递归分治:https://leetcode-cn.com/problems/er-cha-s... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
"""剑指Offer:判断有点繁琐"""
<|body_0|>
def verifyPostorder1(self, postorder: List[int]) -> bool:
"""递归分治:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
"""剑指Offer:判断有点繁琐"""
length = len(postorder)
if length <= 0:
return True
root = postorder[length - 1]
lIndex = 0
for i in range(length - 1):
if postorder[i] > root:
... | the_stack_v2_python_sparse | lcof/33-er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof.py | yuenliou/leetcode | train | 0 | |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nform = InterfaceForm()\nlist_inter = None\nif query:\n list_inter = Interface.objects.filter(Q(name_interface__icontains=query))\nelse:\n list_inter = Interface.objects.all()\noutput = {'form': form, 'list_inter': list_inter}\nreturn rende... | <|body_start_0|>
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
form = InterfaceForm()
list_inter = None
if query:
list_inter = Interface.objects.filter(Q(name_interface__icontains=query))
else:
list_inter = Interface.objects.a... | Clase para crear una interfaz | NewInterfaceView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewInterfaceView:
"""Clase para crear una interfaz"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = request.G... | stack_v2_sparse_classes_36k_train_017782 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003504 | Implement the Python class `NewInterfaceView` described below.
Class description:
Clase para crear una interfaz
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `NewInterfaceView` described below.
Class description:
Clase para crear una interfaz
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class NewInterfaceView:
"""Clase para crear ... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class NewInterfaceView:
"""Clase para crear una interfaz"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewInterfaceView:
"""Clase para crear una interfaz"""
def get(self, request, *args, **kwargs):
"""Método get"""
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
form = InterfaceForm()
list_inter = None
if query:
list_inter = I... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
2cadcd7fa504912608549d866275bd89362e8d87 | [
"options = ['Rock', 'Paper', 'Scissors']\nprint(\"Let's play some rock, paper and scissors!\")\npet_play = options[random.randint(0, 2)]\nplayer_play = options[int(input('Rock, Paper, Scissors?\\n 1. Rock\\n 2. Paper\\n 3. Scissors\\n ')) - 1]\nif player_play == pet_play:\n print('Tie!')\nelif player_play == 'R... | <|body_start_0|>
options = ['Rock', 'Paper', 'Scissors']
print("Let's play some rock, paper and scissors!")
pet_play = options[random.randint(0, 2)]
player_play = options[int(input('Rock, Paper, Scissors?\n 1. Rock\n 2. Paper\n 3. Scissors\n ')) - 1]
if player_play == pet_play:
... | Static class that represents mini games. Each static methods represent operation of each game. | Mini_games | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mini_games:
"""Static class that represents mini games. Each static methods represent operation of each game."""
def rock_paper_scissors():
"""Simulates a rock per and scissors game between player and pet. Randomly provides pet's behaviour."""
<|body_0|>
def hide_and_see... | stack_v2_sparse_classes_36k_train_017783 | 2,043 | no_license | [
{
"docstring": "Simulates a rock per and scissors game between player and pet. Randomly provides pet's behaviour.",
"name": "rock_paper_scissors",
"signature": "def rock_paper_scissors()"
},
{
"docstring": "Simulates a hide and seek game between player and pet. Prints out game results randomly."... | 2 | stack_v2_sparse_classes_30k_train_013544 | Implement the Python class `Mini_games` described below.
Class description:
Static class that represents mini games. Each static methods represent operation of each game.
Method signatures and docstrings:
- def rock_paper_scissors(): Simulates a rock per and scissors game between player and pet. Randomly provides pet... | Implement the Python class `Mini_games` described below.
Class description:
Static class that represents mini games. Each static methods represent operation of each game.
Method signatures and docstrings:
- def rock_paper_scissors(): Simulates a rock per and scissors game between player and pet. Randomly provides pet... | ec79fbccd6cab95192ba8ab0cb42aa3b52a8af99 | <|skeleton|>
class Mini_games:
"""Static class that represents mini games. Each static methods represent operation of each game."""
def rock_paper_scissors():
"""Simulates a rock per and scissors game between player and pet. Randomly provides pet's behaviour."""
<|body_0|>
def hide_and_see... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mini_games:
"""Static class that represents mini games. Each static methods represent operation of each game."""
def rock_paper_scissors():
"""Simulates a rock per and scissors game between player and pet. Randomly provides pet's behaviour."""
options = ['Rock', 'Paper', 'Scissors']
... | the_stack_v2_python_sparse | Assignments/Assignment 1/minigames.py | a01037479/Python_OOP_Projects | train | 0 |
3bb0c0777bc000832fbda5338c40ad26719dade0 | [
"if isinstance(key, int):\n return BlockType(key)\nif key not in BlockType._member_map_:\n return extend_enum(BlockType, key, default)\nreturn BlockType[key]",
"if not (isinstance(value, int) and 0 <= value <= 4294967295):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 168626688 <... | <|body_start_0|>
if isinstance(key, int):
return BlockType(key)
if key not in BlockType._member_map_:
return extend_enum(BlockType, key, default)
return BlockType[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 4294967295):
... | [BlockType] Block Types | BlockType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlockType:
"""[BlockType] Block Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'BlockType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int... | stack_v2_sparse_classes_36k_train_017784 | 5,422 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'BlockType'"
},
{
"docstring": "Lookup function used when value is not found. A... | 2 | null | Implement the Python class `BlockType` described below.
Class description:
[BlockType] Block Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'BlockType': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
... | Implement the Python class `BlockType` described below.
Class description:
[BlockType] Block Types
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'BlockType': Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:
... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class BlockType:
"""[BlockType] Block Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'BlockType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
def _missing_(cls, value: 'int... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlockType:
"""[BlockType] Block Types"""
def get(key: 'int | str', default: 'int'=-1) -> 'BlockType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
return BlockType(key)
... | the_stack_v2_python_sparse | pcapkit/const/pcapng/block_type.py | JarryShaw/PyPCAPKit | train | 204 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nself.average_by_layers = average_by_layers\nself.average_by_discriminators = average_by_discriminators\nself.include_final_outputs = include_final_outputs",
"feat_match_loss = 0.0\nfor i, (feats_hat_, feats_) in enumerate(zip(feats_hat, feats)):\n feat_match_loss_ = 0.0\n if not self.in... | <|body_start_0|>
super().__init__()
self.average_by_layers = average_by_layers
self.average_by_discriminators = average_by_discriminators
self.include_final_outputs = include_final_outputs
<|end_body_0|>
<|body_start_1|>
feat_match_loss = 0.0
for i, (feats_hat_, feats_) ... | Feature matching loss module. | FeatureMatchLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureMatchLoss:
"""Feature matching loss module."""
def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False):
"""Initialize FeatureMatchLoss module."""
<|body_0|>
def forward(self, feats_hat, feats):
"""Calcualate ... | stack_v2_sparse_classes_36k_train_017785 | 46,210 | permissive | [
{
"docstring": "Initialize FeatureMatchLoss module.",
"name": "__init__",
"signature": "def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False)"
},
{
"docstring": "Calcualate feature matching loss. Args: feats_hat(list): List of list of discriminat... | 2 | stack_v2_sparse_classes_30k_train_003629 | Implement the Python class `FeatureMatchLoss` described below.
Class description:
Feature matching loss module.
Method signatures and docstrings:
- def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): Initialize FeatureMatchLoss module.
- def forward(self, feats_hat... | Implement the Python class `FeatureMatchLoss` described below.
Class description:
Feature matching loss module.
Method signatures and docstrings:
- def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False): Initialize FeatureMatchLoss module.
- def forward(self, feats_hat... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class FeatureMatchLoss:
"""Feature matching loss module."""
def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False):
"""Initialize FeatureMatchLoss module."""
<|body_0|>
def forward(self, feats_hat, feats):
"""Calcualate ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureMatchLoss:
"""Feature matching loss module."""
def __init__(self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False):
"""Initialize FeatureMatchLoss module."""
super().__init__()
self.average_by_layers = average_by_layers
self.avera... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
1780e975aa396f6117a64666ecbb7754d356d4b3 | [
"self.__userNamespace = namespace\nself.__namespace = None\nself.__instance = None\nself.__importt()",
"try:\n if self.__userNamespace:\n self.__namespace = __import__(self.__userNamespace, fromlist=True)\n else:\n return None\nexcept Exception as e:\n return None",
"try:\n if classnam... | <|body_start_0|>
self.__userNamespace = namespace
self.__namespace = None
self.__instance = None
self.__importt()
<|end_body_0|>
<|body_start_1|>
try:
if self.__userNamespace:
self.__namespace = __import__(self.__userNamespace, fromlist=True)
... | R | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
<|body_0|>
def __importt(self):
"""Import package if import fail will return None"""
<|body_1|>
def Instance(self, classname, *args):
"""... | stack_v2_sparse_classes_36k_train_017786 | 2,494 | no_license | [
{
"docstring": "热加载一个类 参数 - namespace: string, 格式:generic.requier:R",
"name": "__init__",
"signature": "def __init__(self, namespace, *args, **kwargs)"
},
{
"docstring": "Import package if import fail will return None",
"name": "__importt",
"signature": "def __importt(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_train_006887 | Implement the Python class `R` described below.
Class description:
Implement the R class.
Method signatures and docstrings:
- def __init__(self, namespace, *args, **kwargs): 热加载一个类 参数 - namespace: string, 格式:generic.requier:R
- def __importt(self): Import package if import fail will return None
- def Instance(self, c... | Implement the Python class `R` described below.
Class description:
Implement the R class.
Method signatures and docstrings:
- def __init__(self, namespace, *args, **kwargs): 热加载一个类 参数 - namespace: string, 格式:generic.requier:R
- def __importt(self): Import package if import fail will return None
- def Instance(self, c... | 1678f8f3450dd194c50ffc89dcc771f14976ca20 | <|skeleton|>
class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
<|body_0|>
def __importt(self):
"""Import package if import fail will return None"""
<|body_1|>
def Instance(self, classname, *args):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class R:
def __init__(self, namespace, *args, **kwargs):
"""热加载一个类 参数 - namespace: string, 格式:generic.requier:R"""
self.__userNamespace = namespace
self.__namespace = None
self.__instance = None
self.__importt()
def __importt(self):
"""Import package if import fa... | the_stack_v2_python_sparse | generic/requier.py | TangJing/TDlib | train | 0 | |
bbde78a5fb4ca31521c59b648bf60f41df73d67f | [
"self.num_rows = num_rows\nself.colors = colors\nself.titles = titles\nself.win = pg.GraphicsWindow(title=window_title)\nself.win.resize(window_width, window_height)\nself.win.setWindowTitle(window_title)\nself.plotAreas = []\nself.curves = []\nfor i in range(0, self.num_rows):\n self.plotAreas.append(self.win.a... | <|body_start_0|>
self.num_rows = num_rows
self.colors = colors
self.titles = titles
self.win = pg.GraphicsWindow(title=window_title)
self.win.resize(window_width, window_height)
self.win.setWindowTitle(window_title)
self.plotAreas = []
self.curves = []
... | GraphVisualizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphVisualizer:
def __init__(self, num_rows, colors, titles, legend_layout='first', window_width=1000, window_height=600, window_title='PLL State Graphs'):
"""Initialize a graph visualizer. :param num_rows: Number of rows of graph to display (too many will cause performance) :param colo... | stack_v2_sparse_classes_36k_train_017787 | 2,515 | no_license | [
{
"docstring": "Initialize a graph visualizer. :param num_rows: Number of rows of graph to display (too many will cause performance) :param colors: Colors of the different curves in each graph :param titles: Titles of the curves in each graph :param legend_layout: (optional, default=\"first\") Determines where/... | 2 | stack_v2_sparse_classes_30k_train_000092 | Implement the Python class `GraphVisualizer` described below.
Class description:
Implement the GraphVisualizer class.
Method signatures and docstrings:
- def __init__(self, num_rows, colors, titles, legend_layout='first', window_width=1000, window_height=600, window_title='PLL State Graphs'): Initialize a graph visua... | Implement the Python class `GraphVisualizer` described below.
Class description:
Implement the GraphVisualizer class.
Method signatures and docstrings:
- def __init__(self, num_rows, colors, titles, legend_layout='first', window_width=1000, window_height=600, window_title='PLL State Graphs'): Initialize a graph visua... | b8061fe79f88c0892b55c2f4488355a8f68cc957 | <|skeleton|>
class GraphVisualizer:
def __init__(self, num_rows, colors, titles, legend_layout='first', window_width=1000, window_height=600, window_title='PLL State Graphs'):
"""Initialize a graph visualizer. :param num_rows: Number of rows of graph to display (too many will cause performance) :param colo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GraphVisualizer:
def __init__(self, num_rows, colors, titles, legend_layout='first', window_width=1000, window_height=600, window_title='PLL State Graphs'):
"""Initialize a graph visualizer. :param num_rows: Number of rows of graph to display (too many will cause performance) :param colors: Colors of ... | the_stack_v2_python_sparse | lib/visualization/GraphVisualizer.py | kevroy314/PLL-Neural-Network | train | 3 | |
5b10583dcd9ea6bd340af3beccf70a3e617eaab9 | [
"BaseType.__init__(self, cle)\nself.poids_max = 5.0\nself.etendre_editeur('ma', 'poids maximum', Flottant, self, 'poids_max')",
"poids_max = enveloppes['ma']\npoids_max.prompt = \"Poids maximum de l'écope : \"\npoids_max.aide_courte = \"Entrez le |ent|poids maximum|ff| en kg de l'écope.\\nEntrez |cmd|/|ff| pour r... | <|body_start_0|>
BaseType.__init__(self, cle)
self.poids_max = 5.0
self.etendre_editeur('ma', 'poids maximum', Flottant, self, 'poids_max')
<|end_body_0|>
<|body_start_1|>
poids_max = enveloppes['ma']
poids_max.prompt = "Poids maximum de l'écope : "
poids_max.aide_courte... | Type d'objet: écope. | Ecope | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ecope:
"""Type d'objet: écope."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
BaseType.__init__(s... | stack_v2_sparse_classes_36k_train_017788 | 2,557 | permissive | [
{
"docstring": "Constructeur de l'objet",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Travail sur les enveloppes",
"name": "travailler_enveloppes",
"signature": "def travailler_enveloppes(self, enveloppes)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003690 | Implement the Python class `Ecope` described below.
Class description:
Type d'objet: écope.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes | Implement the Python class `Ecope` described below.
Class description:
Type d'objet: écope.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
<|skeleton|>
class Ecope:
"""Type d'objet: écope."""
d... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Ecope:
"""Type d'objet: écope."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ecope:
"""Type d'objet: écope."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
BaseType.__init__(self, cle)
self.poids_max = 5.0
self.etendre_editeur('ma', 'poids maximum', Flottant, self, 'poids_max')
def travailler_enveloppes(self, enveloppes):
... | the_stack_v2_python_sparse | src/secondaires/navigation/types/ecope.py | vincent-lg/tsunami | train | 5 |
68f4d013e443994638d6da7bd3eb86e3be4ebfef | [
"logger.info('Overriding class: Space -> SearchSpace.')\nn_dimensions = 1\nsuper(SearchSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)\nself.build()\nlogger.info('Class overrided.')",
"for agent in self.agents:\n agent.fill_with_uniform()\nself.best_agent = copy.de... | <|body_start_0|>
logger.info('Overriding class: Space -> SearchSpace.')
n_dimensions = 1
super(SearchSpace, self).__init__(n_agents, n_variables, n_dimensions, lower_bound, upper_bound, mapping)
self.build()
logger.info('Class overrided.')
<|end_body_0|>
<|body_start_1|>
... | A SearchSpace class for agents, variables and methods related to the search space. | SearchSpace | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchSpace:
"""A SearchSpace class for agents, variables and methods related to the search space."""
def __init__(self, n_agents: int, n_variables: int, lower_bound: Union[float, List, Tuple, np.ndarray], upper_bound: Union[float, List, Tuple, np.ndarray], mapping: Optional[List[str]]=None)... | stack_v2_sparse_classes_36k_train_017789 | 1,500 | permissive | [
{
"docstring": "Initialization method. Args: n_agents: Number of agents. n_variables: Number of decision variables. lower_bound: Minimum possible values. upper_bound: Maximum possible values. mapping: String-based identifiers for mapping variables' names.",
"name": "__init__",
"signature": "def __init__... | 2 | stack_v2_sparse_classes_30k_train_009061 | Implement the Python class `SearchSpace` described below.
Class description:
A SearchSpace class for agents, variables and methods related to the search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, lower_bound: Union[float, List, Tuple, np.ndarray], upper_bound: Union... | Implement the Python class `SearchSpace` described below.
Class description:
A SearchSpace class for agents, variables and methods related to the search space.
Method signatures and docstrings:
- def __init__(self, n_agents: int, n_variables: int, lower_bound: Union[float, List, Tuple, np.ndarray], upper_bound: Union... | 7326a887ed8e3858bc99c8815048d56d02edf88c | <|skeleton|>
class SearchSpace:
"""A SearchSpace class for agents, variables and methods related to the search space."""
def __init__(self, n_agents: int, n_variables: int, lower_bound: Union[float, List, Tuple, np.ndarray], upper_bound: Union[float, List, Tuple, np.ndarray], mapping: Optional[List[str]]=None)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchSpace:
"""A SearchSpace class for agents, variables and methods related to the search space."""
def __init__(self, n_agents: int, n_variables: int, lower_bound: Union[float, List, Tuple, np.ndarray], upper_bound: Union[float, List, Tuple, np.ndarray], mapping: Optional[List[str]]=None) -> None:
... | the_stack_v2_python_sparse | opytimizer/spaces/search.py | gugarosa/opytimizer | train | 602 |
c8ea73afb727b386f17a6ca9bcd8e6e0f9bc4b89 | [
"self.N = N\nself.nummap = dict()\nv = 0\nfor i in range(N):\n while v in blacklist:\n v += 1\n self.nummap[i] = v % N\n v += 1",
"if len(self.nummap) == 1:\n return self.nummap[0]\nelse:\n return self.nummap[randint(0, self.N - 1)]"
] | <|body_start_0|>
self.N = N
self.nummap = dict()
v = 0
for i in range(N):
while v in blacklist:
v += 1
self.nummap[i] = v % N
v += 1
<|end_body_0|>
<|body_start_1|>
if len(self.nummap) == 1:
return self.nummap[0]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.N = N
self.nummap = dict()
v = 0
for i i... | stack_v2_sparse_classes_36k_train_017790 | 1,789 | no_license | [
{
"docstring": ":type N: int :type blacklist: List[int]",
"name": "__init__",
"signature": "def __init__(self, N, blacklist)"
},
{
"docstring": ":rtype: int",
"name": "pick",
"signature": "def pick(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, N, blacklist): :type N: int :type blacklist: List[int]
- def pick(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, N, blacklist):
... | 08c6d27498e35f636045fed05a6f94b760ab69ca | <|skeleton|>
class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
<|body_0|>
def pick(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, N, blacklist):
""":type N: int :type blacklist: List[int]"""
self.N = N
self.nummap = dict()
v = 0
for i in range(N):
while v in blacklist:
v += 1
self.nummap[i] = v % N
v += 1
def pic... | the_stack_v2_python_sparse | solutions/hashtable/710.Random.Pick.with.Blacklist.py | ljia2/leetcode.py | train | 0 | |
74d469c0c16c9e1b160ff0516ec117e1d5660674 | [
"if not root:\n return ''\nret = []\nq = collections.deque([root])\nwhile q:\n node = q.popleft()\n if not node:\n ret.append('#')\n continue\n else:\n ret.append(str(node.val))\n q.append(node.left)\n q.append(node.right)\nreturn ','.join(ret)",
"if not data:\n return No... | <|body_start_0|>
if not root:
return ''
ret = []
q = collections.deque([root])
while q:
node = q.popleft()
if not node:
ret.append('#')
continue
else:
ret.append(str(node.val))
q.a... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_017791 | 1,720 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 881b98bfec23ec62112e2648c00ce7744ce70856 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
ret = []
q = collections.deque([root])
while q:
node = q.popleft()
if not node:
ret.app... | the_stack_v2_python_sparse | 00_leetcode/297.serialize-and-deserialize-binary-tree.py | luxuguang-leo/everyday_leetcode | train | 3 | |
9efc50638e516b542eddacc588fcc642faf7b0cd | [
"self.url = url\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36 Maxthon/5.1.3.2000'}\nr = requests.get(url=self.url, headers=headers)\nif r.status_code == 200:\n self.text = r.text\nelse:\n self.text = None",
"if self.te... | <|body_start_0|>
self.url = url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36 Maxthon/5.1.3.2000'}
r = requests.get(url=self.url, headers=headers)
if r.status_code == 200:
self.text = r.t... | Extract_link | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Extract_link:
def __init__(self, url):
"""初始化时访问url并将response的内容存储起来"""
<|body_0|>
def extract_link(self):
"""从页面中分析出链接"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.url = url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW... | stack_v2_sparse_classes_36k_train_017792 | 1,794 | no_license | [
{
"docstring": "初始化时访问url并将response的内容存储起来",
"name": "__init__",
"signature": "def __init__(self, url)"
},
{
"docstring": "从页面中分析出链接",
"name": "extract_link",
"signature": "def extract_link(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012934 | Implement the Python class `Extract_link` described below.
Class description:
Implement the Extract_link class.
Method signatures and docstrings:
- def __init__(self, url): 初始化时访问url并将response的内容存储起来
- def extract_link(self): 从页面中分析出链接 | Implement the Python class `Extract_link` described below.
Class description:
Implement the Extract_link class.
Method signatures and docstrings:
- def __init__(self, url): 初始化时访问url并将response的内容存储起来
- def extract_link(self): 从页面中分析出链接
<|skeleton|>
class Extract_link:
def __init__(self, url):
"""初始化时访问u... | 355c7251dda058deefc80f3bffbf6c541d92ad41 | <|skeleton|>
class Extract_link:
def __init__(self, url):
"""初始化时访问url并将response的内容存储起来"""
<|body_0|>
def extract_link(self):
"""从页面中分析出链接"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Extract_link:
def __init__(self, url):
"""初始化时访问url并将response的内容存储起来"""
self.url = url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36 Maxthon/5.1.3.2000'}
r = requests.get(url=self.url, head... | the_stack_v2_python_sparse | module4-04threads/spider.py | echolvan/homework | train | 0 | |
42992f185c943abe534ab86eb968e04530cb33fc | [
"if not self._unscale:\n raise ResourceValueError('SAM requires unscaled values')\nres_df = pd.DataFrame({'Year': self.time_index.year, 'Month': self.time_index.month, 'Day': self.time_index.day, 'Hour': self.time_index.hour})\nif len(self) > 8784:\n res_df['Minute'] = self.time_index.minute\ntime_zone = self... | <|body_start_0|>
if not self._unscale:
raise ResourceValueError('SAM requires unscaled values')
res_df = pd.DataFrame({'Year': self.time_index.year, 'Month': self.time_index.month, 'Day': self.time_index.day, 'Hour': self.time_index.hour})
if len(self) > 8784:
res_df['Min... | Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class | SolarResource | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolarResource:
"""Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM solar resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extra... | stack_v2_sparse_classes_36k_train_017793 | 43,525 | permissive | [
{
"docstring": "Get SAM solar resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract SAM DataFrame for Returns ------- res_df : pandas.DataFrame time-series DataFrame of resource variables needed to run SAM",
"name": "_get_SAM_df",
"signatu... | 3 | stack_v2_sparse_classes_30k_train_002365 | Implement the Python class `SolarResource` described below.
Class description:
Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _get_SAM_df(self, ds_name, site): Get SAM solar resource DataFrame for given site Parameters ---------- ds_... | Implement the Python class `SolarResource` described below.
Class description:
Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _get_SAM_df(self, ds_name, site): Get SAM solar resource DataFrame for given site Parameters ---------- ds_... | ca598da8bbcd9983fb1355fe3b67d58273eef5c6 | <|skeleton|>
class SolarResource:
"""Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM solar resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolarResource:
"""Class to handle Solar Resource .h5 files See Also -------- resource.Resource : Parent class"""
def _get_SAM_df(self, ds_name, site):
"""Get SAM solar resource DataFrame for given site Parameters ---------- ds_name : str 'Dataset' name == SAM site : int Site to extract SAM DataFr... | the_stack_v2_python_sparse | rex/renewable_resource.py | aidanbharath/rex | train | 0 |
dafe2af1e992ad48c7fc90b60df65eacaf6f064b | [
"self.x = x\nself.y = y\nself.width = width\nself.height = height\nself.col = col\nself.priority = priority",
"str1 = 'Oval @ ( ' + str(self.x) + ' , ' + str(self.y) + ' ) '\nstr2 = 'height = ' + str(self.height) + ', width = ' + str(self.width)\nreturn str1 + str2",
"x = int(self.x - 0.5 * self.width)\ny = int... | <|body_start_0|>
self.x = x
self.y = y
self.width = width
self.height = height
self.col = col
self.priority = priority
<|end_body_0|>
<|body_start_1|>
str1 = 'Oval @ ( ' + str(self.x) + ' , ' + str(self.y) + ' ) '
str2 = 'height = ' + str(self.height) + '... | Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw | Oval | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Oval:
"""Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw"""
def __init__(self, x=0, y=0, width=0, height=0, col=media.white, priority=0):
"""Initialize the attributes of the Oval object. The x and y values represent the center of th... | stack_v2_sparse_classes_36k_train_017794 | 1,652 | no_license | [
{
"docstring": "Initialize the attributes of the Oval object. The x and y values represent the center of the oval, and the width and height of the oval are passed in as width and height. All input values are integers, except for colour, which is a media.color value.",
"name": "__init__",
"signature": "d... | 3 | stack_v2_sparse_classes_30k_train_001525 | Implement the Python class `Oval` described below.
Class description:
Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw
Method signatures and docstrings:
- def __init__(self, x=0, y=0, width=0, height=0, col=media.white, priority=0): Initialize the attributes of the O... | Implement the Python class `Oval` described below.
Class description:
Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw
Method signatures and docstrings:
- def __init__(self, x=0, y=0, width=0, height=0, col=media.white, priority=0): Initialize the attributes of the O... | b7bd34be51f9c22b6d31f5fe62b14300e89adf9f | <|skeleton|>
class Oval:
"""Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw"""
def __init__(self, x=0, y=0, width=0, height=0, col=media.white, priority=0):
"""Initialize the attributes of the Oval object. The x and y values represent the center of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Oval:
"""Draw a Oval with the center (x,y) and width and heigh. the class has methods: __init__ __str__ draw"""
def __init__(self, x=0, y=0, width=0, height=0, col=media.white, priority=0):
"""Initialize the attributes of the Oval object. The x and y values represent the center of the oval, and t... | the_stack_v2_python_sparse | collage image/oval.py | wangchi9/undergraduate-projects | train | 0 |
59052ba107e06b632ac3847d32878ea5ef8add2c | [
"if hasattr(self, 'set_model_params'):\n set_model_param_method = getattr(self, 'set_model_params')\n args, varargs, kw, default = inspect.getargspec(set_model_param_method)\n if varargs is not None:\n raise RuntimeError(\"pyEMMA models should always specify their parameters in the signature of thei... | <|body_start_0|>
if hasattr(self, 'set_model_params'):
set_model_param_method = getattr(self, 'set_model_params')
args, varargs, kw, default = inspect.getargspec(set_model_param_method)
if varargs is not None:
raise RuntimeError("pyEMMA models should always sp... | Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with pyEMMA and sklearn Estimators. | Model | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with pyEMM... | stack_v2_sparse_classes_36k_train_017795 | 6,799 | permissive | [
{
"docstring": "Get parameter names for the estimator",
"name": "_get_model_param_names",
"signature": "def _get_model_param_names(self)"
},
{
"docstring": "Update given model parameter if they are set to specific values",
"name": "update_model_params",
"signature": "def update_model_par... | 3 | null | Implement the Python class `Model` described below.
Class description:
Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclas... | Implement the Python class `Model` described below.
Class description:
Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclas... | a36534ce2ec6a799428dfbdef0465c979e6c68aa | <|skeleton|>
class Model:
"""Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with pyEMM... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
"""Base class for pyEMMA models This class is inspired by sklearn's BaseEstimator class. However, we define parameter names not by the current class' __init__ but have to announce them. This allows us to also remember the parameters of model superclasses. This class can be mixed with pyEMMA and sklearn... | the_stack_v2_python_sparse | pyemma/_base/model.py | clonker/PyEMMA | train | 1 |
58337bffadabbaf28aad27fe0cbb50a291330bc8 | [
"u = User(id=1)\nassert u.id == 1\nu = User(id=2, name=u'Unicode Náme')\nassert u.name == u'Unicode Náme'\nu = User('ASCII Name', 3)\nassert u.id == 3 and u.name == 'ASCII Name'",
"elem = objectify.parse(TestUser.xml).getroot()\nu = User(elem=elem)\nassert u.id == 5\nassert u.name == u'Bongani Buthelêzi'"
] | <|body_start_0|>
u = User(id=1)
assert u.id == 1
u = User(id=2, name=u'Unicode Náme')
assert u.name == u'Unicode Náme'
u = User('ASCII Name', 3)
assert u.id == 3 and u.name == 'ASCII Name'
<|end_body_0|>
<|body_start_1|>
elem = objectify.parse(TestUser.xml).getro... | Unit test for the User model class. | TestUser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUser:
"""Unit test for the User model class."""
def test_create_no_xml(self):
"""Test creation of a simple User object with its own constructor."""
<|body_0|>
def test_create_from_xml(self):
"""Test creation of a User instance by using the create_from_elem() ... | stack_v2_sparse_classes_36k_train_017796 | 1,947 | no_license | [
{
"docstring": "Test creation of a simple User object with its own constructor.",
"name": "test_create_no_xml",
"signature": "def test_create_no_xml(self)"
},
{
"docstring": "Test creation of a User instance by using the create_from_elem() factory method.",
"name": "test_create_from_xml",
... | 2 | null | Implement the Python class `TestUser` described below.
Class description:
Unit test for the User model class.
Method signatures and docstrings:
- def test_create_no_xml(self): Test creation of a simple User object with its own constructor.
- def test_create_from_xml(self): Test creation of a User instance by using th... | Implement the Python class `TestUser` described below.
Class description:
Unit test for the User model class.
Method signatures and docstrings:
- def test_create_no_xml(self): Test creation of a simple User object with its own constructor.
- def test_create_from_xml(self): Test creation of a User instance by using th... | 2c169f0904d54d462958049e5527c3d8fb780238 | <|skeleton|>
class TestUser:
"""Unit test for the User model class."""
def test_create_no_xml(self):
"""Test creation of a simple User object with its own constructor."""
<|body_0|>
def test_create_from_xml(self):
"""Test creation of a User instance by using the create_from_elem() ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUser:
"""Unit test for the User model class."""
def test_create_no_xml(self):
"""Test creation of a simple User object with its own constructor."""
u = User(id=1)
assert u.id == 1
u = User(id=2, name=u'Unicode Náme')
assert u.name == u'Unicode Náme'
u =... | the_stack_v2_python_sparse | spelt/models/test_user.py | translate/spelt | train | 2 |
927b0c960263c119595be0c7410d4ed40e6b0e9d | [
"nums = [i for i in range(1, k + 1)]\nnums.append(n + 1)\nleft, output = (0, [])\nwhile left < k:\n output.append(nums[:k])\n left = 0\n while left < k and nums[left] + 1 == nums[left + 1]:\n nums[left] = left + 1\n left += 1\n nums[left] += 1\nreturn output",
"def back_track(first=1, co... | <|body_start_0|>
nums = [i for i in range(1, k + 1)]
nums.append(n + 1)
left, output = (0, [])
while left < k:
output.append(nums[:k])
left = 0
while left < k and nums[left] + 1 == nums[left + 1]:
nums[left] = left + 1
l... | Combination | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Combination:
def get_all(self, n: int, k: int) -> List[List[int]]:
"""Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n: :param k: :return:"""
<|body_0|>
def get_all_(self, n: int, k: int) -> List[List[int]... | stack_v2_sparse_classes_36k_train_017797 | 1,812 | no_license | [
{
"docstring": "Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n: :param k: :return:",
"name": "get_all",
"signature": "def get_all(self, n: int, k: int) -> List[List[int]]"
},
{
"docstring": "Approach: Back Tracking Time Comp... | 2 | stack_v2_sparse_classes_30k_train_001317 | Implement the Python class `Combination` described below.
Class description:
Implement the Combination class.
Method signatures and docstrings:
- def get_all(self, n: int, k: int) -> List[List[int]]: Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n... | Implement the Python class `Combination` described below.
Class description:
Implement the Combination class.
Method signatures and docstrings:
- def get_all(self, n: int, k: int) -> List[List[int]]: Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Combination:
def get_all(self, n: int, k: int) -> List[List[int]]:
"""Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n: :param k: :return:"""
<|body_0|>
def get_all_(self, n: int, k: int) -> List[List[int]... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Combination:
def get_all(self, n: int, k: int) -> List[List[int]]:
"""Approach: Lexographic Binary Sorted Combinations Time Complexity: O (k C(k, n)) Space Complexity: O (C(k, n)) :param n: :param k: :return:"""
nums = [i for i in range(1, k + 1)]
nums.append(n + 1)
left, outpu... | the_stack_v2_python_sparse | revisited/permutations_combinations_subsets/combinations.py | Shiv2157k/leet_code | train | 1 | |
ebef2a3509452c7d06a973262d975bc8a1c8bcd1 | [
"token = get_jwt_value(request)\nif token is None:\n return None\npayload = jwt_decode_handler(token)\nuser = self.authenticate_credentials(payload)\nreturn (user, token)",
"User = get_user_model()\nuuid = payload.get('uuid')\nif not uuid:\n msg = _('Invalid payload.')\n raise exceptions.AuthenticationFa... | <|body_start_0|>
token = get_jwt_value(request)
if token is None:
return None
payload = jwt_decode_handler(token)
user = self.authenticate_credentials(payload)
return (user, token)
<|end_body_0|>
<|body_start_1|>
User = get_user_model()
uuid = payload... | Token based authentication using the JSON Web Token standard. | BaseJSONWebTokenAuthentication | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
... | stack_v2_sparse_classes_36k_train_017798 | 2,443 | permissive | [
{
"docstring": "Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`.",
"name": "authenticate",
"signature": "def authenticate(self, request)"
},
{
"docstring": "Returns an active user that matches the payload's u... | 2 | stack_v2_sparse_classes_30k_train_004340 | Implement the Python class `BaseJSONWebTokenAuthentication` described below.
Class description:
Token based authentication using the JSON Web Token standard.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-ba... | Implement the Python class `BaseJSONWebTokenAuthentication` described below.
Class description:
Token based authentication using the JSON Web Token standard.
Method signatures and docstrings:
- def authenticate(self, request): Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-ba... | 95ab36c5af3bdd9bc2e8201983a828e7e2e2ef76 | <|skeleton|>
class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseJSONWebTokenAuthentication:
"""Token based authentication using the JSON Web Token standard."""
def authenticate(self, request):
"""Returns a two-tuple of `User` and token if a valid signature has been supplied using JWT-based authentication. Otherwise returns `None`."""
token = get_j... | the_stack_v2_python_sparse | mt_jwt_auth/jwt_user/authenticators.py | abdulsami5/mt_jwt_auth | train | 1 |
ce8eefc65189e1c03def86e94c5361f00e3d1251 | [
"try:\n receiver = self.cleaned_data.get('receiver', '')\n self.instance.receiver = User.objects.get(username=receiver)\n return receiver\nexcept User.DoesNotExist:\n raise forms.ValidationError('Receiver does not exist')",
"raw_content = self.cleaned_data.get('content')\nif not len(raw_content):\n ... | <|body_start_0|>
try:
receiver = self.cleaned_data.get('receiver', '')
self.instance.receiver = User.objects.get(username=receiver)
return receiver
except User.DoesNotExist:
raise forms.ValidationError('Receiver does not exist')
<|end_body_0|>
<|body_star... | New message form | MessageForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
<|body_0|>
def clean_content(self):
"""Clean content"""
<|body_1|>
def save(self, *args, **kwargs):
"""Set sender if not exist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k_train_017799 | 1,309 | no_license | [
{
"docstring": "Clean receiver",
"name": "clean_receiver",
"signature": "def clean_receiver(self)"
},
{
"docstring": "Clean content",
"name": "clean_content",
"signature": "def clean_content(self)"
},
{
"docstring": "Set sender if not exist",
"name": "save",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_020617 | Implement the Python class `MessageForm` described below.
Class description:
New message form
Method signatures and docstrings:
- def clean_receiver(self): Clean receiver
- def clean_content(self): Clean content
- def save(self, *args, **kwargs): Set sender if not exist | Implement the Python class `MessageForm` described below.
Class description:
New message form
Method signatures and docstrings:
- def clean_receiver(self): Clean receiver
- def clean_content(self): Clean content
- def save(self, *args, **kwargs): Set sender if not exist
<|skeleton|>
class MessageForm:
"""New mes... | 39deb1dc046c80edd6bfdfbef8391842eda35dd2 | <|skeleton|>
class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
<|body_0|>
def clean_content(self):
"""Clean content"""
<|body_1|>
def save(self, *args, **kwargs):
"""Set sender if not exist"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageForm:
"""New message form"""
def clean_receiver(self):
"""Clean receiver"""
try:
receiver = self.cleaned_data.get('receiver', '')
self.instance.receiver = User.objects.get(username=receiver)
return receiver
except User.DoesNotExist:
... | the_stack_v2_python_sparse | src/messaging/forms.py | nvbn/djang0byte | train | 26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.