blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7797f84800307bcaf6aecc4e421e3971bd084ed | [
"if kaldi_vocabulary is not None:\n self.kaldi_word_to_id = read_kaldi_vocabulary(kaldi_vocabulary)\n self.kaldi_id_to_word = [None] * len(self.kaldi_word_to_id)\n for word, id in self.kaldi_word_to_id.items():\n self.kaldi_id_to_word[id] = word\nelif lattice_format == 'kaldi':\n raise ValueError... | <|body_start_0|>
if kaldi_vocabulary is not None:
self.kaldi_word_to_id = read_kaldi_vocabulary(kaldi_vocabulary)
self.kaldi_id_to_word = [None] * len(self.kaldi_word_to_id)
for word, id in self.kaldi_word_to_id.items():
self.kaldi_id_to_word[id] = word
... | LatticeBatch | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatticeBatch:
def __init__(self, lattices, lattice_list_file, lattice_format, kaldi_vocabulary=None, num_jobs=1, job_id=0):
"""Reads the Kaldi word ID mapping, if given, and slices the lattices corresponding to the given job ID. If there's nothing else in the lattice list, adds the stand... | stack_v2_sparse_classes_75kplus_train_074400 | 4,242 | permissive | [
{
"docstring": "Reads the Kaldi word ID mapping, if given, and slices the lattices corresponding to the given job ID. If there's nothing else in the lattice list, adds the standard input. :type lattices: list of strs :param lattices: a list of lattice file paths :type lattice_list_file: file object :param latti... | 2 | stack_v2_sparse_classes_30k_test_001141 | Implement the Python class `LatticeBatch` described below.
Class description:
Implement the LatticeBatch class.
Method signatures and docstrings:
- def __init__(self, lattices, lattice_list_file, lattice_format, kaldi_vocabulary=None, num_jobs=1, job_id=0): Reads the Kaldi word ID mapping, if given, and slices the la... | Implement the Python class `LatticeBatch` described below.
Class description:
Implement the LatticeBatch class.
Method signatures and docstrings:
- def __init__(self, lattices, lattice_list_file, lattice_format, kaldi_vocabulary=None, num_jobs=1, job_id=0): Reads the Kaldi word ID mapping, if given, and slices the la... | 9904faec19ad5718470f21927229aad2656e5686 | <|skeleton|>
class LatticeBatch:
def __init__(self, lattices, lattice_list_file, lattice_format, kaldi_vocabulary=None, num_jobs=1, job_id=0):
"""Reads the Kaldi word ID mapping, if given, and slices the lattices corresponding to the given job ID. If there's nothing else in the lattice list, adds the stand... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LatticeBatch:
def __init__(self, lattices, lattice_list_file, lattice_format, kaldi_vocabulary=None, num_jobs=1, job_id=0):
"""Reads the Kaldi word ID mapping, if given, and slices the lattices corresponding to the given job ID. If there's nothing else in the lattice list, adds the standard input. :ty... | the_stack_v2_python_sparse | theanolm/scoring/latticebatch.py | senarvi/theanolm | train | 95 | |
2c56abeb2396749edb0ac6a156b985fc6cf2b939 | [
"self.instance = get_object_or_404(Instance, slug=self.kwargs['slug'])\ncanvas = self.instance.images().filter(short_id=self.kwargs['short_id']).first()\nif canvas and Instance.allow_canvas_detail(canvas):\n return canvas\nelse:\n raise Http404",
"context = super(CanvasDetail, self).get_context_data(*args, ... | <|body_start_0|>
self.instance = get_object_or_404(Instance, slug=self.kwargs['slug'])
canvas = self.instance.images().filter(short_id=self.kwargs['short_id']).first()
if canvas and Instance.allow_canvas_detail(canvas):
return canvas
else:
raise Http404
<|end_body... | CanvasDetail | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasDetail:
def get_object(self, queryset=None):
"""Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Set extra context for :class:`CanvasDetai... | stack_v2_sparse_classes_75kplus_train_074401 | 37,410 | permissive | [
{
"docstring": "Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated.",
"name": "get_object",
"signature": "def get_object(self, queryset=None)"
},
{
"docstring": "Set extra context for :class:`CanvasDetail` view.",
"name": "get_context... | 2 | stack_v2_sparse_classes_30k_train_005376 | Implement the Python class `CanvasDetail` described below.
Class description:
Implement the CanvasDetail class.
Method signatures and docstrings:
- def get_object(self, queryset=None): Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated.
- def get_context_data(... | Implement the Python class `CanvasDetail` described below.
Class description:
Implement the CanvasDetail class.
Method signatures and docstrings:
- def get_object(self, queryset=None): Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated.
- def get_context_data(... | 6371bb1266d7751af59aeaa3426ef7ac02a1fe17 | <|skeleton|>
class CanvasDetail:
def get_object(self, queryset=None):
"""Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated."""
<|body_0|>
def get_context_data(self, *args, **kwargs):
"""Set extra context for :class:`CanvasDetai... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CanvasDetail:
def get_object(self, queryset=None):
"""Limit canvas detail view to those with :class:`derrida.interventions.models.Intervention` objects associated."""
self.instance = get_object_or_404(Instance, slug=self.kwargs['slug'])
canvas = self.instance.images().filter(short_id=s... | the_stack_v2_python_sparse | derrida/books/views.py | Princeton-CDH/derrida-django | train | 13 | |
e671e8af709d5560eb10b9a873dd7f279ee16cab | [
"self.__nb_objects\nif id is None:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\nelse:\n self.id = id",
"if list_dictionaries is None:\n return '[]'\nelse:\n return json.dumps(list_dictionaries)",
"list_dicts = []\nfor instances in list_objs:\n list_dicts.append(instances.to_dictiona... | <|body_start_0|>
self.__nb_objects
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
self.id = id
<|end_body_0|>
<|body_start_1|>
if list_dictionaries is None:
return '[]'
else:
return json.dumps(l... | Class Base Attributes: __nb_objects = # of instances meant to be id | Base | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Base:
"""Class Base Attributes: __nb_objects = # of instances meant to be id"""
def __init__(self, id=None):
"""init method Args: id - obj id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representatin of list_dictionaries Args: ... | stack_v2_sparse_classes_75kplus_train_074402 | 1,496 | no_license | [
{
"docstring": "init method Args: id - obj id",
"name": "__init__",
"signature": "def __init__(self, id=None)"
},
{
"docstring": "Returns the JSON string representatin of list_dictionaries Args: list_dictionaries - list of dictionaries",
"name": "to_json_string",
"signature": "def to_jso... | 3 | null | Implement the Python class `Base` described below.
Class description:
Class Base Attributes: __nb_objects = # of instances meant to be id
Method signatures and docstrings:
- def __init__(self, id=None): init method Args: id - obj id
- def to_json_string(list_dictionaries): Returns the JSON string representatin of lis... | Implement the Python class `Base` described below.
Class description:
Class Base Attributes: __nb_objects = # of instances meant to be id
Method signatures and docstrings:
- def __init__(self, id=None): init method Args: id - obj id
- def to_json_string(list_dictionaries): Returns the JSON string representatin of lis... | a3871616169d94fad284c999d83f21682e17b909 | <|skeleton|>
class Base:
"""Class Base Attributes: __nb_objects = # of instances meant to be id"""
def __init__(self, id=None):
"""init method Args: id - obj id"""
<|body_0|>
def to_json_string(list_dictionaries):
"""Returns the JSON string representatin of list_dictionaries Args: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Base:
"""Class Base Attributes: __nb_objects = # of instances meant to be id"""
def __init__(self, id=None):
"""init method Args: id - obj id"""
self.__nb_objects
if id is None:
Base.__nb_objects += 1
self.id = Base.__nb_objects
else:
se... | the_stack_v2_python_sparse | 0x0C-python-almost_a_circle/models/base.py | GabrielAbdul/holbertonschool-higher_level_programming | train | 0 |
7f7363430380b5165615220db708e3c1596e3861 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. The followi... | UserAPIServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserAPIServicer:
"""UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interp... | stack_v2_sparse_classes_75kplus_train_074403 | 5,753 | no_license | [
{
"docstring": "Gets the information about an user by its user id.",
"name": "GetUser",
"signature": "def GetUser(self, request, context)"
},
{
"docstring": "Gets the groups of a user.",
"name": "GetUserGroups",
"signature": "def GetUserGroups(self, request, context)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_test_002842 | Implement the Python class `UserAPIServicer` described below.
Class description:
UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTI... | Implement the Python class `UserAPIServicer` described below.
Class description:
UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTI... | dad1a042b38db5f8bedcac3b6af25066f4d6eef9 | <|skeleton|>
class UserAPIServicer:
"""UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserAPIServicer:
"""UserProvider API. The UserProvider API is responsible for creating a key-value map according to user userprovider. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as desc... | the_stack_v2_python_sparse | cs3/identity/user/v1beta1/user_api_pb2_grpc.py | SamuAlfageme/python-cs3apis | train | 0 |
d17973ed51d6284a547e2ef8a77a27b5774985ef | [
"for key in inwrappers:\n if not key.startswith('foreign data wrapper '):\n raise KeyError('Unrecognized object type: %s' % key)\n fdw = key[21:]\n inobj = inwrappers[key]\n inservs = {}\n for key in inobj:\n if key.startswith('server '):\n inservs.update({key: inobj[key]})\n... | <|body_start_0|>
for key in inwrappers:
if not key.startswith('foreign data wrapper '):
raise KeyError('Unrecognized object type: %s' % key)
fdw = key[21:]
inobj = inwrappers[key]
inservs = {}
for key in inobj:
if key.st... | The collection of foreign data wrappers in a database | ForeignDataWrapperDict | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForeignDataWrapperDict:
"""The collection of foreign data wrappers in a database"""
def from_map(self, inwrappers, newdb):
"""Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map defining the data wrappers :param newdb: collection of dict... | stack_v2_sparse_classes_75kplus_train_074404 | 24,509 | permissive | [
{
"docstring": "Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map defining the data wrappers :param newdb: collection of dictionaries defining the database",
"name": "from_map",
"signature": "def from_map(self, inwrappers, newdb)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_050394 | Implement the Python class `ForeignDataWrapperDict` described below.
Class description:
The collection of foreign data wrappers in a database
Method signatures and docstrings:
- def from_map(self, inwrappers, newdb): Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map de... | Implement the Python class `ForeignDataWrapperDict` described below.
Class description:
The collection of foreign data wrappers in a database
Method signatures and docstrings:
- def from_map(self, inwrappers, newdb): Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map de... | ec682513d5256e383647f38f7fba29530cfb9fbe | <|skeleton|>
class ForeignDataWrapperDict:
"""The collection of foreign data wrappers in a database"""
def from_map(self, inwrappers, newdb):
"""Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map defining the data wrappers :param newdb: collection of dict... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ForeignDataWrapperDict:
"""The collection of foreign data wrappers in a database"""
def from_map(self, inwrappers, newdb):
"""Initialize the dictionary of wrappers by examining the input map :param inwrappers: input YAML map defining the data wrappers :param newdb: collection of dictionaries defi... | the_stack_v2_python_sparse | pyrseas/dbobject/foreign.py | perseas/Pyrseas | train | 323 |
12f41fcdfdcd7befdcb6ae51ca0b8f37ac879435 | [
"pergunta = 'Qual a primeira língua que você aprendeu a falar?'\nminha_pesquisa = PesquisaAnonima(pergunta=pergunta)\nminha_pesquisa.conjunto_respostas(nova_resposta='Português')\nself.assertIn('Português', minha_pesquisa.respostas)",
"pergunta = 'Qual a primeira língua que você aprendeu a falar?'\nminha_pesquisa... | <|body_start_0|>
pergunta = 'Qual a primeira língua que você aprendeu a falar?'
minha_pesquisa = PesquisaAnonima(pergunta=pergunta)
minha_pesquisa.conjunto_respostas(nova_resposta='Português')
self.assertIn('Português', minha_pesquisa.respostas)
<|end_body_0|>
<|body_start_1|>
p... | Testes para a classe PesquisaAnonima | TestePesquisaAnonima | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestePesquisaAnonima:
"""Testes para a classe PesquisaAnonima"""
def test_resposta_unica(self):
"""Testa se uma única resposta é armazenada de forma apropriada."""
<|body_0|>
def test_tres_respostas(self):
"""Testa se três respostas individuais são armazenadas de... | stack_v2_sparse_classes_75kplus_train_074405 | 1,192 | permissive | [
{
"docstring": "Testa se uma única resposta é armazenada de forma apropriada.",
"name": "test_resposta_unica",
"signature": "def test_resposta_unica(self)"
},
{
"docstring": "Testa se três respostas individuais são armazenadas de forma apropriada.",
"name": "test_tres_respostas",
"signat... | 2 | null | Implement the Python class `TestePesquisaAnonima` described below.
Class description:
Testes para a classe PesquisaAnonima
Method signatures and docstrings:
- def test_resposta_unica(self): Testa se uma única resposta é armazenada de forma apropriada.
- def test_tres_respostas(self): Testa se três respostas individua... | Implement the Python class `TestePesquisaAnonima` described below.
Class description:
Testes para a classe PesquisaAnonima
Method signatures and docstrings:
- def test_resposta_unica(self): Testa se uma única resposta é armazenada de forma apropriada.
- def test_tres_respostas(self): Testa se três respostas individua... | de88ba326cdd9c17a456161cdb2f9ca69f7da65e | <|skeleton|>
class TestePesquisaAnonima:
"""Testes para a classe PesquisaAnonima"""
def test_resposta_unica(self):
"""Testa se uma única resposta é armazenada de forma apropriada."""
<|body_0|>
def test_tres_respostas(self):
"""Testa se três respostas individuais são armazenadas de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestePesquisaAnonima:
"""Testes para a classe PesquisaAnonima"""
def test_resposta_unica(self):
"""Testa se uma única resposta é armazenada de forma apropriada."""
pergunta = 'Qual a primeira língua que você aprendeu a falar?'
minha_pesquisa = PesquisaAnonima(pergunta=pergunta)
... | the_stack_v2_python_sparse | PYTHON/Python-Estudos/testes_pesquisa_00.py | sourcery-ai-bot/Estudos | train | 0 |
7f2edde26123b4f99e7470659c9d41dacdc15d16 | [
"if root is None:\n return None\nif root is p or root is q:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif left is None:\n return right\nelif right is None:\n return left\nelse:\n return root",
"if root is None:\n return ... | <|body_start_0|>
if root is None:
return None
if root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left is None:
return right
elif right is None:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor1(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"... | stack_v2_sparse_classes_75kplus_train_074406 | 1,835 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowest... | 3 | stack_v2_sparse_classes_30k_train_011835 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor1(self, root, p, q): :type root: T... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lowestCommonAncestor(self, root, p, q): :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode
- def lowestCommonAncestor1(self, root, p, q): :type root: T... | 945274c5f1385415b2839da53a921d3e23f7efa3 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor1(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if root is None:
return None
if root is p or root is q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
... | the_stack_v2_python_sparse | leetcode/leetcode_236.py | reach950/data-structure-algorithm-in-python | train | 0 | |
59d39fdcc2b24b90dceb996c889af5de25eb65da | [
"\"\"\"\n Thoughts:\n 这个方法没有left和right子树为None的情况进行对比会出现问题.\n \"\"\"\nif not self.isEqualNode(root1, root2):\n return False\nif not self.isEqualNode(root1.left, root2.left):\n root1.left, root1.right = (root1.right, root1.left)\nreturn self.flipEquiv(root1.left, root2.left) and self.flipEq... | <|body_start_0|>
"""
Thoughts:
这个方法没有left和right子树为None的情况进行对比会出现问题.
"""
if not self.isEqualNode(root1, root2):
return False
if not self.isEqualNode(root1.left, root2.left):
root1.left, root1.right = (root1.right, root1.left)... | Solution_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def isEqualNode(self, root1, root2):
"""return True if root1.val == root2.val"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
""... | stack_v2_sparse_classes_75kplus_train_074407 | 3,565 | no_license | [
{
"docstring": ":type root1: TreeNode :type root2: TreeNode :rtype: bool",
"name": "flipEquiv",
"signature": "def flipEquiv(self, root1, root2)"
},
{
"docstring": "return True if root1.val == root2.val",
"name": "isEqualNode",
"signature": "def isEqualNode(self, root1, root2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010057 | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def isEqualNode(self, root1, root2): return True if root1.val == root2.val | Implement the Python class `Solution_1` described below.
Class description:
Implement the Solution_1 class.
Method signatures and docstrings:
- def flipEquiv(self, root1, root2): :type root1: TreeNode :type root2: TreeNode :rtype: bool
- def isEqualNode(self, root1, root2): return True if root1.val == root2.val
<|sk... | f96a2273c6831a8035e1adacfa452f73c599ae16 | <|skeleton|>
class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
<|body_0|>
def isEqualNode(self, root1, root2):
"""return True if root1.val == root2.val"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution_1:
def flipEquiv(self, root1, root2):
""":type root1: TreeNode :type root2: TreeNode :rtype: bool"""
"""
Thoughts:
这个方法没有left和right子树为None的情况进行对比会出现问题.
"""
if not self.isEqualNode(root1, root2):
return False
i... | the_stack_v2_python_sparse | Python/FlipEquivalentBinaryTrees.py | here0009/LeetCode | train | 1 | |
852592373ddb19250e93c83ea058f0521ed99b8c | [
"for idx in range(len(nums)):\n high = min(len(nums), idx + k + 1)\n demoset = set(nums[idx + 1:high])\n if nums[idx] in demoset:\n return True\nreturn False",
"\"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\nnumDict = {}\nfor i in range(len(nums)... | <|body_start_0|>
for idx in range(len(nums)):
high = min(len(nums), idx + k + 1)
demoset = set(nums[idx + 1:high])
if nums[idx] in demoset:
return True
return False
<|end_body_0|>
<|body_start_1|>
"""
:type nums: List[int]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_75kplus_train_074408 | 843 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate",
"signature": "def containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "containsNearbyDuplicate2",
"signature": "def contai... | 2 | stack_v2_sparse_classes_30k_train_037627 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def containsNearbyDuplicate2(self, nums, k): :type nums: List[int] :type k: int :rty... | 829f918a0d4d94da5fd3004768421974fbe056e7 | <|skeleton|>
class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def containsNearbyDuplicate2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
for idx in range(len(nums)):
high = min(len(nums), idx + k + 1)
demoset = set(nums[idx + 1:high])
if nums[idx] in demoset:
return True... | the_stack_v2_python_sparse | leetcode/easy/easy 201-400/219_存在重复元素 II.py | Weikoi/OJ_Python | train | 0 | |
247359405b89f3e88fb6252469f378519163222a | [
"ctx_.dy = parent_ctx.dy\nctx_.save_for_backward(*input_)\njacobian = _evaluate_grad_matrix('jacobian')\nreturn jacobian",
"hessian = _evaluate_grad_matrix('hessian')\nif torch.squeeze(ddy).ndim > 1:\n vhp = ctx_.dy.view(1, -1) @ ddy @ hessian @ ctx_.dy.view(-1, 1)\nelse:\n vhp = ddy @ hessian\nvhp = torch.... | <|body_start_0|>
ctx_.dy = parent_ctx.dy
ctx_.save_for_backward(*input_)
jacobian = _evaluate_grad_matrix('jacobian')
return jacobian
<|end_body_0|>
<|body_start_1|>
hessian = _evaluate_grad_matrix('hessian')
if torch.squeeze(ddy).ndim > 1:
vhp = ctx_.dy.view... | _Jacobian | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Jacobian:
def forward(ctx_, parent_ctx, *input_):
"""Implements the forward pass QNode Jacobian evaluation"""
<|body_0|>
def backward(ctx_, ddy):
"""Implements the backward pass QNode vector-Hessian product"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074409 | 11,340 | permissive | [
{
"docstring": "Implements the forward pass QNode Jacobian evaluation",
"name": "forward",
"signature": "def forward(ctx_, parent_ctx, *input_)"
},
{
"docstring": "Implements the backward pass QNode vector-Hessian product",
"name": "backward",
"signature": "def backward(ctx_, ddy)"
}
] | 2 | stack_v2_sparse_classes_30k_train_048331 | Implement the Python class `_Jacobian` described below.
Class description:
Implement the _Jacobian class.
Method signatures and docstrings:
- def forward(ctx_, parent_ctx, *input_): Implements the forward pass QNode Jacobian evaluation
- def backward(ctx_, ddy): Implements the backward pass QNode vector-Hessian produ... | Implement the Python class `_Jacobian` described below.
Class description:
Implement the _Jacobian class.
Method signatures and docstrings:
- def forward(ctx_, parent_ctx, *input_): Implements the forward pass QNode Jacobian evaluation
- def backward(ctx_, ddy): Implements the backward pass QNode vector-Hessian produ... | 0c1c805fd5dfce465a8955ee3faf81037023a23e | <|skeleton|>
class _Jacobian:
def forward(ctx_, parent_ctx, *input_):
"""Implements the forward pass QNode Jacobian evaluation"""
<|body_0|>
def backward(ctx_, ddy):
"""Implements the backward pass QNode vector-Hessian product"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Jacobian:
def forward(ctx_, parent_ctx, *input_):
"""Implements the forward pass QNode Jacobian evaluation"""
ctx_.dy = parent_ctx.dy
ctx_.save_for_backward(*input_)
jacobian = _evaluate_grad_matrix('jacobian')
return jacobian
def backward(ctx_, ddy):
"""I... | the_stack_v2_python_sparse | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#1426/before/torch.py | MattePalte/Bugs-Quantum-Computing-Platforms | train | 4 | |
a62605feffd48ef6f7304bc24756a5a4b1823308 | [
"self.mask_array = mask_array\nself.number_of_roi = number_of_roi\nself.results = results",
"StructureSetROISequence = pydicom.sequence.Sequence()\nfor number_roi in range(1, self.number_of_roi + 1):\n dataset = pydicom.dataset.Dataset()\n dataset.ROINumber = number_roi\n dataset.ReferencedFrameOfReferen... | <|body_start_0|>
self.mask_array = mask_array
self.number_of_roi = number_of_roi
self.results = results
<|end_body_0|>
<|body_start_1|>
StructureSetROISequence = pydicom.sequence.Sequence()
for number_roi in range(1, self.number_of_roi + 1):
dataset = pydicom.dataset... | a class to represent StructureSetROISequence | StructureSetROISequence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StructureSetROISequence:
"""a class to represent StructureSetROISequence"""
def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int):
"""constructor Args: mask_array (np.ndarray): [mask ndarray] results (dict): [dict generated by 'generate_dict.py'] number_of_roi... | stack_v2_sparse_classes_75kplus_train_074410 | 2,708 | permissive | [
{
"docstring": "constructor Args: mask_array (np.ndarray): [mask ndarray] results (dict): [dict generated by 'generate_dict.py'] number_of_roi (int): [total number of ROI]",
"name": "__init__",
"signature": "def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int)"
},
{
"doc... | 3 | stack_v2_sparse_classes_30k_train_007456 | Implement the Python class `StructureSetROISequence` described below.
Class description:
a class to represent StructureSetROISequence
Method signatures and docstrings:
- def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int): constructor Args: mask_array (np.ndarray): [mask ndarray] results (di... | Implement the Python class `StructureSetROISequence` described below.
Class description:
a class to represent StructureSetROISequence
Method signatures and docstrings:
- def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int): constructor Args: mask_array (np.ndarray): [mask ndarray] results (di... | 56619b47877ad912d7fe33616d6596ce542705bb | <|skeleton|>
class StructureSetROISequence:
"""a class to represent StructureSetROISequence"""
def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int):
"""constructor Args: mask_array (np.ndarray): [mask ndarray] results (dict): [dict generated by 'generate_dict.py'] number_of_roi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class StructureSetROISequence:
"""a class to represent StructureSetROISequence"""
def __init__(self, mask_array: np.ndarray, results: dict, number_of_roi: int):
"""constructor Args: mask_array (np.ndarray): [mask ndarray] results (dict): [dict generated by 'generate_dict.py'] number_of_roi (int): [tota... | the_stack_v2_python_sparse | dicom_to_cnn/model/segmentation/rtstruct/StructureSetROISequence.py | wendyrvllr/Dicom-To-CNN | train | 0 |
7b6b9273e8f1d5648db3d263762a115be41afbfa | [
"self.edge_to = [None for _ in range(G.V)]\nself.dist_to = [float('inf') for _ in range(G.V)]\nself.marked = [False for _ in range(G.V)]\nself.pq = IndexMinPQ()\nself.dist_to[0] = 0.0\nself.pq.insert(0, 0.0)\nwhile self.pq:\n self.visit(G, self.pq.del_min())",
"self.marked[v] = True\nfor e in G.adj[v]:\n w ... | <|body_start_0|>
self.edge_to = [None for _ in range(G.V)]
self.dist_to = [float('inf') for _ in range(G.V)]
self.marked = [False for _ in range(G.V)]
self.pq = IndexMinPQ()
self.dist_to[0] = 0.0
self.pq.insert(0, 0.0)
while self.pq:
self.visit(G, self... | PrimMst | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrimMst:
def __init__(self, G):
"""Args: G: EdgeWeightedEdge"""
<|body_0|>
def visit(self, G, v):
"""将顶点v添加到树中, 更新数据 Args: G: EdgeWeightedGraph v: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.edge_to = [None for _ in range(G.V)]
... | stack_v2_sparse_classes_75kplus_train_074411 | 1,332 | no_license | [
{
"docstring": "Args: G: EdgeWeightedEdge",
"name": "__init__",
"signature": "def __init__(self, G)"
},
{
"docstring": "将顶点v添加到树中, 更新数据 Args: G: EdgeWeightedGraph v: int",
"name": "visit",
"signature": "def visit(self, G, v)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004929 | Implement the Python class `PrimMst` described below.
Class description:
Implement the PrimMst class.
Method signatures and docstrings:
- def __init__(self, G): Args: G: EdgeWeightedEdge
- def visit(self, G, v): 将顶点v添加到树中, 更新数据 Args: G: EdgeWeightedGraph v: int | Implement the Python class `PrimMst` described below.
Class description:
Implement the PrimMst class.
Method signatures and docstrings:
- def __init__(self, G): Args: G: EdgeWeightedEdge
- def visit(self, G, v): 将顶点v添加到树中, 更新数据 Args: G: EdgeWeightedGraph v: int
<|skeleton|>
class PrimMst:
def __init__(self, G):... | c4e5cce32826ae8ead955277b85f6b3377286d51 | <|skeleton|>
class PrimMst:
def __init__(self, G):
"""Args: G: EdgeWeightedEdge"""
<|body_0|>
def visit(self, G, v):
"""将顶点v添加到树中, 更新数据 Args: G: EdgeWeightedGraph v: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PrimMst:
def __init__(self, G):
"""Args: G: EdgeWeightedEdge"""
self.edge_to = [None for _ in range(G.V)]
self.dist_to = [float('inf') for _ in range(G.V)]
self.marked = [False for _ in range(G.V)]
self.pq = IndexMinPQ()
self.dist_to[0] = 0.0
self.pq.ins... | the_stack_v2_python_sparse | code/chapter4/PrimMST.py | AiZhanghan/Algorithms-Fourth-Edition | train | 0 | |
4b5138967c1399153a6017b312fffa391e733bdc | [
"dt = datetime(2017, 11, 22, 1, 0)\ncycletime = '20171122T0100Z'\nresult = datetime_to_cycletime(dt)\nself.assertIsInstance(result, str)\nself.assertEqual(result, cycletime)",
"dt = datetime(2017, 11, 22, 1, 0)\ncycletime = '201711220100'\nresult = datetime_to_cycletime(dt, cycletime_format='%Y%m%d%H%M')\nself.as... | <|body_start_0|>
dt = datetime(2017, 11, 22, 1, 0)
cycletime = '20171122T0100Z'
result = datetime_to_cycletime(dt)
self.assertIsInstance(result, str)
self.assertEqual(result, cycletime)
<|end_body_0|>
<|body_start_1|>
dt = datetime(2017, 11, 22, 1, 0)
cycletime =... | Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ. | Test_datetime_to_cycletime | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
<|body_0|>
def test_define_cycletime_format(self... | stack_v2_sparse_classes_75kplus_train_074412 | 19,622 | permissive | [
{
"docstring": "Test that a datetime object is returned of the expected value.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test when a cycletime is defined.",
"name": "test_define_cycletime_format",
"signature": "def test_define_cycletime_format(self)"
... | 3 | stack_v2_sparse_classes_30k_test_001427 | Implement the Python class `Test_datetime_to_cycletime` described below.
Class description:
Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ.
Method signatures and docstrings:
- def test_basic(self): Test that a datetime object is returned of the expected value.
- def t... | Implement the Python class `Test_datetime_to_cycletime` described below.
Class description:
Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ.
Method signatures and docstrings:
- def test_basic(self): Test that a datetime object is returned of the expected value.
- def t... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
<|body_0|>
def test_define_cycletime_format(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_datetime_to_cycletime:
"""Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ."""
def test_basic(self):
"""Test that a datetime object is returned of the expected value."""
dt = datetime(2017, 11, 22, 1, 0)
cycletime = '20171122T01... | the_stack_v2_python_sparse | improver_tests/utilities/temporal/test_temporal.py | metoppv/improver | train | 101 |
a41b1df91bfb4a684d6d908af56644acef1f0e43 | [
"self._unwrapped = DrivingAgentEnv()\nsuper().__init__(self._unwrapped)\ndims_shape = (len(WEATHER), len(CAR_CONDITION))\nself.nm_encoder = partial(np.ravel_multi_index, dims=dims_shape)\nself.nm_decoder = partial(np.unravel_index, shape=dims_shape)\nself.observation_space = Discrete(np.prod(dims_shape))",
"weath... | <|body_start_0|>
self._unwrapped = DrivingAgentEnv()
super().__init__(self._unwrapped)
dims_shape = (len(WEATHER), len(CAR_CONDITION))
self.nm_encoder = partial(np.ravel_multi_index, dims=dims_shape)
self.nm_decoder = partial(np.unravel_index, shape=dims_shape)
self.obser... | Non-Markovian version of the "Driving agent" environment. | NonMarkovianDrivingAgentEnv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NonMarkovianDrivingAgentEnv:
"""Non-Markovian version of the "Driving agent" environment."""
def __init__(self):
"""Initialize the enviornment."""
<|body_0|>
def _process(self, observation):
"""Process observation by removing road status."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_074413 | 5,627 | no_license | [
{
"docstring": "Initialize the enviornment.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Process observation by removing road status.",
"name": "_process",
"signature": "def _process(self, observation)"
},
{
"docstring": "Reset the environment.",
... | 4 | stack_v2_sparse_classes_30k_test_002715 | Implement the Python class `NonMarkovianDrivingAgentEnv` described below.
Class description:
Non-Markovian version of the "Driving agent" environment.
Method signatures and docstrings:
- def __init__(self): Initialize the enviornment.
- def _process(self, observation): Process observation by removing road status.
- d... | Implement the Python class `NonMarkovianDrivingAgentEnv` described below.
Class description:
Non-Markovian version of the "Driving agent" environment.
Method signatures and docstrings:
- def __init__(self): Initialize the enviornment.
- def _process(self, observation): Process observation by removing road status.
- d... | b516ffa46e9df6a67fbda7546f9128c23920c460 | <|skeleton|>
class NonMarkovianDrivingAgentEnv:
"""Non-Markovian version of the "Driving agent" environment."""
def __init__(self):
"""Initialize the enviornment."""
<|body_0|>
def _process(self, observation):
"""Process observation by removing road status."""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NonMarkovianDrivingAgentEnv:
"""Non-Markovian version of the "Driving agent" environment."""
def __init__(self):
"""Initialize the enviornment."""
self._unwrapped = DrivingAgentEnv()
super().__init__(self._unwrapped)
dims_shape = (len(WEATHER), len(CAR_CONDITION))
... | the_stack_v2_python_sparse | src/envs/driving_agent.py | marcofavorito/PAC-RDPs-code | train | 2 |
005e82747d80348c953b99e0be6367fbbde8e836 | [
"self.host = host\nself.port = port\nself.connection = None\nself.database = None\nself.product = None\nself.customer = None\nself.rental = None",
"if self.connection is None:\n try:\n self.connection = MongoClient(self.host, self.port)\n LOGGER.info('connected to mongo')\n LOGGER.info('en... | <|body_start_0|>
self.host = host
self.port = port
self.connection = None
self.database = None
self.product = None
self.customer = None
self.rental = None
<|end_body_0|>
<|body_start_1|>
if self.connection is None:
try:
self.co... | establish MongoDB connection (per assignment's example) | MongoDBConnection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
<|body_0|>
def __enter__(self):
"""enter"""
<|body_1|>
def __exit__(self, exc_type... | stack_v2_sparse_classes_75kplus_train_074414 | 7,711 | no_license | [
{
"docstring": "use public ip-address and port",
"name": "__init__",
"signature": "def __init__(self, host='127.0.0.1', port=27017)"
},
{
"docstring": "enter",
"name": "__enter__",
"signature": "def __enter__(self)"
},
{
"docstring": "exit",
"name": "__exit__",
"signature... | 3 | stack_v2_sparse_classes_30k_train_040685 | Implement the Python class `MongoDBConnection` described below.
Class description:
establish MongoDB connection (per assignment's example)
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port=27017): use public ip-address and port
- def __enter__(self): enter
- def __exit__(self, exc_type, ex... | Implement the Python class `MongoDBConnection` described below.
Class description:
establish MongoDB connection (per assignment's example)
Method signatures and docstrings:
- def __init__(self, host='127.0.0.1', port=27017): use public ip-address and port
- def __enter__(self): enter
- def __exit__(self, exc_type, ex... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
<|body_0|>
def __enter__(self):
"""enter"""
<|body_1|>
def __exit__(self, exc_type... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MongoDBConnection:
"""establish MongoDB connection (per assignment's example)"""
def __init__(self, host='127.0.0.1', port=27017):
"""use public ip-address and port"""
self.host = host
self.port = port
self.connection = None
self.database = None
self.produc... | the_stack_v2_python_sparse | students/florentin_popescu/Lesson_09/database.py | JavaRod/SP_Python220B_2019 | train | 1 |
fe1a36e4c30fe9144eb4a0c821777f731cd90a76 | [
"clusters = ['a0370', 'a1689', 'a1835', 'a2218', 'a2219', 'a2390', 'cl0024', 'ms0451', 'ms1054', 'ms1358', 'rxj0152', 'rxj1347']\nself.beam = [get_spire_beam_fwhm('PSW'), get_spire_beam_fwhm('PMW'), get_spire_beam_fwhm('PLW')]\nself.verbose = verbose\nself.saveplot = saveplot\nself.maketf = maketf\nself.sgen = sgen... | <|body_start_0|>
clusters = ['a0370', 'a1689', 'a1835', 'a2218', 'a2219', 'a2390', 'cl0024', 'ms0451', 'ms1054', 'ms1358', 'rxj0152', 'rxj1347']
self.beam = [get_spire_beam_fwhm('PSW'), get_spire_beam_fwhm('PMW'), get_spire_beam_fwhm('PLW')]
self.verbose = verbose
self.saveplot = saveplo... | Catsrc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Catsrc:
def __init__(self, clusname, isim=None, saveplot=1, maketf=0, sgen=None, verbose=1, resolution='nr', superplot=0, testflag=2, lense_only=0):
"""initializing function for catsrc class Purpose: read in arguments to be passed to functions in catsrc. Inputs : Clusname - the name of t... | stack_v2_sparse_classes_75kplus_train_074415 | 10,865 | no_license | [
{
"docstring": "initializing function for catsrc class Purpose: read in arguments to be passed to functions in catsrc. Inputs : Clusname - the name of the galaxy cluster saveplot - flag to set if you want to save plots to a file maketf - make transfer function flag (currently not used) sgen - flag for looking a... | 4 | stack_v2_sparse_classes_30k_train_009724 | Implement the Python class `Catsrc` described below.
Class description:
Implement the Catsrc class.
Method signatures and docstrings:
- def __init__(self, clusname, isim=None, saveplot=1, maketf=0, sgen=None, verbose=1, resolution='nr', superplot=0, testflag=2, lense_only=0): initializing function for catsrc class Pu... | Implement the Python class `Catsrc` described below.
Class description:
Implement the Catsrc class.
Method signatures and docstrings:
- def __init__(self, clusname, isim=None, saveplot=1, maketf=0, sgen=None, verbose=1, resolution='nr', superplot=0, testflag=2, lense_only=0): initializing function for catsrc class Pu... | a74894cb06e50d5d5db9a253455fe9df3f0c0dc4 | <|skeleton|>
class Catsrc:
def __init__(self, clusname, isim=None, saveplot=1, maketf=0, sgen=None, verbose=1, resolution='nr', superplot=0, testflag=2, lense_only=0):
"""initializing function for catsrc class Purpose: read in arguments to be passed to functions in catsrc. Inputs : Clusname - the name of t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Catsrc:
def __init__(self, clusname, isim=None, saveplot=1, maketf=0, sgen=None, verbose=1, resolution='nr', superplot=0, testflag=2, lense_only=0):
"""initializing function for catsrc class Purpose: read in arguments to be passed to functions in catsrc. Inputs : Clusname - the name of the galaxy clus... | the_stack_v2_python_sparse | catsrc.py | rit-rsz/rsz | train | 4 | |
1cd7a2279fa533cf0affc8a4b5a7b5762130b48a | [
"self.points = points\nself.nPoints = len(self.points)\nself.solve()",
"A = [[1 * self.points[i][0], 1] for i in range(self.nPoints)]\nA = np.array(A, dtype='float64')\nb = [self.points[i][1] for i in range(self.nPoints)]\nb = np.array(b, dtype='float64')\nresults = np.linalg.solve(A, b)\nself.results = results",... | <|body_start_0|>
self.points = points
self.nPoints = len(self.points)
self.solve()
<|end_body_0|>
<|body_start_1|>
A = [[1 * self.points[i][0], 1] for i in range(self.nPoints)]
A = np.array(A, dtype='float64')
b = [self.points[i][1] for i in range(self.nPoints)]
... | Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0 | LinearInterpolation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearInterpolation:
"""Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0"""
def __init__(self, points):
"""Keyword Arguments: - points - tuple of points that will be used for interpolation."""
<|body_0|>
def solve(self) -> list:
... | stack_v2_sparse_classes_75kplus_train_074416 | 1,853 | no_license | [
{
"docstring": "Keyword Arguments: - points - tuple of points that will be used for interpolation.",
"name": "__init__",
"signature": "def __init__(self, points)"
},
{
"docstring": "Solve the linear system using numpy linalg solve method and returns the scalars to `self.result` attr used for P a... | 4 | null | Implement the Python class `LinearInterpolation` described below.
Class description:
Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0
Method signatures and docstrings:
- def __init__(self, points): Keyword Arguments: - points - tuple of points that will be used for interpolation... | Implement the Python class `LinearInterpolation` described below.
Class description:
Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0
Method signatures and docstrings:
- def __init__(self, points): Keyword Arguments: - points - tuple of points that will be used for interpolation... | ca41d38bd2b9db7f177a01b2a159fa40a12a1f23 | <|skeleton|>
class LinearInterpolation:
"""Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0"""
def __init__(self, points):
"""Keyword Arguments: - points - tuple of points that will be used for interpolation."""
<|body_0|>
def solve(self) -> list:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LinearInterpolation:
"""Class for solve Linear Interpolation problems. Author: Medeiros Gilberto Version: 0.1.0"""
def __init__(self, points):
"""Keyword Arguments: - points - tuple of points that will be used for interpolation."""
self.points = points
self.nPoints = len(self.poin... | the_stack_v2_python_sparse | IFSC/Calculo Numerico/numapy-master/interpolation/linear.py | HidoiOokami/Projects-Python | train | 0 |
e2b6fcdb10f659aba4f0941d17d3d9500875dff9 | [
"g.sort()\ns.sort()\ng_length = len(g) - 1\ngave_cookies = 0\nfor select_cookie in s:\n if gave_cookies > g_length:\n break\n elif g[gave_cookies] <= select_cookie:\n gave_cookies += 1\nreturn gave_cookies",
"g.sort()\ns.sort()\nchild = 0\ncookie = 0\nwhile child < len(g) and cookie < len(s):\... | <|body_start_0|>
g.sort()
s.sort()
g_length = len(g) - 1
gave_cookies = 0
for select_cookie in s:
if gave_cookies > g_length:
break
elif g[gave_cookies] <= select_cookie:
gave_cookies += 1
return gave_cookies
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_0|>
def findContentChildren2(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074417 | 1,966 | no_license | [
{
"docstring": ":type g: List[int] :type s: List[int] :rtype: int",
"name": "findContentChildren",
"signature": "def findContentChildren(self, g, s)"
},
{
"docstring": ":type g: List[int] :type s: List[int] :rtype: int",
"name": "findContentChildren2",
"signature": "def findContentChildr... | 2 | stack_v2_sparse_classes_30k_train_046129 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
- def findContentChildren2(self, g, s): :type g: List[int] :type s: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findContentChildren(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
- def findContentChildren2(self, g, s): :type g: List[int] :type s: List[int] :rtype: int
... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_0|>
def findContentChildren2(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def findContentChildren(self, g, s):
""":type g: List[int] :type s: List[int] :rtype: int"""
g.sort()
s.sort()
g_length = len(g) - 1
gave_cookies = 0
for select_cookie in s:
if gave_cookies > g_length:
break
elif... | the_stack_v2_python_sparse | Problems/0400_0499/0455_Assign_Cookies/Project_Python3/Assign_Cookies.py | NobuyukiInoue/LeetCode | train | 0 | |
a990c98909e931384cd0a1197181ac066d559bc4 | [
"username = self.cleaned_data['username']\ntry:\n User._default_manager.get(username=username)\nexcept User.DoesNotExist:\n return username\nraise forms.ValidationError(_(u'该昵称已经被使用'))",
"password = self.cleaned_data['password']\nrepassword = self.cleaned_data['repassword']\nif password and repassword and (... | <|body_start_0|>
username = self.cleaned_data['username']
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_(u'该昵称已经被使用'))
<|end_body_0|>
<|body_start_1|>
password = self.cleaned_data[... | 注册表单 | RegisterForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证昵称"""
<|body_0|>
def clean_repassword(self):
"""验证两次输入密码"""
<|body_1|>
def clean_email(self):
"""验证email"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
username = self... | stack_v2_sparse_classes_75kplus_train_074418 | 2,370 | no_license | [
{
"docstring": "验证昵称",
"name": "clean_username",
"signature": "def clean_username(self)"
},
{
"docstring": "验证两次输入密码",
"name": "clean_repassword",
"signature": "def clean_repassword(self)"
},
{
"docstring": "验证email",
"name": "clean_email",
"signature": "def clean_email(s... | 3 | stack_v2_sparse_classes_30k_train_007362 | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证昵称
- def clean_repassword(self): 验证两次输入密码
- def clean_email(self): 验证email | Implement the Python class `RegisterForm` described below.
Class description:
注册表单
Method signatures and docstrings:
- def clean_username(self): 验证昵称
- def clean_repassword(self): 验证两次输入密码
- def clean_email(self): 验证email
<|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证昵称"... | 5a7869f589d608c1748a7a58c54478a2c87675ee | <|skeleton|>
class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证昵称"""
<|body_0|>
def clean_repassword(self):
"""验证两次输入密码"""
<|body_1|>
def clean_email(self):
"""验证email"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RegisterForm:
"""注册表单"""
def clean_username(self):
"""验证昵称"""
username = self.cleaned_data['username']
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_(u'该昵称已经被使用'))
... | the_stack_v2_python_sparse | accounts/forms.py | chivyzhuang/Bugless | train | 0 |
912c90c58095803598c17d621284f4b6ac6e2ab3 | [
"chapterMapping = super()._get_chapterMapping(chId, chapterNumber)\nif self.novel.chapters[chId].suppressChapterTitle:\n chapterMapping['Title'] = ''\nreturn chapterMapping",
"sceneMapping = super()._get_sceneMapping(scId, sceneNumber, wordsTotal, lettersTotal)\nsceneMapping['Summary'] = _('Summary')\nreturn s... | <|body_start_0|>
chapterMapping = super()._get_chapterMapping(chId, chapterNumber)
if self.novel.chapters[chId].suppressChapterTitle:
chapterMapping['Title'] = ''
return chapterMapping
<|end_body_0|>
<|body_start_1|>
sceneMapping = super()._get_sceneMapping(scId, sceneNumber... | ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes. | OdtWManuscript | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int... | stack_v2_sparse_classes_75kplus_train_074419 | 3,448 | permissive | [
{
"docstring": "Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int -- chapter number. Suppress the chapter title if necessary. Extends the superclass method.",
"name": "_get_chapterMapping",
"signature": "def _get_chapterMapping(self, chI... | 2 | stack_v2_sparse_classes_30k_train_036002 | Implement the Python class `OdtWManuscript` described below.
Class description:
ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes.
Method signatures and docstrings:
- def _get_chapterMapping(self, chId, chapterNumber): Return a mapping dictionary for a chapter section. Position... | Implement the Python class `OdtWManuscript` described below.
Class description:
ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes.
Method signatures and docstrings:
- def _get_chapterMapping(self, chId, chapterNumber): Return a mapping dictionary for a chapter section. Position... | 33a868daed653c3371f5991d243a034668a80884 | <|skeleton|>
class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OdtWManuscript:
"""ODT manuscript file writer. Export a manuscript with invisibly tagged chapters and scenes."""
def _get_chapterMapping(self, chId, chapterNumber):
"""Return a mapping dictionary for a chapter section. Positional arguments: chId: str -- chapter ID. chapterNumber: int -- chapter n... | the_stack_v2_python_sparse | src/pywriter/odt_w/odt_w_manuscript.py | peter88213/PyWriter | train | 3 |
f068238f44d66169f7d98fdbb4afcb52104b6c63 | [
"if 'sep' in kwargs:\n sep = kwargs.pop('sep')\nelse:\n sep = ';'\nself.fill_values = dict() if fill_values is None else fill_values\nself.df = pd.read_csv(station_meta_csv, sep=sep, **kwargs)",
"vars = []\nfor var in varnames:\n if var in self.fill_values.keys() and (not (var.endswith('_depth_from') or ... | <|body_start_0|>
if 'sep' in kwargs:
sep = kwargs.pop('sep')
else:
sep = ';'
self.fill_values = dict() if fill_values is None else fill_values
self.df = pd.read_csv(station_meta_csv, sep=sep, **kwargs)
<|end_body_0|>
<|body_start_1|>
vars = []
for... | Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_from;<var1>_depth_to;<var2>;... - where network and ... | CustomStationMetadataCsv | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_... | stack_v2_sparse_classes_75kplus_train_074420 | 8,725 | permissive | [
{
"docstring": "Parameters ---------- station_meta_csv: str Path to the csv file with the above described content fill_values: dict, optional (default: None) Values to use for a certain custom metadata variable, if no match is found. kwargs: Additional kwargs as passed to :func:`pandas.read_csv` To use a differ... | 4 | stack_v2_sparse_classes_30k_train_039691 | Implement the Python class `CustomStationMetadataCsv` described below.
Class description:
Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structur... | Implement the Python class `CustomStationMetadataCsv` described below.
Class description:
Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structur... | 66d798089ff5bd97ad9892f24bf903a8e97be620 | <|skeleton|>
class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CustomStationMetadataCsv:
"""Allows passing (static) metadata for ISMN stations as a csv file. E.g. if the station specific variables provided by the ISMN are not enough. In this case that the metadata must be stored in a csv file with the following structure: network;station;<var1>;<var1>_depth_from;<var1>_d... | the_stack_v2_python_sparse | src/ismn/custom.py | TUW-GEO/ismn | train | 20 |
0c537649fc89f3a6db7c05b8ef1c75265fe7524d | [
"if reflection_table.get_flags(reflection_table.flags.integrated_prf).count(True) == 0:\n raise NoProfilesException('WARNING: No profile-integrated reflections found')\nselection = reflection_table.get_flags(reflection_table.flags.integrated, all=True)\nreflection_table = reflection_table.select(selection)\nlogg... | <|body_start_0|>
if reflection_table.get_flags(reflection_table.flags.integrated_prf).count(True) == 0:
raise NoProfilesException('WARNING: No profile-integrated reflections found')
selection = reflection_table.get_flags(reflection_table.flags.integrated, all=True)
reflection_table =... | Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained. | SumAndPrfIntensityReducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SumAndPrfIntensityReducer:
"""Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by sum and prf methods."""... | stack_v2_sparse_classes_75kplus_train_074421 | 38,270 | permissive | [
{
"docstring": "Select reflections successfully integrated by sum and prf methods.",
"name": "reduce_on_intensities",
"signature": "def reduce_on_intensities(reflection_table)"
},
{
"docstring": "Apply corrections to the intensities and variances (partiality, lp, qe).",
"name": "apply_scalin... | 2 | stack_v2_sparse_classes_30k_test_000155 | Implement the Python class `SumAndPrfIntensityReducer` described below.
Class description:
Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select refle... | Implement the Python class `SumAndPrfIntensityReducer` described below.
Class description:
Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained.
Method signatures and docstrings:
- def reduce_on_intensities(reflection_table): Select refle... | 88bf7f7c5ac44defc046ebf0719cde748092cfff | <|skeleton|>
class SumAndPrfIntensityReducer:
"""Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by sum and prf methods."""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SumAndPrfIntensityReducer:
"""Reduction methods for data with sum and profile intensities. Only reflections with valid values for all intensity types are retained."""
def reduce_on_intensities(reflection_table):
"""Select reflections successfully integrated by sum and prf methods."""
if r... | the_stack_v2_python_sparse | src/dials/util/filter_reflections.py | dials/dials | train | 71 |
a6bc8be51e79feac69dfd407e8396f5214f848e9 | [
"cwd = os.getcwd()\nadded, errors = database.import_data(cwd, 'products.csv', 'customers.csv', 'rentals.csv')\nself.assertEqual(added, (3, 3, 4))\nself.assertEqual(errors, (0, 0, 0))\nadd_tuple, error_tuple = database.import_data(cwd, 'p.csv', 'c.csv', 'r.csv')\nself.assertEqual(add_tuple, (0, 0, 0))\nself.assertEq... | <|body_start_0|>
cwd = os.getcwd()
added, errors = database.import_data(cwd, 'products.csv', 'customers.csv', 'rentals.csv')
self.assertEqual(added, (3, 3, 4))
self.assertEqual(errors, (0, 0, 0))
add_tuple, error_tuple = database.import_data(cwd, 'p.csv', 'c.csv', 'r.csv')
... | Class for testing database functions | TestDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDatabase:
"""Class for testing database functions"""
def test_import_data(self):
"""Test import_data function"""
<|body_0|>
def test_show_available_products(self):
"""Test show_available_products functions"""
<|body_1|>
def test_show_rentals(self... | stack_v2_sparse_classes_75kplus_train_074422 | 2,178 | no_license | [
{
"docstring": "Test import_data function",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "Test show_available_products functions",
"name": "test_show_available_products",
"signature": "def test_show_available_products(self)"
},
{
"docstr... | 3 | null | Implement the Python class `TestDatabase` described below.
Class description:
Class for testing database functions
Method signatures and docstrings:
- def test_import_data(self): Test import_data function
- def test_show_available_products(self): Test show_available_products functions
- def test_show_rentals(self): T... | Implement the Python class `TestDatabase` described below.
Class description:
Class for testing database functions
Method signatures and docstrings:
- def test_import_data(self): Test import_data function
- def test_show_available_products(self): Test show_available_products functions
- def test_show_rentals(self): T... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestDatabase:
"""Class for testing database functions"""
def test_import_data(self):
"""Test import_data function"""
<|body_0|>
def test_show_available_products(self):
"""Test show_available_products functions"""
<|body_1|>
def test_show_rentals(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDatabase:
"""Class for testing database functions"""
def test_import_data(self):
"""Test import_data function"""
cwd = os.getcwd()
added, errors = database.import_data(cwd, 'products.csv', 'customers.csv', 'rentals.csv')
self.assertEqual(added, (3, 3, 4))
self.... | the_stack_v2_python_sparse | students/matt_casali/lesson05/assignment/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
99a9a0217d9bca72912c2ea87655806f2dcc35a1 | [
"import category_encoders as ce\nif cat_features is None:\n cat_features = train_df.select_dtypes(include=['object', 'category', 'bool']).columns.to_list()\ncount_enc = ce.CountEncoder(cols=cat_features)\ncount_enc.fit(train_df[cat_features])\ntrain_encoded = train_df.join(count_enc.transform(train_df[cat_featur... | <|body_start_0|>
import category_encoders as ce
if cat_features is None:
cat_features = train_df.select_dtypes(include=['object', 'category', 'bool']).columns.to_list()
count_enc = ce.CountEncoder(cols=cat_features)
count_enc.fit(train_df[cat_features])
train_encoded ... | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
def count_encoder(train_df, valid_df, cat_features=None):
"""Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kaggle.com/matleonard/categorical-encodings"""
<|body_0|>
def target_encoder(train_df,... | stack_v2_sparse_classes_75kplus_train_074423 | 19,449 | no_license | [
{
"docstring": "Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kaggle.com/matleonard/categorical-encodings",
"name": "count_encoder",
"signature": "def count_encoder(train_df, valid_df, cat_features=None)"
},
{
"docstring": ... | 4 | stack_v2_sparse_classes_30k_train_008950 | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def count_encoder(train_df, valid_df, cat_features=None): Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kag... | Implement the Python class `Encoder` described below.
Class description:
Implement the Encoder class.
Method signatures and docstrings:
- def count_encoder(train_df, valid_df, cat_features=None): Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kag... | 44cd6fafb503665df8a2d5030f427f11b10025e5 | <|skeleton|>
class Encoder:
def count_encoder(train_df, valid_df, cat_features=None):
"""Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kaggle.com/matleonard/categorical-encodings"""
<|body_0|>
def target_encoder(train_df,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Encoder:
def count_encoder(train_df, valid_df, cat_features=None):
"""Count_Encoding: カテゴリ列をカウント値に変換する特徴量エンジニアリング(要はgroupby().size()の集計列追加のこと) ※カウント数が同じカテゴリは同じようなデータ傾向になる可能性がある https://www.kaggle.com/matleonard/categorical-encodings"""
import category_encoders as ce
if cat_features is ... | the_stack_v2_python_sparse | code/train_nn.py | riron1206/Probspace_geme_compe | train | 0 | |
433d5359539e34642a6d972c07f705c9f5c3ba2d | [
"stack = []\nans = 0\nfor i, a in enumerate(A):\n ans += a\n left = 0\n right = 0\n while stack and stack[-1][0] >= a:\n temp = stack.pop()\n left += temp[1] + 1\n ans += (temp[1] + right + temp[1] * right) * temp[0]\n ans %= 10 ** 9 + 7\n right += temp[1] + 1\n sta... | <|body_start_0|>
stack = []
ans = 0
for i, a in enumerate(A):
ans += a
left = 0
right = 0
while stack and stack[-1][0] >= a:
temp = stack.pop()
left += temp[1] + 1
ans += (temp[1] + right + temp[1] * ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sumSubarrayMins(self, A):
""":type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边"""
<|body_0|>
def sumSubarrayMins_1(self, A):
"""444ms :param A: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
stack =... | stack_v2_sparse_classes_75kplus_train_074424 | 2,125 | no_license | [
{
"docstring": ":type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边",
"name": "sumSubarrayMins",
"signature": "def sumSubarrayMins(self, A)"
},
{
"docstring": "444ms :param A: :return:",
"name": "sumSubarrayMins_1",
"signature": "def sumSubarrayMins_1(self, A)"
... | 2 | stack_v2_sparse_classes_30k_val_002876 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumSubarrayMins(self, A): :type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边
- def sumSubarrayMins_1(self, A): 444ms :param A: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sumSubarrayMins(self, A): :type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边
- def sumSubarrayMins_1(self, A): 444ms :param A: :return:
<|skeleton|... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def sumSubarrayMins(self, A):
""":type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边"""
<|body_0|>
def sumSubarrayMins_1(self, A):
"""444ms :param A: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def sumSubarrayMins(self, A):
""":type A: List[int] :rtype: int 208 ms # 记录左右两边能扩展的最大位置,第一次向前记录左边,stack跳出记录右边"""
stack = []
ans = 0
for i, a in enumerate(A):
ans += a
left = 0
right = 0
while stack and stack[-1][0] >= a:... | the_stack_v2_python_sparse | SumOfSubarrayMinimums_MID_907.py | 953250587/leetcode-python | train | 2 | |
86e1ca70e8644629d1bed819ecd00acd20bd069d | [
"self.a = a\nself.n = len(a)\nfor i in reversed(range(self.n // 2)):\n self.sink(i)",
"lv = rv = -(1 << 31)\nif 2 * ix + 1 < self.n:\n lv = self.a[2 * ix + 1]\nif 2 * ix + 2 < self.n:\n rv = self.a[2 * ix + 2]\nif lv >= rv and lv > self.a[ix]:\n self.a[ix], self.a[2 * ix + 1] = (self.a[2 * ix + 1], se... | <|body_start_0|>
self.a = a
self.n = len(a)
for i in reversed(range(self.n // 2)):
self.sink(i)
<|end_body_0|>
<|body_start_1|>
lv = rv = -(1 << 31)
if 2 * ix + 1 < self.n:
lv = self.a[2 * ix + 1]
if 2 * ix + 2 < self.n:
rv = self.a[2 ... | MaxHeap | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxHeap:
def __init__(self, a):
""":param a: List[int]"""
<|body_0|>
def sink(self, ix):
""":param ix: :return:"""
<|body_1|>
def swim(self, ix):
""":param ix: :return:"""
<|body_2|>
def pop(self):
""":return:"""
<|bo... | stack_v2_sparse_classes_75kplus_train_074425 | 2,203 | no_license | [
{
"docstring": ":param a: List[int]",
"name": "__init__",
"signature": "def __init__(self, a)"
},
{
"docstring": ":param ix: :return:",
"name": "sink",
"signature": "def sink(self, ix)"
},
{
"docstring": ":param ix: :return:",
"name": "swim",
"signature": "def swim(self, ... | 5 | stack_v2_sparse_classes_30k_train_019786 | Implement the Python class `MaxHeap` described below.
Class description:
Implement the MaxHeap class.
Method signatures and docstrings:
- def __init__(self, a): :param a: List[int]
- def sink(self, ix): :param ix: :return:
- def swim(self, ix): :param ix: :return:
- def pop(self): :return:
- def insert(self, v): :par... | Implement the Python class `MaxHeap` described below.
Class description:
Implement the MaxHeap class.
Method signatures and docstrings:
- def __init__(self, a): :param a: List[int]
- def sink(self, ix): :param ix: :return:
- def swim(self, ix): :param ix: :return:
- def pop(self): :return:
- def insert(self, v): :par... | 8af637d35831f1da1f5007a88a39e3a9a87e8be8 | <|skeleton|>
class MaxHeap:
def __init__(self, a):
""":param a: List[int]"""
<|body_0|>
def sink(self, ix):
""":param ix: :return:"""
<|body_1|>
def swim(self, ix):
""":param ix: :return:"""
<|body_2|>
def pop(self):
""":return:"""
<|bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxHeap:
def __init__(self, a):
""":param a: List[int]"""
self.a = a
self.n = len(a)
for i in reversed(range(self.n // 2)):
self.sink(i)
def sink(self, ix):
""":param ix: :return:"""
lv = rv = -(1 << 31)
if 2 * ix + 1 < self.n:
... | the_stack_v2_python_sparse | page5/main215.py | feizhihui/LeetCode | train | 0 | |
3a21d16cf6ba406eec741a3c38080c363fa031ab | [
"if isinstance(f, Transform):\n return f\nelse:\n return cls(f)",
"self.mask, self.is_tuple = (mask, is_tuple)\nif encodes:\n self.encodes = encodes\n self.order = getattr(encodes, 'order', 0)"
] | <|body_start_0|>
if isinstance(f, Transform):
return f
else:
return cls(f)
<|end_body_0|>
<|body_start_1|>
self.mask, self.is_tuple = (mask, is_tuple)
if encodes:
self.encodes = encodes
self.order = getattr(encodes, 'order', 0)
<|end_body_... | "A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None | Transform | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cl... | stack_v2_sparse_classes_75kplus_train_074426 | 14,141 | no_license | [
{
"docstring": "purpose: - why `Transform.create`? 1. we need a slight revised version of __init__ 2. `@classmethod` help to create another __init__ without __init__ if `f` is already an instance of `Transform`, just return `f`; if not, turn `f` into a `Transform`",
"name": "create",
"signature": "def c... | 2 | stack_v2_sparse_classes_30k_train_041436 | Implement the Python class `Transform` described below.
Class description:
"A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`... | Implement the Python class `Transform` described below.
Class description:
"A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`... | 4230be915e70a7e5a22f2f7e5137cca7045754fd | <|skeleton|>
class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cl... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Transform:
""""A function that `encodes` if `filt` matches, and optionally `decodes`, with an optional `setup`" 1. every tfm's `order` default to 0 2. `assoc`, `is_tuple`, `prev` default to None 3. `filt`, `mask`, default to None 4. `_is_setup`,`_done_setup`, default to None"""
def create(cls, f, filt=No... | the_stack_v2_python_sparse | my_workstation/my-v2/data.pipeline.Transform.py | EmbraceLife/fastai_treasures | train | 21 |
4b29436e94b709d7724cc042d22f0b6786cbffcd | [
"try:\n body = self.get_json_request_body()\n group_name = body.get('group_name', None)\n if group_name:\n client = WeChatClient(WX_PUBLIC['APP_ID'], WX_PUBLIC['APP_SECRET'])\n res = client.group.create(group_name)\n if res:\n self.write(res)\n else:\n logg... | <|body_start_0|>
try:
body = self.get_json_request_body()
group_name = body.get('group_name', None)
if group_name:
client = WeChatClient(WX_PUBLIC['APP_ID'], WX_PUBLIC['APP_SECRET'])
res = client.group.create(group_name)
if res:... | 用户分组创建、查询用户分组 | WXGroupHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WXGroupHandler:
"""用户分组创建、查询用户分组"""
def do_post(self):
"""创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:"""
<|body_0|>
def do_get(self):
"""查询所有分组或查询用户所在分组 ID 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b16... | stack_v2_sparse_classes_75kplus_train_074427 | 8,866 | no_license | [
{
"docstring": "创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:",
"name": "do_post",
"signature": "def do_post(self)"
},
{
"docstring": "查询所有分组或查询用户所在分组 ID 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html",
"name": "do_get",
... | 2 | stack_v2_sparse_classes_30k_train_042363 | Implement the Python class `WXGroupHandler` described below.
Class description:
用户分组创建、查询用户分组
Method signatures and docstrings:
- def do_post(self): 创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:
- def do_get(self): 查询所有分组或查询用户所在分组 ID 参考 http://mp.weixin.qq.com/wiki/0/56d992c6... | Implement the Python class `WXGroupHandler` described below.
Class description:
用户分组创建、查询用户分组
Method signatures and docstrings:
- def do_post(self): 创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:
- def do_get(self): 查询所有分组或查询用户所在分组 ID 参考 http://mp.weixin.qq.com/wiki/0/56d992c6... | 9cbe81eea34039068c9d0771eae617791ccbdef9 | <|skeleton|>
class WXGroupHandler:
"""用户分组创建、查询用户分组"""
def do_post(self):
"""创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:"""
<|body_0|>
def do_get(self):
"""查询所有分组或查询用户所在分组 ID 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b16... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WXGroupHandler:
"""用户分组创建、查询用户分组"""
def do_post(self):
"""创建用户分组 参考 http://mp.weixin.qq.com/wiki/0/56d992c605a97245eb7e617854b169fc.html :return:"""
try:
body = self.get_json_request_body()
group_name = body.get('group_name', None)
if group_name:
... | the_stack_v2_python_sparse | web/pay_api/wx_public/wx_client_user.py | cash2one/payment-1 | train | 0 |
4c459062c6c5b868b35fa7761acf7675e5338b3e | [
"if not hasattr(self, '_body'):\n chunks = []\n async for chunk in self.stream():\n chunks.append(chunk)\n self.scope['_body'] = self._body = b''.join(chunks)\nreturn self._body",
"if not hasattr(self, '_json'):\n body = await self.body()\n if b'\\\\u0000' in body:\n raise ValueError(... | <|body_start_0|>
if not hasattr(self, '_body'):
chunks = []
async for chunk in self.stream():
chunks.append(chunk)
self.scope['_body'] = self._body = b''.join(chunks)
return self._body
<|end_body_0|>
<|body_start_1|>
if not hasattr(self, '_jso... | SafeRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SafeRequest:
async def body(self) -> bytes:
"""Read the body like normal but store it in the request scope for use in error handling middleware."""
<|body_0|>
async def json(self) -> str:
"""Like the super json method, but will raise an error if null bytes are found ... | stack_v2_sparse_classes_75kplus_train_074428 | 1,564 | permissive | [
{
"docstring": "Read the body like normal but store it in the request scope for use in error handling middleware.",
"name": "body",
"signature": "async def body(self) -> bytes"
},
{
"docstring": "Like the super json method, but will raise an error if null bytes are found in the JSON, also use uj... | 2 | null | Implement the Python class `SafeRequest` described below.
Class description:
Implement the SafeRequest class.
Method signatures and docstrings:
- async def body(self) -> bytes: Read the body like normal but store it in the request scope for use in error handling middleware.
- async def json(self) -> str: Like the sup... | Implement the Python class `SafeRequest` described below.
Class description:
Implement the SafeRequest class.
Method signatures and docstrings:
- async def body(self) -> bytes: Read the body like normal but store it in the request scope for use in error handling middleware.
- async def json(self) -> str: Like the sup... | 2c31c1180d6e1a96bffb668921104ce730b46a9c | <|skeleton|>
class SafeRequest:
async def body(self) -> bytes:
"""Read the body like normal but store it in the request scope for use in error handling middleware."""
<|body_0|>
async def json(self) -> str:
"""Like the super json method, but will raise an error if null bytes are found ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SafeRequest:
async def body(self) -> bytes:
"""Read the body like normal but store it in the request scope for use in error handling middleware."""
if not hasattr(self, '_body'):
chunks = []
async for chunk in self.stream():
chunks.append(chunk)
... | the_stack_v2_python_sparse | foxglove/route_class.py | samuelcolvin/foxglove | train | 37 | |
1159da8d1e2b221f3c16e01a7eaa552bffd1dadb | [
"v1 = SCons.Node.Python.Value('a')\nassert v1.value == 'a', v1.value\nvalue2 = 'a'\nv2 = SCons.Node.Python.Value(value2)\nassert v2.value == value2, v2.value\nassert v2.value is value2, v2.value\nassert v1 is not v2\nassert v1.value == v2.value\nv3 = SCons.Node.Python.Value('c', 'cb')\nassert v3.built_value == 'cb'... | <|body_start_0|>
v1 = SCons.Node.Python.Value('a')
assert v1.value == 'a', v1.value
value2 = 'a'
v2 = SCons.Node.Python.Value(value2)
assert v2.value == value2, v2.value
assert v2.value is value2, v2.value
assert v1 is not v2
assert v1.value == v2.value
... | ValueTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ValueTestCase:
def test_Value(self) -> None:
"""Test creating a Value() object"""
<|body_0|>
def test_build(self) -> None:
"""Test "building" a Value Node"""
<|body_1|>
def test_read(self) -> None:
"""Test the Value.read() method"""
<|bod... | stack_v2_sparse_classes_75kplus_train_074429 | 6,319 | permissive | [
{
"docstring": "Test creating a Value() object",
"name": "test_Value",
"signature": "def test_Value(self) -> None"
},
{
"docstring": "Test \"building\" a Value Node",
"name": "test_build",
"signature": "def test_build(self) -> None"
},
{
"docstring": "Test the Value.read() method... | 5 | stack_v2_sparse_classes_30k_test_001032 | Implement the Python class `ValueTestCase` described below.
Class description:
Implement the ValueTestCase class.
Method signatures and docstrings:
- def test_Value(self) -> None: Test creating a Value() object
- def test_build(self) -> None: Test "building" a Value Node
- def test_read(self) -> None: Test the Value.... | Implement the Python class `ValueTestCase` described below.
Class description:
Implement the ValueTestCase class.
Method signatures and docstrings:
- def test_Value(self) -> None: Test creating a Value() object
- def test_build(self) -> None: Test "building" a Value Node
- def test_read(self) -> None: Test the Value.... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class ValueTestCase:
def test_Value(self) -> None:
"""Test creating a Value() object"""
<|body_0|>
def test_build(self) -> None:
"""Test "building" a Value Node"""
<|body_1|>
def test_read(self) -> None:
"""Test the Value.read() method"""
<|bod... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ValueTestCase:
def test_Value(self) -> None:
"""Test creating a Value() object"""
v1 = SCons.Node.Python.Value('a')
assert v1.value == 'a', v1.value
value2 = 'a'
v2 = SCons.Node.Python.Value(value2)
assert v2.value == value2, v2.value
assert v2.value is ... | the_stack_v2_python_sparse | SCons/Node/PythonTests.py | SCons/scons | train | 1,827 | |
38464c5c9a564b96f5de4ed8abfd219e816e1310 | [
"super(FocalLoss, self).__init__()\nself.alpha: float = alpha\nself.gamma: Optional[float] = gamma\nself.reduction: Optional[str] = reduction\nself.eps: float = 1e-06",
"if not torch.is_tensor(input):\n raise TypeError('Input type is not a torch.Tensor. Got {}'.format(type(input)))\nif not len(input.shape) == ... | <|body_start_0|>
super(FocalLoss, self).__init__()
self.alpha: float = alpha
self.gamma: Optional[float] = gamma
self.reduction: Optional[str] = reduction
self.eps: float = 1e-06
<|end_body_0|>
<|body_start_1|>
if not torch.is_tensor(input):
raise TypeError('... | FocalLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
def __init__(self, alpha: float, gamma: Optional[float]=2.0, reduction: Optional[str]='none') -> None:
"""[Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py] Args: alpha (float): [alpha hyperparameter for focal loss] gamma (Opti... | stack_v2_sparse_classes_75kplus_train_074430 | 9,281 | no_license | [
{
"docstring": "[Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py] Args: alpha (float): [alpha hyperparameter for focal loss] gamma (Optional[float], optional): [gamma hyperparams]. Defaults to 2.0. reduction (Optional[str], optional): [reduction type]. Defaults... | 2 | null | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha: float, gamma: Optional[float]=2.0, reduction: Optional[str]='none') -> None: [Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/mas... | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha: float, gamma: Optional[float]=2.0, reduction: Optional[str]='none') -> None: [Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/mas... | 554252d271be78d59adb019613283f09edf395ad | <|skeleton|>
class FocalLoss:
def __init__(self, alpha: float, gamma: Optional[float]=2.0, reduction: Optional[str]='none') -> None:
"""[Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py] Args: alpha (float): [alpha hyperparameter for focal loss] gamma (Opti... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FocalLoss:
def __init__(self, alpha: float, gamma: Optional[float]=2.0, reduction: Optional[str]='none') -> None:
"""[Focal Loss Class. Hacked from: https://github.com/kornia/kornia/blob/master/kornia/losses/focal.py] Args: alpha (float): [alpha hyperparameter for focal loss] gamma (Optional[float], o... | the_stack_v2_python_sparse | loss.py | prinzROSE/sslad | train | 0 | |
6cbe661344667bb9da2f9af6092b7e7c7c042951 | [
"data_in = {'indent': 0, 'body': 'notatag', 'filename': '', 'line': 0}\nres = TagToken.make(data_in)\nself.assertFalse(res)",
"data_in = {'indent': 0, 'body': 'p:', 'filename': '', 'line': 0}\ntoken = TagToken.make(data_in)\nself.assertTrue(token)\nself.assertEqual(token.tagname, 'p')\nself.assertFalse(token.cont... | <|body_start_0|>
data_in = {'indent': 0, 'body': 'notatag', 'filename': '', 'line': 0}
res = TagToken.make(data_in)
self.assertFalse(res)
<|end_body_0|>
<|body_start_1|>
data_in = {'indent': 0, 'body': 'p:', 'filename': '', 'line': 0}
token = TagToken.make(data_in)
self.... | TagTokenTestCase | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagTokenTestCase:
def testMakeNoMatch(self):
"""no match - no token"""
<|body_0|>
def testMakeBareTag(self):
"""tag only - no content or atts"""
<|body_1|>
def testMakeTagWithContent(self):
"""tag with content but no atts"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_074431 | 39,836 | permissive | [
{
"docstring": "no match - no token",
"name": "testMakeNoMatch",
"signature": "def testMakeNoMatch(self)"
},
{
"docstring": "tag only - no content or atts",
"name": "testMakeBareTag",
"signature": "def testMakeBareTag(self)"
},
{
"docstring": "tag with content but no atts",
"... | 6 | stack_v2_sparse_classes_30k_test_003005 | Implement the Python class `TagTokenTestCase` described below.
Class description:
Implement the TagTokenTestCase class.
Method signatures and docstrings:
- def testMakeNoMatch(self): no match - no token
- def testMakeBareTag(self): tag only - no content or atts
- def testMakeTagWithContent(self): tag with content but... | Implement the Python class `TagTokenTestCase` described below.
Class description:
Implement the TagTokenTestCase class.
Method signatures and docstrings:
- def testMakeNoMatch(self): no match - no token
- def testMakeBareTag(self): tag only - no content or atts
- def testMakeTagWithContent(self): tag with content but... | 430d6dfd719f8c88a4c3de2b735f8736187ff19b | <|skeleton|>
class TagTokenTestCase:
def testMakeNoMatch(self):
"""no match - no token"""
<|body_0|>
def testMakeBareTag(self):
"""tag only - no content or atts"""
<|body_1|>
def testMakeTagWithContent(self):
"""tag with content but no atts"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TagTokenTestCase:
def testMakeNoMatch(self):
"""no match - no token"""
data_in = {'indent': 0, 'body': 'notatag', 'filename': '', 'line': 0}
res = TagToken.make(data_in)
self.assertFalse(res)
def testMakeBareTag(self):
"""tag only - no content or atts"""
da... | the_stack_v2_python_sparse | evoke/nevo/test.py | howiemac/evoke | train | 0 | |
ff6868c40b4bd30e0e3d2654f6f0ff7f5eb29cda | [
"try:\n dhcpController = DhcpController()\n json_data = json.dumps(dhcpController.get_dhcp_server_configuration_subnet())\n resp = Response(json_data, status=200, mimetype='application/json')\n return resp\nexcept ValueError as ve:\n return Response(json.dumps(str(ve)), status=404, mimetype='applicat... | <|body_start_0|>
try:
dhcpController = DhcpController()
json_data = json.dumps(dhcpController.get_dhcp_server_configuration_subnet())
resp = Response(json_data, status=200, mimetype='application/json')
return resp
except ValueError as ve:
retur... | DhcpServer_Configuration_Subnet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DhcpServer_Configuration_Subnet:
def get(self):
"""Gets the subnet parameter"""
<|body_0|>
def put(self):
"""Update the subnet parameter"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
dhcpController = DhcpController()
j... | stack_v2_sparse_classes_75kplus_train_074432 | 20,424 | no_license | [
{
"docstring": "Gets the subnet parameter",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Update the subnet parameter",
"name": "put",
"signature": "def put(self)"
}
] | 2 | null | Implement the Python class `DhcpServer_Configuration_Subnet` described below.
Class description:
Implement the DhcpServer_Configuration_Subnet class.
Method signatures and docstrings:
- def get(self): Gets the subnet parameter
- def put(self): Update the subnet parameter | Implement the Python class `DhcpServer_Configuration_Subnet` described below.
Class description:
Implement the DhcpServer_Configuration_Subnet class.
Method signatures and docstrings:
- def get(self): Gets the subnet parameter
- def put(self): Update the subnet parameter
<|skeleton|>
class DhcpServer_Configuration_S... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class DhcpServer_Configuration_Subnet:
def get(self):
"""Gets the subnet parameter"""
<|body_0|>
def put(self):
"""Update the subnet parameter"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DhcpServer_Configuration_Subnet:
def get(self):
"""Gets the subnet parameter"""
try:
dhcpController = DhcpController()
json_data = json.dumps(dhcpController.get_dhcp_server_configuration_subnet())
resp = Response(json_data, status=200, mimetype='application/... | the_stack_v2_python_sparse | configuration-agent/dhcp/rest_api/resources/dhcp_server.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
76858d8ed3bf6b2c0d6a0bf1ea6101e5ef57a931 | [
"self.datastore_id = datastore_id\nself.file_restore_info = file_restore_info\nself.name = name\nself.objects = objects\nself.protection_source_name = protection_source_name\nself.start_time_usecs = start_time_usecs\nself.mtype = mtype\nself.username = username",
"if dictionary is None:\n return None\ndatastor... | <|body_start_0|>
self.datastore_id = datastore_id
self.file_restore_info = file_restore_info
self.name = name
self.objects = objects
self.protection_source_name = protection_source_name
self.start_time_usecs = start_time_usecs
self.mtype = mtype
self.usern... | Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's files are recovered to. This field is populated when objects are rec... | RestoreSourceSummaryByObjectTypeElement | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreSourceSummaryByObjectTypeElement:
"""Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's f... | stack_v2_sparse_classes_75kplus_train_074433 | 6,343 | permissive | [
{
"docstring": "Constructor for the RestoreSourceSummaryByObjectTypeElement class",
"name": "__init__",
"signature": "def __init__(self, datastore_id=None, file_restore_info=None, name=None, objects=None, protection_source_name=None, start_time_usecs=None, mtype=None, username=None)"
},
{
"docst... | 2 | stack_v2_sparse_classes_30k_train_023218 | Implement the Python class `RestoreSourceSummaryByObjectTypeElement` described below.
Class description:
Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Speci... | Implement the Python class `RestoreSourceSummaryByObjectTypeElement` described below.
Class description:
Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Speci... | 0093194d125fc6746f55b8499da1270c64f473fc | <|skeleton|>
class RestoreSourceSummaryByObjectTypeElement:
"""Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RestoreSourceSummaryByObjectTypeElement:
"""Implementation of the 'RestoreSourceSummaryByObjectTypeElement' model. RestoreSourceSummaryByObjectTypeElement represents a recover/clone summary for a single object type. Attributes: datastore_id (long|int): Specifies the datastore where the object's files are reco... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_source_summary_by_object_type_element.py | hsantoyo2/management-sdk-python | train | 0 |
9bbf90c88f1744026911054c586a696d05a0bded | [
"cur = head\nwhile cur:\n runner = cur.next\n while runner and runner.val == cur.val:\n runner = runner.next\n cur.next = runner\n cur = runner\nreturn head",
"if not head:\n return head\nif head.next:\n if head.val == head.next.val:\n head = self.deleteDuplicates2(head.next)\n ... | <|body_start_0|>
cur = head
while cur:
runner = cur.next
while runner and runner.val == cur.val:
runner = runner.next
cur.next = runner
cur = runner
return head
<|end_body_0|>
<|body_start_1|>
if not head:
retur... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cur = head
while c... | stack_v2_sparse_classes_75kplus_train_074434 | 874 | permissive | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates2",
"signature": "def deleteDuplicates2(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009876 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates2(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 4dc4e6642dc92f1983c13564cc0fd99917cab358 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates2(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
cur = head
while cur:
runner = cur.next
while runner and runner.val == cur.val:
runner = runner.next
cur.next = runner
cur = runner
... | the_stack_v2_python_sparse | Python/remove-duplicates-from-sorted-list.py | kamyu104/LeetCode-Solutions | train | 4,549 | |
0ca18030f0d39e6fba58c4ddb1ac45ccc277e674 | [
"if settings.DEBUG:\n return True\nelse:\n return False",
"if settings.DEBUG:\n return True\nelse:\n return False"
] | <|body_start_0|>
if settings.DEBUG:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if settings.DEBUG:
return True
else:
return False
<|end_body_1|>
| ContactsAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactsAdmin:
def has_add_permission(self, *args, **kwargs):
"""Запрещаем добавлять новые экземпляры Contacts при DEBUG=False"""
<|body_0|>
def has_delete_permission(self, *args, **kwargs):
"""Запрещаем удалять экземпляры Contacts при DEBUG=False"""
<|body_1... | stack_v2_sparse_classes_75kplus_train_074435 | 1,855 | no_license | [
{
"docstring": "Запрещаем добавлять новые экземпляры Contacts при DEBUG=False",
"name": "has_add_permission",
"signature": "def has_add_permission(self, *args, **kwargs)"
},
{
"docstring": "Запрещаем удалять экземпляры Contacts при DEBUG=False",
"name": "has_delete_permission",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_020036 | Implement the Python class `ContactsAdmin` described below.
Class description:
Implement the ContactsAdmin class.
Method signatures and docstrings:
- def has_add_permission(self, *args, **kwargs): Запрещаем добавлять новые экземпляры Contacts при DEBUG=False
- def has_delete_permission(self, *args, **kwargs): Запреща... | Implement the Python class `ContactsAdmin` described below.
Class description:
Implement the ContactsAdmin class.
Method signatures and docstrings:
- def has_add_permission(self, *args, **kwargs): Запрещаем добавлять новые экземпляры Contacts при DEBUG=False
- def has_delete_permission(self, *args, **kwargs): Запреща... | c76996698bbbd88309ed35f47d19e09fec19eb94 | <|skeleton|>
class ContactsAdmin:
def has_add_permission(self, *args, **kwargs):
"""Запрещаем добавлять новые экземпляры Contacts при DEBUG=False"""
<|body_0|>
def has_delete_permission(self, *args, **kwargs):
"""Запрещаем удалять экземпляры Contacts при DEBUG=False"""
<|body_1... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ContactsAdmin:
def has_add_permission(self, *args, **kwargs):
"""Запрещаем добавлять новые экземпляры Contacts при DEBUG=False"""
if settings.DEBUG:
return True
else:
return False
def has_delete_permission(self, *args, **kwargs):
"""Запрещаем удалят... | the_stack_v2_python_sparse | www/contacts/admin.py | boogiiieee/Victoria | train | 0 | |
843340b87c5e03db2f5f9389b0b1d3328436b965 | [
"super(FeatureExtractor, self).__init__()\nself.sa_module_1 = PointNet_SA_Module_KNN(512, 16, 3, [64, 128], group_all=False, if_bn=False, if_idx=True)\nself.transformer_1 = Transformer(128, dim=64)\nself.sa_module_2 = PointNet_SA_Module_KNN(128, 16, 128, [128, 256], group_all=False, if_bn=False, if_idx=True)\nself.... | <|body_start_0|>
super(FeatureExtractor, self).__init__()
self.sa_module_1 = PointNet_SA_Module_KNN(512, 16, 3, [64, 128], group_all=False, if_bn=False, if_idx=True)
self.transformer_1 = Transformer(128, dim=64)
self.sa_module_2 = PointNet_SA_Module_KNN(128, 16, 128, [128, 256], group_al... | FeatureExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExtractor:
def __init__(self, out_dim=1024):
"""Encoder that encodes information of partial point cloud"""
<|body_0|>
def forward(self, point_cloud):
"""Args: point_cloud: b, 3, n Returns: l3_points: (B, out_dim, 1)"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_75kplus_train_074436 | 6,896 | permissive | [
{
"docstring": "Encoder that encodes information of partial point cloud",
"name": "__init__",
"signature": "def __init__(self, out_dim=1024)"
},
{
"docstring": "Args: point_cloud: b, 3, n Returns: l3_points: (B, out_dim, 1)",
"name": "forward",
"signature": "def forward(self, point_cloud... | 2 | stack_v2_sparse_classes_30k_train_022740 | Implement the Python class `FeatureExtractor` described below.
Class description:
Implement the FeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, out_dim=1024): Encoder that encodes information of partial point cloud
- def forward(self, point_cloud): Args: point_cloud: b, 3, n Returns: l3... | Implement the Python class `FeatureExtractor` described below.
Class description:
Implement the FeatureExtractor class.
Method signatures and docstrings:
- def __init__(self, out_dim=1024): Encoder that encodes information of partial point cloud
- def forward(self, point_cloud): Args: point_cloud: b, 3, n Returns: l3... | 2b3859f04c30550dc4222db329377237d2e6b38c | <|skeleton|>
class FeatureExtractor:
def __init__(self, out_dim=1024):
"""Encoder that encodes information of partial point cloud"""
<|body_0|>
def forward(self, point_cloud):
"""Args: point_cloud: b, 3, n Returns: l3_points: (B, out_dim, 1)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FeatureExtractor:
def __init__(self, out_dim=1024):
"""Encoder that encodes information of partial point cloud"""
super(FeatureExtractor, self).__init__()
self.sa_module_1 = PointNet_SA_Module_KNN(512, 16, 3, [64, 128], group_all=False, if_bn=False, if_idx=True)
self.transforme... | the_stack_v2_python_sparse | models/model.py | eveybody2/SnowflakeNet | train | 1 | |
d0080a7269e8d96a6ea0d65fc893088ddc8bfc76 | [
"def single_max_number(a, k):\n drop = len(a) - k\n stack = []\n for x in a:\n while stack and drop > 0 and (x > stack[-1]):\n drop -= 1\n stack.pop()\n stack.append(x)\n return stack[:k]\n\ndef merge(a, b):\n a, b = (collections.deque(a), collections.deque(b))\n ... | <|body_start_0|>
def single_max_number(a, k):
drop = len(a) - k
stack = []
for x in a:
while stack and drop > 0 and (x > stack[-1]):
drop -= 1
stack.pop()
stack.append(x)
return stack[:k]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxNumber(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxNumber_DP(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]"""
... | stack_v2_sparse_classes_75kplus_train_074437 | 2,784 | no_license | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]",
"name": "maxNumber",
"signature": "def maxNumber(self, nums1, nums2, k)"
},
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]",
"name": "maxNumber_DP",
... | 2 | stack_v2_sparse_classes_30k_train_025856 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNumber(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]
- def maxNumber_DP(self, nums1, nums2, k): :type nums1: List[in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxNumber(self, nums1, nums2, k): :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]
- def maxNumber_DP(self, nums1, nums2, k): :type nums1: List[in... | 0a7aa09a2b95e4caca5b5123fb735ceb5c01e992 | <|skeleton|>
class Solution:
def maxNumber(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]"""
<|body_0|>
def maxNumber_DP(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxNumber(self, nums1, nums2, k):
""":type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int]"""
def single_max_number(a, k):
drop = len(a) - k
stack = []
for x in a:
while stack and drop > 0 and (x > stack[-... | the_stack_v2_python_sparse | create-maximum-number.py | onestarshang/leetcode | train | 0 | |
eca9b34b267e00712d798e7bdd47afb5cfbd5cdd | [
"super(PIDTimedLoop, self).__init__(period, num_period)\nself._pid = pid\nself._is_active = pid.poll() is None",
"if not self._is_active:\n raise StopIteration\ntry:\n self._pid.wait(timeout=timeout)\n self._is_active = False\nexcept subprocess.TimeoutExpired:\n pass"
] | <|body_start_0|>
super(PIDTimedLoop, self).__init__(period, num_period)
self._pid = pid
self._is_active = pid.poll() is None
<|end_body_0|>
<|body_start_1|>
if not self._is_active:
raise StopIteration
try:
self._pid.wait(timeout=timeout)
self.... | PIDTimedLoop | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PIDTimedLoop:
def __init__(self, pid, period, num_period=None):
"""Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of time intervals requested, and that the first iteration is not delayed. The total amount of time spanned... | stack_v2_sparse_classes_75kplus_train_074438 | 13,068 | permissive | [
{
"docstring": "Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of time intervals requested, and that the first iteration is not delayed. The total amount of time spanned by the loop is the product of the two input parameters. To create an infin... | 2 | stack_v2_sparse_classes_30k_train_033550 | Implement the Python class `PIDTimedLoop` described below.
Class description:
Implement the PIDTimedLoop class.
Method signatures and docstrings:
- def __init__(self, pid, period, num_period=None): Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of ti... | Implement the Python class `PIDTimedLoop` described below.
Class description:
Implement the PIDTimedLoop class.
Method signatures and docstrings:
- def __init__(self, pid, period, num_period=None): Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of ti... | 8acb57ab057104612e24d436a92c3fc1a1aa37c0 | <|skeleton|>
class PIDTimedLoop:
def __init__(self, pid, period, num_period=None):
"""Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of time intervals requested, and that the first iteration is not delayed. The total amount of time spanned... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PIDTimedLoop:
def __init__(self, pid, period, num_period=None):
"""Similar to the TimedLoop but stop when subprocess ends The number of loops executed is one greater than the number of time intervals requested, and that the first iteration is not delayed. The total amount of time spanned by the loop i... | the_stack_v2_python_sparse | service/geopmdpy/runtime.py | dannosliwcd/geopm | train | 0 | |
26cdefa93399ba83ec04ea9dd35d814b8f09b7b0 | [
"self._MySQL = mysql_instance\nself.sql_script = sql_script\nself.split_algo = split_algo\nself._prep_statements = prep_statements\nself._dump_fails = dump_fails\nself._execute_iters = 0",
"print('\\tRetrieving commands from', self.sql_script)\nprint('\\tUsing command splitter algorithm {0}'.format(self.split_alg... | <|body_start_0|>
self._MySQL = mysql_instance
self.sql_script = sql_script
self.split_algo = split_algo
self._prep_statements = prep_statements
self._dump_fails = dump_fails
self._execute_iters = 0
<|end_body_0|>
<|body_start_1|>
print('\tRetrieving commands from... | Execute | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Execute:
def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None):
"""Execute a sql file one command at a time."""
<|body_0|>
def commands(self):
"""Fetch individual SQL commands from a SQL commands conta... | stack_v2_sparse_classes_75kplus_train_074439 | 6,364 | permissive | [
{
"docstring": "Execute a sql file one command at a time.",
"name": "__init__",
"signature": "def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None)"
},
{
"docstring": "Fetch individual SQL commands from a SQL commands containing m... | 6 | stack_v2_sparse_classes_30k_train_019194 | Implement the Python class `Execute` described below.
Class description:
Implement the Execute class.
Method signatures and docstrings:
- def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None): Execute a sql file one command at a time.
- def commands(se... | Implement the Python class `Execute` described below.
Class description:
Implement the Execute class.
Method signatures and docstrings:
- def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None): Execute a sql file one command at a time.
- def commands(se... | 6964f718f4b72eb30f2259adfcfaf3090526c53d | <|skeleton|>
class Execute:
def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None):
"""Execute a sql file one command at a time."""
<|body_0|>
def commands(self):
"""Fetch individual SQL commands from a SQL commands conta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Execute:
def __init__(self, sql_script=None, split_algo='sql_split', prep_statements=True, dump_fails=True, mysql_instance=None):
"""Execute a sql file one command at a time."""
self._MySQL = mysql_instance
self.sql_script = sql_script
self.split_algo = split_algo
self.... | the_stack_v2_python_sparse | mysql/toolkit/commands/execute.py | sfneal/mysql-toolkit | train | 6 | |
da9fe439af3d65a216d67ba4ca0043025586241f | [
"self.qualifier = parent.get('qualifier', '')\nself.rtype = parent.get('rtype', [])\nself.red_index = parent.get('red_index', None)\nself.red_dim = parent.get('red_dim', None)\nself.apply_to = kwargs.get(self.qualifier + '_apply_to', kwargs.get('apply_to', []))\nif self.apply_to is None:\n self.apply_to = []\nif... | <|body_start_0|>
self.qualifier = parent.get('qualifier', '')
self.rtype = parent.get('rtype', [])
self.red_index = parent.get('red_index', None)
self.red_dim = parent.get('red_dim', None)
self.apply_to = kwargs.get(self.qualifier + '_apply_to', kwargs.get('apply_to', []))
... | InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype. | InvariantRtypeSampling | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvariantRtypeSampling:
"""InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype."""
def __init__(self, parent=dict(), **kwargs):
"""Initialize the sampler. [inputs] (parent=dict(), **kwargs) parent: object o... | stack_v2_sparse_classes_75kplus_train_074440 | 7,623 | permissive | [
{
"docstring": "Initialize the sampler. [inputs] (parent=dict(), **kwargs) parent: object or dictionary composed of the parent instantiation or namespace (e.g. class HyperManager from mner.solvers.manager.py) from which the sampler is instantiated. - qualifier: (default=\"\") string that preprends a prefix to t... | 2 | stack_v2_sparse_classes_30k_train_013474 | Implement the Python class `InvariantRtypeSampling` described below.
Class description:
InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype.
Method signatures and docstrings:
- def __init__(self, parent=dict(), **kwargs): Initialize the sam... | Implement the Python class `InvariantRtypeSampling` described below.
Class description:
InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype.
Method signatures and docstrings:
- def __init__(self, parent=dict(), **kwargs): Initialize the sam... | 97d2f67304478dcf6fb26294ed357f8c31601d01 | <|skeleton|>
class InvariantRtypeSampling:
"""InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype."""
def __init__(self, parent=dict(), **kwargs):
"""Initialize the sampler. [inputs] (parent=dict(), **kwargs) parent: object o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvariantRtypeSampling:
"""InvariantRtypeSampling (class) Sample a feasible point for invariant hyperparameters. See mner.solvers.constraints.InvariantRtype."""
def __init__(self, parent=dict(), **kwargs):
"""Initialize the sampler. [inputs] (parent=dict(), **kwargs) parent: object or dictionary ... | the_stack_v2_python_sparse | mner/solvers/samplers.py | jkaardal/mner | train | 5 |
9de05161892ec57b03094ba097e4bc9621a53e1b | [
"super(Record, self).__init__(dtype=PARA_RECORD, name=name, index=index, label=label, help=help, default=default, required=required, group=group)\nself.fields = dict()\nfor para in fields:\n if para.name in self.fields:\n raise err.InvalidParameterError(\"duplicate field '{}'\".format(para.name))\n sel... | <|body_start_0|>
super(Record, self).__init__(dtype=PARA_RECORD, name=name, index=index, label=label, help=help, default=default, required=required, group=group)
self.fields = dict()
for para in fields:
if para.name in self.fields:
raise err.InvalidParameterError("dup... | Record parameter type that associates parameter declarations for record components with unique keys. | Record | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Record:
"""Record parameter type that associates parameter declarations for record components with unique keys."""
def __init__(self, name: str, fields: List[Parameter], index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Dict]=None, required: Optio... | stack_v2_sparse_classes_75kplus_train_074441 | 6,520 | permissive | [
{
"docstring": "Initialize the base properties for a record parameter declaration. Parameters ---------- name: string Unique parameter identifier fields: list List of parameter declarations for record fields. The field name is the name of the respective parameter. index: int, default=0 Index position of the par... | 4 | stack_v2_sparse_classes_30k_train_030968 | Implement the Python class `Record` described below.
Class description:
Record parameter type that associates parameter declarations for record components with unique keys.
Method signatures and docstrings:
- def __init__(self, name: str, fields: List[Parameter], index: Optional[int]=0, label: Optional[str]=None, hel... | Implement the Python class `Record` described below.
Class description:
Record parameter type that associates parameter declarations for record components with unique keys.
Method signatures and docstrings:
- def __init__(self, name: str, fields: List[Parameter], index: Optional[int]=0, label: Optional[str]=None, hel... | 7116b7060aa68ab36bf08e6393be166dc5db955f | <|skeleton|>
class Record:
"""Record parameter type that associates parameter declarations for record components with unique keys."""
def __init__(self, name: str, fields: List[Parameter], index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Dict]=None, required: Optio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Record:
"""Record parameter type that associates parameter declarations for record components with unique keys."""
def __init__(self, name: str, fields: List[Parameter], index: Optional[int]=0, label: Optional[str]=None, help: Optional[str]=None, default: Optional[Dict]=None, required: Optional[bool]=Fal... | the_stack_v2_python_sparse | flowserv/model/parameter/record.py | anrunw/flowserv-core-1 | train | 0 |
b23ff4c5719c2d901651070229a616b6e3380c79 | [
"json_data = request.get_json()\nuser_data = user_schema.load(json_data, partial=('full_name', 'email', 'password'))\nuser = UserModel.find_user_by_mobile_number(mobile_number=json_data['mobile_number'])\nif not user:\n return ({'msg': USER_NOT_FOUND.format(json_data['mobile_number'])}, 404)\ntry:\n message =... | <|body_start_0|>
json_data = request.get_json()
user_data = user_schema.load(json_data, partial=('full_name', 'email', 'password'))
user = UserModel.find_user_by_mobile_number(mobile_number=json_data['mobile_number'])
if not user:
return ({'msg': USER_NOT_FOUND.format(json_da... | UserConfirm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserConfirm:
def post(cls):
"""Sends the OTP for activation. payload = { mobile_number:"********" }"""
<|body_0|>
def put(cls):
"""Confirms the registration of user and changing user.activated = True payload = { mobile_number:"********" }"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_074442 | 5,332 | no_license | [
{
"docstring": "Sends the OTP for activation. payload = { mobile_number:\"********\" }",
"name": "post",
"signature": "def post(cls)"
},
{
"docstring": "Confirms the registration of user and changing user.activated = True payload = { mobile_number:\"********\" }",
"name": "put",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_019358 | Implement the Python class `UserConfirm` described below.
Class description:
Implement the UserConfirm class.
Method signatures and docstrings:
- def post(cls): Sends the OTP for activation. payload = { mobile_number:"********" }
- def put(cls): Confirms the registration of user and changing user.activated = True pay... | Implement the Python class `UserConfirm` described below.
Class description:
Implement the UserConfirm class.
Method signatures and docstrings:
- def post(cls): Sends the OTP for activation. payload = { mobile_number:"********" }
- def put(cls): Confirms the registration of user and changing user.activated = True pay... | 857ce6e952dd223f8b9df46742c602780601f80a | <|skeleton|>
class UserConfirm:
def post(cls):
"""Sends the OTP for activation. payload = { mobile_number:"********" }"""
<|body_0|>
def put(cls):
"""Confirms the registration of user and changing user.activated = True payload = { mobile_number:"********" }"""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserConfirm:
def post(cls):
"""Sends the OTP for activation. payload = { mobile_number:"********" }"""
json_data = request.get_json()
user_data = user_schema.load(json_data, partial=('full_name', 'email', 'password'))
user = UserModel.find_user_by_mobile_number(mobile_number=js... | the_stack_v2_python_sparse | ONE VISA CONNECT/Customer/Backend/Customer Api/resources/user.py | tdhankhar/Contrivers_VISA_Hackathon_Project | train | 0 | |
aaa519df947752dc00da7b9fb879fec3a1177924 | [
"torch.set_num_threads(1)\ntorch.set_num_interop_threads(1)\nif isinstance(graphnet_modules, list):\n self._modules = graphnet_modules\nelse:\n self._modules = [graphnet_modules]\nself._gcd_file = gcd_file\nself._n_workers = n_workers",
"try:\n os.makedirs(output_folder)\nexcept FileExistsError:\n ass... | <|body_start_0|>
torch.set_num_threads(1)
torch.set_num_interop_threads(1)
if isinstance(graphnet_modules, list):
self._modules = graphnet_modules
else:
self._modules = [graphnet_modules]
self._gcd_file = gcd_file
self._n_workers = n_workers
<|end_... | Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules. | GraphNeTI3Deployer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initial... | stack_v2_sparse_classes_75kplus_train_074443 | 6,500 | permissive | [
{
"docstring": "Initialize the deployer. Will apply graphnet i3 modules to i3 files in the order in which they appear in graphnet_modules.Each module is run independently. Args: graphnet_modules: List of graphnet i3 modules. Order of appearence in the list determines order of deployment. gcd_file: path to gcd f... | 5 | stack_v2_sparse_classes_30k_train_046019 | Implement the Python class `GraphNeTI3Deployer` described below.
Class description:
Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules.
Method signatures and docstrings:
- def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Mo... | Implement the Python class `GraphNeTI3Deployer` described below.
Class description:
Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules.
Method signatures and docstrings:
- def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Mo... | f6e03282dd665c81d06eaa1ab55a07d138064e9a | <|skeleton|>
class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initial... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphNeTI3Deployer:
"""Deploys graphnet i3 modules to i3 files. Modules are applied in the order in which they appear in graphnet_modules."""
def __init__(self, graphnet_modules: Union[GraphNeTI3Module, Sequence[GraphNeTI3Module]], gcd_file: str, n_workers: int=1) -> None:
"""Initialize the deplo... | the_stack_v2_python_sparse | src/graphnet/deployment/i3modules/deployer.py | graphnet-team/graphnet | train | 55 |
148cb3a6d2caf569427fe09e5974594e7dfdc026 | [
"super().__init__(model_dir, *args, **kwargs)\nfrom modelscope.trainers.nlp.space.trainer.gen_trainer import MultiWOZTrainer\nself.model_dir = model_dir\nself.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))\nimport torch\nself.config.use_gpu = True if ('device'... | <|body_start_0|>
super().__init__(model_dir, *args, **kwargs)
from modelscope.trainers.nlp.space.trainer.gen_trainer import MultiWOZTrainer
self.model_dir = model_dir
self.config = kwargs.pop('config', Config.from_file(os.path.join(self.model_dir, ModelFile.CONFIGURATION)))
impor... | SpaceForDialogModeling | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpaceForDialogModeling:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The model path. text_field (`BPETextField`, *optional*, defaults to `MultiWOZBPETextField`): The text field. config (`C... | stack_v2_sparse_classes_75kplus_train_074444 | 4,353 | permissive | [
{
"docstring": "initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The model path. text_field (`BPETextField`, *optional*, defaults to `MultiWOZBPETextField`): The text field. config (`Config`, *optional*, defaults to config in model hub): The config.",
"name": "__init_... | 2 | stack_v2_sparse_classes_30k_train_045793 | Implement the Python class `SpaceForDialogModeling` described below.
Class description:
Implement the SpaceForDialogModeling class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The mode... | Implement the Python class `SpaceForDialogModeling` described below.
Class description:
Implement the SpaceForDialogModeling class.
Method signatures and docstrings:
- def __init__(self, model_dir: str, *args, **kwargs): initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The mode... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class SpaceForDialogModeling:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The model path. text_field (`BPETextField`, *optional*, defaults to `MultiWOZBPETextField`): The text field. config (`C... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpaceForDialogModeling:
def __init__(self, model_dir: str, *args, **kwargs):
"""initialize the test generation model from the `model_dir` path. Args: model_dir (`str`): The model path. text_field (`BPETextField`, *optional*, defaults to `MultiWOZBPETextField`): The text field. config (`Config`, *optio... | the_stack_v2_python_sparse | ai/modelscope/modelscope/models/nlp/space/dialog_modeling.py | alldatacenter/alldata | train | 774 | |
3e27bc73e5e89a0838a15641db44137573030ee3 | [
"overlaps = []\nfor other in shapes:\n if other is self:\n continue\n overlap = self.get_overlap(other)\n if overlap.dist < 0:\n overlaps.append(overlap)\nif len(overlaps) == 0:\n return\noverlaps.sort(key=lambda item: item.area, reverse=True)\nfor i, old_overlap in enumerate(overlaps):\n ... | <|body_start_0|>
overlaps = []
for other in shapes:
if other is self:
continue
overlap = self.get_overlap(other)
if overlap.dist < 0:
overlaps.append(overlap)
if len(overlaps) == 0:
return
overlaps.sort(key=l... | Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject. | CollisionShape | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
... | stack_v2_sparse_classes_75kplus_train_074445 | 24,636 | permissive | [
{
"docstring": "Resolve this shape's overlap(s) with given list of shapes.",
"name": "resolve_overlaps_with_shapes",
"signature": "def resolve_overlaps_with_shapes(self, shapes)"
},
{
"docstring": "Resolve this shape's given overlap.",
"name": "resolve_overlap",
"signature": "def resolve... | 3 | stack_v2_sparse_classes_30k_train_025415 | Implement the Python class `CollisionShape` described below.
Class description:
Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject.
Method signatures and docstrings:
- def resolve_overlaps_with_shapes(self, shapes): Resolve... | Implement the Python class `CollisionShape` described below.
Class description:
Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject.
Method signatures and docstrings:
- def resolve_overlaps_with_shapes(self, shapes): Resolve... | 79b3c24deb26d1d2e5855461c8819f0542ce5ea4 | <|skeleton|>
class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CollisionShape:
"""Abstract class for a shape that can overlap and collide with other shapes. Shapes are part of a Collideable which in turn is part of a GameObject."""
def resolve_overlaps_with_shapes(self, shapes):
"""Resolve this shape's overlap(s) with given list of shapes."""
overlap... | the_stack_v2_python_sparse | collision.py | michael-lazar/playscii | train | 28 |
4ad4d36b848ef9313bd105bc90fb203e2c925f30 | [
"for index_1 in range(0, len(num)):\n for index_2 in range(len(num[:index_1]) + 1, len(num)):\n if num[index_1] + num[index_2] == target:\n return (index_1 + 1, index_2 + 1)",
"d = {}\nfor index, num in enumerate(num, 1):\n if target - num in d.keys():\n return (d[target - num], ind... | <|body_start_0|>
for index_1 in range(0, len(num)):
for index_2 in range(len(num[:index_1]) + 1, len(num)):
if num[index_1] + num[index_2] == target:
return (index_1 + 1, index_2 + 1)
<|end_body_0|>
<|body_start_1|>
d = {}
for index, num in enumer... | https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero based. Assume each input has one solution. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero based. Assume each input has one solution.... | stack_v2_sparse_classes_75kplus_train_074446 | 2,183 | no_license | [
{
"docstring": "Nested loops that iterate over length of 'num' means this solution runs O(n^2) time.",
"name": "naive_two_sum",
"signature": "def naive_two_sum(self, num, target)"
},
{
"docstring": "Uses a dictionary to speed up the runtime by storing the numbers we've seen before with their ind... | 2 | null | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero bas... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero bas... | ddf53992451a834c801471ab7c2acedf95f5c3cc | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero based. Assume each input has one solution.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
"""https://leetcode.com/problems/two-sum/ Given an array of integers, find two numbers such that they add up to a specific target number. Returns indices of two numbers such that they add to target, where index1 < index2. Indices are *not* zero based. Assume each input has one solution."""
def ... | the_stack_v2_python_sparse | two_sum.py | bridgette/Python100 | train | 4 |
3f7bcb652f73223f02ca8f33b966fe200381f228 | [
"cls = self.__class__\nself._depvar = depvar\nself._mutation_column = mutation_column\nself._constraints = util.setNoneList(constraints)\nself._num_folds = num_folds\nself._cv_model_cls = cv_model_cls\nself._cv_model_flags = cv_model_flags\nself._percentile_threshold = percentile_threshold\nself.provider = ModelDat... | <|body_start_0|>
cls = self.__class__
self._depvar = depvar
self._mutation_column = mutation_column
self._constraints = util.setNoneList(constraints)
self._num_folds = num_folds
self._cv_model_cls = cv_model_cls
self._cv_model_flags = cv_model_flags
self._... | Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the regression score - score the model quality predict - provide predicted values Not... | GenomeModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenomeModel:
"""Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the regression score - score the model quality... | stack_v2_sparse_classes_75kplus_train_074447 | 5,569 | permissive | [
{
"docstring": ":param str depvar: dependent variable :param str mutation_column: Name of the column with mutations :param list-of-booleanFunction constraints: constraints are predicates :param str transform_type: how the predictor variables are transformed :param int num_folds: Number of folds in cross validat... | 3 | null | Implement the Python class `GenomeModel` described below.
Class description:
Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the reg... | Implement the Python class `GenomeModel` described below.
Class description:
Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the reg... | 704435e66c58677bab24f27820458870092924e2 | <|skeleton|>
class GenomeModel:
"""Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the regression score - score the model quality... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenomeModel:
"""Instances do a single regression for a dependent variable, mutation_column (e.g., KEY_MUTATION, POSITION), data constraints. Identifies correlated mutations and constructs mutation groups. Key methods: fit - estimate the parameters of the regression score - score the model quality predict - pr... | the_stack_v2_python_sparse | microbepy/model/genome_model.py | ScienceStacks/microbepy | train | 1 |
44cc34a373405f1753d67b0fc1ff1f42fc13d56b | [
"try:\n user = SiteUser.objects.get(email=email)\n if user.check_password(password):\n return user\nexcept SiteUser.DoesNotExist:\n return None",
"try:\n user = SiteUser.objects.get(pk=user_id)\nexcept SiteUser.DoesNotExist:\n return None\nelse:\n return user"
] | <|body_start_0|>
try:
user = SiteUser.objects.get(email=email)
if user.check_password(password):
return user
except SiteUser.DoesNotExist:
return None
<|end_body_0|>
<|body_start_1|>
try:
user = SiteUser.objects.get(pk=user_id)
... | Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair. | EmailAuthBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, email=None, password=None):
"""Authenticate a user based on email address as the user name."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_074448 | 1,096 | permissive | [
{
"docstring": "Authenticate a user based on email address as the user name.",
"name": "authenticate",
"signature": "def authenticate(self, email=None, password=None)"
},
{
"docstring": "Get a User object from the user_id.",
"name": "get_user",
"signature": "def get_user(self, user_id)"
... | 2 | stack_v2_sparse_classes_30k_train_014945 | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair.
Method signatures and docstrings:
- def authenticate(self, email=None, password=None): Authenticate a user based on... | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair.
Method signatures and docstrings:
- def authenticate(self, email=None, password=None): Authenticate a user based on... | 3e662db65a7ca654f75a19e38cb0931be21f92e9 | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, email=None, password=None):
"""Authenticate a user based on email address as the user name."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair rather than a username/password pair."""
def authenticate(self, email=None, password=None):
"""Authenticate a user based on email address as the user name."""
try:
user = Si... | the_stack_v2_python_sparse | accounts/backends.py | Firmicety/fomalhaut-panel | train | 0 |
0d78e040ed02c3d7e494e673d3af889978bfd303 | [
"study_id = filter_params.pop('study_id', None)\ngenomic_file_id = filter_params.pop('genomic_file_id', None)\nq = ReadGroup.query.filter_by(**filter_params)\nfrom dataservice.api.participant.models import Participant\nfrom dataservice.api.biospecimen.models import Biospecimen\nfrom dataservice.api.genomic_file.mod... | <|body_start_0|>
study_id = filter_params.pop('study_id', None)
genomic_file_id = filter_params.pop('genomic_file_id', None)
q = ReadGroup.query.filter_by(**filter_params)
from dataservice.api.participant.models import Participant
from dataservice.api.biospecimen.models import Bi... | ReadGroup REST API | ReadGroupListAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadGroupListAPI:
"""ReadGroup REST API"""
def get(self, filter_params, after, limit):
"""Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup"""
<|body_0|>
def post(self):
"""Create a new read_grou... | stack_v2_sparse_classes_75kplus_train_074449 | 5,741 | permissive | [
{
"docstring": "Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup",
"name": "get",
"signature": "def get(self, filter_params, after, limit)"
},
{
"docstring": "Create a new read_group --- template: path: new_resource.yml propert... | 2 | null | Implement the Python class `ReadGroupListAPI` described below.
Class description:
ReadGroup REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup
- def post(self): C... | Implement the Python class `ReadGroupListAPI` described below.
Class description:
ReadGroup REST API
Method signatures and docstrings:
- def get(self, filter_params, after, limit): Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup
- def post(self): C... | 36ee3fc3d1ba9d1a177274d051fb175c56dd898e | <|skeleton|>
class ReadGroupListAPI:
"""ReadGroup REST API"""
def get(self, filter_params, after, limit):
"""Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup"""
<|body_0|>
def post(self):
"""Create a new read_grou... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ReadGroupListAPI:
"""ReadGroup REST API"""
def get(self, filter_params, after, limit):
"""Get all read_groups --- description: Get all read_groups template: path: get_list.yml properties: resource: ReadGroup"""
study_id = filter_params.pop('study_id', None)
genomic_file_id = filte... | the_stack_v2_python_sparse | dataservice/api/read_group/resources.py | kids-first/kf-api-dataservice | train | 9 |
c861396ad766887d4c8613df582d09c5647972f7 | [
"self.key = key\nself.in_degree = 0\nself.out_degree = 0\nself.weight_list = []\nself.adjust_list = []\nself.backup_in_degree = self.in_degree\nself.backup_out_degree = self.out_degree\nself.dist = 0",
"self.adjust_list.append(to_vertex)\nself.out_degree += 1\nself.backup_out_degree += 1"
] | <|body_start_0|>
self.key = key
self.in_degree = 0
self.out_degree = 0
self.weight_list = []
self.adjust_list = []
self.backup_in_degree = self.in_degree
self.backup_out_degree = self.out_degree
self.dist = 0
<|end_body_0|>
<|body_start_1|>
self.a... | vertex | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class vertex:
def __init__(self, key, weight=None):
""":param key: :param weight:"""
<|body_0|>
def add_adjust(self, to_vertex):
"""给节点添加邻接节点 :param to_vertex: 本节点邻接的另一个节点 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.key = key
sel... | stack_v2_sparse_classes_75kplus_train_074450 | 699 | no_license | [
{
"docstring": ":param key: :param weight:",
"name": "__init__",
"signature": "def __init__(self, key, weight=None)"
},
{
"docstring": "给节点添加邻接节点 :param to_vertex: 本节点邻接的另一个节点 :return:",
"name": "add_adjust",
"signature": "def add_adjust(self, to_vertex)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010011 | Implement the Python class `vertex` described below.
Class description:
Implement the vertex class.
Method signatures and docstrings:
- def __init__(self, key, weight=None): :param key: :param weight:
- def add_adjust(self, to_vertex): 给节点添加邻接节点 :param to_vertex: 本节点邻接的另一个节点 :return: | Implement the Python class `vertex` described below.
Class description:
Implement the vertex class.
Method signatures and docstrings:
- def __init__(self, key, weight=None): :param key: :param weight:
- def add_adjust(self, to_vertex): 给节点添加邻接节点 :param to_vertex: 本节点邻接的另一个节点 :return:
<|skeleton|>
class vertex:
... | d59f9b3940647548f92ca2819dd5dd2699ea7cbe | <|skeleton|>
class vertex:
def __init__(self, key, weight=None):
""":param key: :param weight:"""
<|body_0|>
def add_adjust(self, to_vertex):
"""给节点添加邻接节点 :param to_vertex: 本节点邻接的另一个节点 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class vertex:
def __init__(self, key, weight=None):
""":param key: :param weight:"""
self.key = key
self.in_degree = 0
self.out_degree = 0
self.weight_list = []
self.adjust_list = []
self.backup_in_degree = self.in_degree
self.backup_out_degree = self.... | the_stack_v2_python_sparse | algorithm/graph/vertex.py | LX2010JY/py_new | train | 0 | |
bb70e4e0c2476bc4f6955e358c2f08be80a92daf | [
"notebook = get_object_or_404(Notebook, slug=notebook_slug)\ncontent = request.data.get('content')\ntitle = request.data.get('title', '')\ntags = request.data.get('tags')\ntype = request.data.get('type', '')\ndate = request.data.get('date', '')\nif content:\n kwargs = {'content': content, 'author': request.user,... | <|body_start_0|>
notebook = get_object_or_404(Notebook, slug=notebook_slug)
content = request.data.get('content')
title = request.data.get('title', '')
tags = request.data.get('tags')
type = request.data.get('type', '')
date = request.data.get('date', '')
if conte... | # Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebook (sets the status to deleted). | EntryListAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntryListAPIView:
"""# Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebook (sets the status to deleted)."""
... | stack_v2_sparse_classes_75kplus_train_074451 | 19,450 | no_license | [
{
"docstring": "Create a new Entry.",
"name": "post",
"signature": "def post(self, request, notebook_slug)"
},
{
"docstring": "Update an existing Notebook.",
"name": "put",
"signature": "def put(self, request, notebook_slug)"
},
{
"docstring": "Delete a Notebook. Sets the status ... | 3 | stack_v2_sparse_classes_30k_train_022037 | Implement the Python class `EntryListAPIView` described below.
Class description:
# Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebo... | Implement the Python class `EntryListAPIView` described below.
Class description:
# Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebo... | b8c4ceff83c92e83a2297b17ad29e29b3b8fdc3c | <|skeleton|>
class EntryListAPIView:
"""# Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebook (sets the status to deleted)."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EntryListAPIView:
"""# Entries - **GET** List the entries for the current notebook. - **POST** Create a new entry attached to the current notebook. - **PUT** Edit the current notebook's name, status, group, or sections. - **DELETE** Delete the current notebook (sets the status to deleted)."""
def post(se... | the_stack_v2_python_sparse | vinci/views/apis.py | mod2/vinci | train | 1 |
a11853aa6b75dec720c782781e03307b25fa1c34 | [
"self.input_lines = input_lines\nself.reducer_obj = reducer_obj\nself.current_key = None\nself.input_finished = False\nself.peeked_row = None\nself.input_row_generator = self._get_input_row_generator()",
"def _keys_row_generator():\n \"\"\"Yields a generator that moves over rows for one key.\"\"\"\n while n... | <|body_start_0|>
self.input_lines = input_lines
self.reducer_obj = reducer_obj
self.current_key = None
self.input_finished = False
self.peeked_row = None
self.input_row_generator = self._get_input_row_generator()
<|end_body_0|>
<|body_start_1|>
def _keys_row_gene... | Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input. | _HiveInputGenerator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HiveInputGenerator:
"""Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input."""
def __init__(self, input_lines, reducer_obj):
"""Initializer.""... | stack_v2_sparse_classes_75kplus_train_074452 | 4,271 | permissive | [
{
"docstring": "Initializer.",
"name": "__init__",
"signature": "def __init__(self, input_lines, reducer_obj)"
},
{
"docstring": "Yields generators for rows of each key.",
"name": "get_key_generator",
"signature": "def get_key_generator(self)"
},
{
"docstring": "Wraps the input a... | 4 | stack_v2_sparse_classes_30k_train_043655 | Implement the Python class `_HiveInputGenerator` described below.
Class description:
Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input.
Method signatures and docstrings:
- def... | Implement the Python class `_HiveInputGenerator` described below.
Class description:
Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input.
Method signatures and docstrings:
- def... | af028dd413dd2595cb8338a5a2c2d61a95adf7c6 | <|skeleton|>
class _HiveInputGenerator:
"""Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input."""
def __init__(self, input_lines, reducer_obj):
"""Initializer.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _HiveInputGenerator:
"""Build generator layer on top of hive input lines. This class slices the input lines and gives generator which in turn yields a generator of rows each for distinct keys in assuming sorted input."""
def __init__(self, input_lines, reducer_obj):
"""Initializer."""
sel... | the_stack_v2_python_sparse | code_root/common/utils/hive_reducer_shim.py | rocketfuel/mool | train | 3 |
43637705175d3e7cbb33ea7c17e2058772e23e7e | [
"errors = {}\nif user_input is not None:\n if user_input[CONF_GATEWAY]:\n return await self.async_step_gateway()\n errors['base'] = 'no_device_selected'\nreturn self.async_show_form(step_id='user', data_schema=CONFIG_SCHEMA, errors=errors)",
"errors = {}\nif user_input is not None:\n host = user_i... | <|body_start_0|>
errors = {}
if user_input is not None:
if user_input[CONF_GATEWAY]:
return await self.async_step_gateway()
errors['base'] = 'no_device_selected'
return self.async_show_form(step_id='user', data_schema=CONFIG_SCHEMA, errors=errors)
<|end_bo... | Handle a Xiaomi Miio config flow. | XiaomiMiioFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XiaomiMiioFlowHandler:
"""Handle a Xiaomi Miio config flow."""
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
<|body_0|>
async def async_step_gateway(self, user_input=None):
"""Handle a flow initialized by the user ... | stack_v2_sparse_classes_75kplus_train_074453 | 2,817 | permissive | [
{
"docstring": "Handle a flow initialized by the user.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
},
{
"docstring": "Handle a flow initialized by the user to configure a gateway.",
"name": "async_step_gateway",
"signature": "async def asy... | 2 | stack_v2_sparse_classes_30k_train_029041 | Implement the Python class `XiaomiMiioFlowHandler` described below.
Class description:
Handle a Xiaomi Miio config flow.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a flow initialized by the user.
- async def async_step_gateway(self, user_input=None): Handle a flow ini... | Implement the Python class `XiaomiMiioFlowHandler` described below.
Class description:
Handle a Xiaomi Miio config flow.
Method signatures and docstrings:
- async def async_step_user(self, user_input=None): Handle a flow initialized by the user.
- async def async_step_gateway(self, user_input=None): Handle a flow ini... | ecdcfb835dc708aa8cd035adbe41dfb104203586 | <|skeleton|>
class XiaomiMiioFlowHandler:
"""Handle a Xiaomi Miio config flow."""
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
<|body_0|>
async def async_step_gateway(self, user_input=None):
"""Handle a flow initialized by the user ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XiaomiMiioFlowHandler:
"""Handle a Xiaomi Miio config flow."""
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
errors = {}
if user_input is not None:
if user_input[CONF_GATEWAY]:
return await self.async_ste... | the_stack_v2_python_sparse | homeassistant/components/xiaomi_miio/config_flow.py | callsSolve/core | train | 1 |
44a9280bf754063a70bb534e9377cbf7f7d0a9c9 | [
"if width < 1 or height < 1:\n raise ValueError\nself.width = width\nself.height = height\nself.food = food[::-1]\nself.board = [[0] * width for _ in range(height)]\nself.board[0][0] = 1\nself.snake = deque([(0, 0)])",
"x, y = self.snake[0]\nif direction == 'U':\n x -= 1\nelif direction == 'D':\n x += 1\... | <|body_start_0|>
if width < 1 or height < 1:
raise ValueError
self.width = width
self.height = height
self.food = food[::-1]
self.board = [[0] * width for _ in range(height)]
self.board[0][0] = 1
self.snake = deque([(0, 0)])
<|end_body_0|>
<|body_star... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
""":type food: list[list[int]] a list of food positions"""
<|body_0|>
def move(self, direction):
""":type direction: str, 'U', 'L', 'R', 'D'"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if width... | stack_v2_sparse_classes_75kplus_train_074454 | 3,422 | no_license | [
{
"docstring": ":type food: list[list[int]] a list of food positions",
"name": "__init__",
"signature": "def __init__(self, width, height, food)"
},
{
"docstring": ":type direction: str, 'U', 'L', 'R', 'D'",
"name": "move",
"signature": "def move(self, direction)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044500 | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): :type food: list[list[int]] a list of food positions
- def move(self, direction): :type direction: str, 'U', 'L', 'R', 'D' | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width, height, food): :type food: list[list[int]] a list of food positions
- def move(self, direction): :type direction: str, 'U', 'L', 'R', 'D'
<|skeleton|... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class SnakeGame:
def __init__(self, width, height, food):
""":type food: list[list[int]] a list of food positions"""
<|body_0|>
def move(self, direction):
""":type direction: str, 'U', 'L', 'R', 'D'"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeGame:
def __init__(self, width, height, food):
""":type food: list[list[int]] a list of food positions"""
if width < 1 or height < 1:
raise ValueError
self.width = width
self.height = height
self.food = food[::-1]
self.board = [[0] * width for _... | the_stack_v2_python_sparse | code353DesignSnakeGame.py | cybelewang/leetcode-python | train | 0 | |
20b7ba6876119169e2a6403e797dc43e9c1161ed | [
"super(PositionalEncoding, self).__init__()\nself.d_model = d_model\nself.reverse = reverse\nself.xscale = math.sqrt(self.d_model)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.pe = None\nself.extend_pe(torch.tensor(0.0).expand(1, max_len))",
"if self.pe is not None:\n if self.pe.size(1) >= x.size(1):\n ... | <|body_start_0|>
super(PositionalEncoding, self).__init__()
self.d_model = d_model
self.reverse = reverse
self.xscale = math.sqrt(self.d_model)
self.dropout = nn.Dropout(p=dropout_rate)
self.pe = None
self.extend_pe(torch.tensor(0.0).expand(1, max_len))
<|end_body... | Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position. | PositionalEncoding | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
"""Construct an Positi... | stack_v2_sparse_classes_75kplus_train_074455 | 4,950 | permissive | [
{
"docstring": "Construct an PositionalEncoding object.",
"name": "__init__",
"signature": "def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False)"
},
{
"docstring": "Reset the positional encodings.",
"name": "extend_pe",
"signature": "def extend_pe(self, x)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_040668 | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position.
Method signatures and docstrings:
- def __init__(self, d_model, dropou... | Implement the Python class `PositionalEncoding` described below.
Class description:
Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position.
Method signatures and docstrings:
- def __init__(self, d_model, dropou... | b60c741f746877293bb85eed6806736fc8fa0ffd | <|skeleton|>
class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
"""Construct an Positi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PositionalEncoding:
"""Positional encoding. Args: d_model: Embedding dimension. dropout_rate: Dropout rate. max_len: Maximum input length. reverse: Whether to reverse the input position."""
def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
"""Construct an PositionalEncoding ... | the_stack_v2_python_sparse | kosmos-2/fairseq/fairseq/modules/positional_encoding.py | microsoft/unilm | train | 15,313 |
75502dab7091f36e3d334b04a5dec851ce882360 | [
"result = True\nstack = []\np = root\npre = None\nwhile p != None and p.val != '#' or stack:\n if p != None and p.val != '#':\n stack.append(p)\n p = p.left\n else:\n temp = stack.pop()\n if (pre != None and pre.val != '#') and temp.val <= pre.val:\n return False\n ... | <|body_start_0|>
result = True
stack = []
p = root
pre = None
while p != None and p.val != '#' or stack:
if p != None and p.val != '#':
stack.append(p)
p = p.left
else:
temp = stack.pop()
if (... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST_self(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = True
stack = []
p... | stack_v2_sparse_classes_75kplus_train_074456 | 1,241 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST",
"signature": "def isValidBST(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isValidBST_self",
"signature": "def isValidBST_self(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051873 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBST_self(self, root): :type root: TreeNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValidBST(self, root): :type root: TreeNode :rtype: bool
- def isValidBST_self(self, root): :type root: TreeNode :rtype: bool
<|skeleton|>
class Solution:
def isValidB... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isValidBST_self(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isValidBST(self, root):
""":type root: TreeNode :rtype: bool"""
result = True
stack = []
p = root
pre = None
while p != None and p.val != '#' or stack:
if p != None and p.val != '#':
stack.append(p)
p = p... | the_stack_v2_python_sparse | 98_validate_binary_search_tree/sol.py | lianke123321/leetcode_sol | train | 0 | |
a937dd7a3ad5b66b166df3c7fa4f862e47a0b230 | [
"scp_utils.BaseScpHelper.Args(parser)\nparser.add_argument('--port', help='The port to connect to.')\nparser.add_argument('--recurse', action='store_true', help='Upload directories recursively.')\nparser.add_argument('--compress', action='store_true', help='Enable compression.')\nparser.add_argument('--scp-flag', a... | <|body_start_0|>
scp_utils.BaseScpHelper.Args(parser)
parser.add_argument('--port', help='The port to connect to.')
parser.add_argument('--recurse', action='store_true', help='Upload directories recursively.')
parser.add_argument('--compress', action='store_true', help='Enable compressio... | Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine instance name (e.g., _example-instance_:~/_FILE_). To denote a local fil... | Scp | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Scp:
"""Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine instance name (e.g., _example-instance_:~... | stack_v2_sparse_classes_75kplus_train_074457 | 3,400 | permissive | [
{
"docstring": "Set up arguments for this command. Args: parser: An argparse.ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "See scp_utils.BaseScpCommand.Run.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010308 | Implement the Python class `Scp` described below.
Class description:
Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine in... | Implement the Python class `Scp` described below.
Class description:
Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine in... | afdc2805cb1b77bd5ac9fdd1a76217f4841f0ea6 | <|skeleton|>
class Scp:
"""Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine instance name (e.g., _example-instance_:~... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Scp:
"""Copy files to and from Google Compute Engine virtual machines via scp. *{command}* copies files between a virtual machine instance and your local machine using the scp command. To denote a remote file, prefix the file name with the virtual machine instance name (e.g., _example-instance_:~/_FILE_). To ... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/compute/scp.py | bopopescu/searchparty | train | 0 |
54f42d782b7f8c39545583e8c082e77c6db88313 | [
"contents: str = ''\ntry:\n with open(filepath, 'r') as f:\n contents = f.read()\nexcept Exception as exc:\n if logger is not None:\n logger.error('FAILED to read keyfile %s: %s', filepath, exc)\n return (None, None)\ntry:\n key_data = pkl.PrivateKeyList.from_string(contents)\n data_pub... | <|body_start_0|>
contents: str = ''
try:
with open(filepath, 'r') as f:
contents = f.read()
except Exception as exc:
if logger is not None:
logger.error('FAILED to read keyfile %s: %s', filepath, exc)
return (None, None)
... | Ed25519KeyUtil | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ed25519KeyUtil:
def parse_private_key_file(cls, filepath: str, logger):
"""Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file :param logger: logger to use for messages :return: (public key part as bytes, private key part as byte... | stack_v2_sparse_classes_75kplus_train_074458 | 2,209 | permissive | [
{
"docstring": "Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file :param logger: logger to use for messages :return: (public key part as bytes, private key part as bytes)",
"name": "parse_private_key_file",
"signature": "def parse_private_key_... | 2 | null | Implement the Python class `Ed25519KeyUtil` described below.
Class description:
Implement the Ed25519KeyUtil class.
Method signatures and docstrings:
- def parse_private_key_file(cls, filepath: str, logger): Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file... | Implement the Python class `Ed25519KeyUtil` described below.
Class description:
Implement the Ed25519KeyUtil class.
Method signatures and docstrings:
- def parse_private_key_file(cls, filepath: str, logger): Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file... | e8aedf9c15baa872eb7aee4d6b28ad6208a9fca2 | <|skeleton|>
class Ed25519KeyUtil:
def parse_private_key_file(cls, filepath: str, logger):
"""Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file :param logger: logger to use for messages :return: (public key part as bytes, private key part as byte... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ed25519KeyUtil:
def parse_private_key_file(cls, filepath: str, logger):
"""Parse a file with ed25519 private key in OPEN SSH PRIVATE key format. :param filepath: file path to a key file :param logger: logger to use for messages :return: (public key part as bytes, private key part as bytes)"""
... | the_stack_v2_python_sparse | studio/ed25519_key_util.py | studioml/studio | train | 406 | |
0cb2f3f2c585b665afa1daad007282903caa93a1 | [
"tk.Canvas.__init__(self, parent, **kwargs)\nself._color1 = color1\nself._color2 = color2\nself.bind('<Configure>', self._draw_gradient)\nself.config(relief='flat', highlightthickness=0)",
"self.delete('gradient')\nwidth = self.winfo_width()\nheight = self.winfo_height()\nlimit = width\nr1, g1, b1 = self.winfo_rg... | <|body_start_0|>
tk.Canvas.__init__(self, parent, **kwargs)
self._color1 = color1
self._color2 = color2
self.bind('<Configure>', self._draw_gradient)
self.config(relief='flat', highlightthickness=0)
<|end_body_0|>
<|body_start_1|>
self.delete('gradient')
width = ... | from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2 | GradientCanvas | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, co... | stack_v2_sparse_classes_75kplus_train_074459 | 19,682 | no_license | [
{
"docstring": "default gradient color: red to black",
"name": "__init__",
"signature": "def __init__(self, parent, color1='#ffc851', color2='#808000', **kwargs)"
},
{
"docstring": "Draw the gradient",
"name": "_draw_gradient",
"signature": "def _draw_gradient(self, event=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_052487 | Implement the Python class `GradientCanvas` described below.
Class description:
from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色... | Implement the Python class `GradientCanvas` described below.
Class description:
from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色... | 440d168fd84bd98d2d9f2bc27b34ac9d7816a4e1 | <|skeleton|>
class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, co... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradientCanvas:
"""from Bryan Oakley on (https://stackoverflow.com/questions/26178869/ is-it-possible-to-apply-gradient-colours- to-bg-of-tkinter-python-widgets) A gradient frame which uses a canvas to draw the background parent: color11: 渐变颜色1 color22: 渐变颜色2"""
def __init__(self, parent, color1='#ffc851... | the_stack_v2_python_sparse | Lib/gpconfig/newGUI.py | hygnic/Gispot | train | 0 |
0b16ba59eec2d77e012fb8d975f94cca7a921172 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('aquan_erj826', 'aquan_erj826')\ncollection = repo.aquan_erj826.firearms\nrepo.dropCollection('gunsRecovered')\nrepo.createCollection('gunsRecovered')\nfor point in collection.find():\n total = int(poi... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aquan_erj826', 'aquan_erj826')
collection = repo.aquan_erj826.firearms
repo.dropCollection('gunsRecovered')
repo.createCollection('gunsRec... | gunsRecovered | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class gunsRecovered:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_75kplus_train_074460 | 4,457 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_val_002340 | Implement the Python class `gunsRecovered` described below.
Class description:
Implement the gunsRecovered class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | Implement the Python class `gunsRecovered` described below.
Class description:
Implement the gunsRecovered class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, e... | 97e72731ffadbeae57d7a332decd58706e7c08de | <|skeleton|>
class gunsRecovered:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class gunsRecovered:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('aquan_erj826', 'aquan_erj826')
... | the_stack_v2_python_sparse | aquan_erj826/gunsRecovered.py | ROODAY/course-2017-fal-proj | train | 3 | |
aa0930de16646b3dce4f78458371976f904e4ad5 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | ResourceServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def List(self, request, context):
"""List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os)."""
<|body_0|>
def Get(self, request, context):
"""Get s... | stack_v2_sparse_classes_75kplus_train_074461 | 12,259 | permissive | [
{
"docstring": "List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os).",
"name": "List",
"signature": "def List(self, request, context)"
},
{
"docstring": "Get specific Compute Cloud instance.",
"name": "Get",
"signature": "def Get(self, request, context)"
}... | 6 | stack_v2_sparse_classes_30k_train_031891 | Implement the Python class `ResourceServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def List(self, request, context): List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os).
- def Get(self, req... | Implement the Python class `ResourceServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def List(self, request, context): List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os).
- def Get(self, req... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class ResourceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def List(self, request, context):
"""List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os)."""
<|body_0|>
def Get(self, request, context):
"""Get s... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceServiceServicer:
"""Missing associated documentation comment in .proto file."""
def List(self, request, context):
"""List resources: [Compute Cloud instances](/docs/backup/concepts/vm-connection#os)."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('M... | the_stack_v2_python_sparse | yandex/cloud/backup/v1/resource_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
aed6e064a4327ef1ee1d80fb195d8fc99b9780d8 | [
"self.current_ind = 0\nself.images = images\nself.xlabels = xlabels",
"plt.gcf()\nif event.key == 'right' and self.current_ind < len(self.images):\n self.current_ind += 1\nelif event.key == 'left' and self.current_ind > 0:\n self.current_ind -= 1\nplt.clf()\nevent.canvas.figure.gca().imshow(self.images[self... | <|body_start_0|>
self.current_ind = 0
self.images = images
self.xlabels = xlabels
<|end_body_0|>
<|body_start_1|>
plt.gcf()
if event.key == 'right' and self.current_ind < len(self.images):
self.current_ind += 1
elif event.key == 'left' and self.current_ind > ... | ImageCycler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageCycler:
def __init__(self, images, xlabels=None):
"""Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy arrays to display as images xlabels : list, optional List of custom labels for the images"""
... | stack_v2_sparse_classes_75kplus_train_074462 | 14,615 | permissive | [
{
"docstring": "Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy arrays to display as images xlabels : list, optional List of custom labels for the images",
"name": "__init__",
"signature": "def __init__(self, images, xlabe... | 3 | stack_v2_sparse_classes_30k_train_013875 | Implement the Python class `ImageCycler` described below.
Class description:
Implement the ImageCycler class.
Method signatures and docstrings:
- def __init__(self, images, xlabels=None): Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy ... | Implement the Python class `ImageCycler` described below.
Class description:
Implement the ImageCycler class.
Method signatures and docstrings:
- def __init__(self, images, xlabels=None): Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy ... | 041391f4ef0667e555046fc66f5beb67b4975dda | <|skeleton|>
class ImageCycler:
def __init__(self, images, xlabels=None):
"""Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy arrays to display as images xlabels : list, optional List of custom labels for the images"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ImageCycler:
def __init__(self, images, xlabels=None):
"""Convenience object to cycle through a list of images inside a jupyter notebook. Parameters ---------- images : list List of numpy arrays to display as images xlabels : list, optional List of custom labels for the images"""
self.current_... | the_stack_v2_python_sparse | astronomaly/utils/utils.py | MichelleLochner/astronomaly | train | 69 | |
750b447436090e8c0fb0557f14b8f50704e6aa59 | [
"self.logger = get_logger(log_to_screen)\nself._factory = ServerFactory()\nself._factory.protocol = Worker\nself._factory.logger = self.logger\nself._factory.protocol.parser = parser()\nself._port = port\nself._reactor = SelectReactor()\nself._reactor.listenTCP(port, self._factory)\nself._resource_manager = Manager... | <|body_start_0|>
self.logger = get_logger(log_to_screen)
self._factory = ServerFactory()
self._factory.protocol = Worker
self._factory.logger = self.logger
self._factory.protocol.parser = parser()
self._port = port
self._reactor = SelectReactor()
self._rea... | Resource manager server. | ResourceManagerServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceManagerServer:
"""Resource manager server."""
def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True):
"""Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractPar... | stack_v2_sparse_classes_75kplus_train_074463 | 2,498 | permissive | [
{
"docstring": "Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractParser`. log_to_screen (bool): Enable log prints to screen.",
"name": "__init__",
"signature": "def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAU... | 3 | stack_v2_sparse_classes_30k_val_002476 | Implement the Python class `ResourceManagerServer` described below.
Class description:
Resource manager server.
Method signatures and docstrings:
- def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): Initialize the resource manager server. Args: port (number): client listener po... | Implement the Python class `ResourceManagerServer` described below.
Class description:
Resource manager server.
Method signatures and docstrings:
- def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True): Initialize the resource manager server. Args: port (number): client listener po... | 746fdc07c4f8de7f98c6ab7fa1d5c95dcadbf6dc | <|skeleton|>
class ResourceManagerServer:
"""Resource manager server."""
def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True):
"""Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractPar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResourceManagerServer:
"""Resource manager server."""
def __init__(self, port=RESOURCE_MANAGER_PORT, parser=DEFAULT_PARSER, log_to_screen=True):
"""Initialize the resource manager server. Args: port (number): client listener port. parser (object): messages parser of type `AbstractParser`. log_to_... | the_stack_v2_python_sparse | src/rotest/management/server/main.py | IamShobe/rotest | train | 3 |
25b84a7ccf0e5f354831f12d9bf42adab3f3cac4 | [
"self.name = name\nself.start_point = start\nself.end_point = end",
"start = self.start_point.position\nend = self.end_point.position\nreturn end - start"
] | <|body_start_0|>
self.name = name
self.start_point = start
self.end_point = end
<|end_body_0|>
<|body_start_1|>
start = self.start_point.position
end = self.end_point.position
return end - start
<|end_body_1|>
| AxisReal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisReal:
def __init__(self, name: Name, start: MarkerReal, end: MarkerReal):
"""Parameters ---------- name: The AxisName of the Axis start: The initial Marker"""
<|body_0|>
def axis(self) -> np.ndarray:
"""Returns the axis vector"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_074464 | 649 | permissive | [
{
"docstring": "Parameters ---------- name: The AxisName of the Axis start: The initial Marker",
"name": "__init__",
"signature": "def __init__(self, name: Name, start: MarkerReal, end: MarkerReal)"
},
{
"docstring": "Returns the axis vector",
"name": "axis",
"signature": "def axis(self)... | 2 | stack_v2_sparse_classes_30k_train_011551 | Implement the Python class `AxisReal` described below.
Class description:
Implement the AxisReal class.
Method signatures and docstrings:
- def __init__(self, name: Name, start: MarkerReal, end: MarkerReal): Parameters ---------- name: The AxisName of the Axis start: The initial Marker
- def axis(self) -> np.ndarray:... | Implement the Python class `AxisReal` described below.
Class description:
Implement the AxisReal class.
Method signatures and docstrings:
- def __init__(self, name: Name, start: MarkerReal, end: MarkerReal): Parameters ---------- name: The AxisName of the Axis start: The initial Marker
- def axis(self) -> np.ndarray:... | 70265cb1931c463a24f27013350e363134ce6801 | <|skeleton|>
class AxisReal:
def __init__(self, name: Name, start: MarkerReal, end: MarkerReal):
"""Parameters ---------- name: The AxisName of the Axis start: The initial Marker"""
<|body_0|>
def axis(self) -> np.ndarray:
"""Returns the axis vector"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AxisReal:
def __init__(self, name: Name, start: MarkerReal, end: MarkerReal):
"""Parameters ---------- name: The AxisName of the Axis start: The initial Marker"""
self.name = name
self.start_point = start
self.end_point = end
def axis(self) -> np.ndarray:
"""Return... | the_stack_v2_python_sparse | binding/python3/model_creation/axis_real.py | pyomeca/biorbd | train | 63 | |
4aa1a8f7b1844258ef13a83e3b7c556dfe311d17 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn BookingWorkHours()",
"from .booking_work_time_slot import BookingWorkTimeSlot\nfrom .day_of_week import DayOfWeek\nfrom .booking_work_time_slot import BookingWorkTimeSlot\nfrom .day_of_week import DayOfWeek\nfields: Dict[str, Callable[... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return BookingWorkHours()
<|end_body_0|>
<|body_start_1|>
from .booking_work_time_slot import BookingWorkTimeSlot
from .day_of_week import DayOfWeek
from .booking_work_time_slot import ... | This type represents the set of working hours in a single day of the week. | BookingWorkHours | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookingWorkHours:
"""This type represents the set of working hours in a single day of the week."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours:
"""Creates a new instance of the appropriate class based on discriminator value Args: pars... | stack_v2_sparse_classes_75kplus_train_074465 | 3,164 | 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: BookingWorkHours",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_va... | 3 | stack_v2_sparse_classes_30k_train_047428 | Implement the Python class `BookingWorkHours` described below.
Class description:
This type represents the set of working hours in a single day of the week.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: Creates a new instance of the ... | Implement the Python class `BookingWorkHours` described below.
Class description:
This type represents the set of working hours in a single day of the week.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours: Creates a new instance of the ... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BookingWorkHours:
"""This type represents the set of working hours in a single day of the week."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours:
"""Creates a new instance of the appropriate class based on discriminator value Args: pars... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BookingWorkHours:
"""This type represents the set of working hours in a single day of the week."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BookingWorkHours:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The p... | the_stack_v2_python_sparse | msgraph/generated/models/booking_work_hours.py | microsoftgraph/msgraph-sdk-python | train | 135 |
e6e7efff6b13bfea86afe53d4c976b179ab74bc7 | [
"def transition_name(state, symb):\n return f'({state}, {symb})'\nerror = False\ntransitions = table['transitions']\nfor state in automaton.states:\n for symb in automaton.alphabet:\n name = transition_name(state, symb)\n answer = context[name]\n answer.suffix = '<i class=\"fas fa-check\"... | <|body_start_0|>
def transition_name(state, symb):
return f'({state}, {symb})'
error = False
transitions = table['transitions']
for state in automaton.states:
for symb in automaton.alphabet:
name = transition_name(state, symb)
answe... | Evaluator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Evaluator:
def eval_transition_table(automaton, table, context):
"""Eval script of transition table question."""
<|body_0|>
def eval_multi_choice_question(checkbox: CheckboxGroup, answers: list, withanswer=True):
"""Eval script of multi choice question."""
<|... | stack_v2_sparse_classes_75kplus_train_074466 | 1,833 | no_license | [
{
"docstring": "Eval script of transition table question.",
"name": "eval_transition_table",
"signature": "def eval_transition_table(automaton, table, context)"
},
{
"docstring": "Eval script of multi choice question.",
"name": "eval_multi_choice_question",
"signature": "def eval_multi_c... | 2 | stack_v2_sparse_classes_30k_test_002499 | Implement the Python class `Evaluator` described below.
Class description:
Implement the Evaluator class.
Method signatures and docstrings:
- def eval_transition_table(automaton, table, context): Eval script of transition table question.
- def eval_multi_choice_question(checkbox: CheckboxGroup, answers: list, withans... | Implement the Python class `Evaluator` described below.
Class description:
Implement the Evaluator class.
Method signatures and docstrings:
- def eval_transition_table(automaton, table, context): Eval script of transition table question.
- def eval_multi_choice_question(checkbox: CheckboxGroup, answers: list, withans... | 8208f08562a7ea573aa0d010b4b28085e73d0f30 | <|skeleton|>
class Evaluator:
def eval_transition_table(automaton, table, context):
"""Eval script of transition table question."""
<|body_0|>
def eval_multi_choice_question(checkbox: CheckboxGroup, answers: list, withanswer=True):
"""Eval script of multi choice question."""
<|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Evaluator:
def eval_transition_table(automaton, table, context):
"""Eval script of transition table question."""
def transition_name(state, symb):
return f'({state}, {symb})'
error = False
transitions = table['transitions']
for state in automaton.states:
... | the_stack_v2_python_sparse | ComputerScience/automaton/scripts/evaluator.py | PremierLangage/Yggdrasil | train | 6 | |
5cf338b07054a033e3510c6cc4504c378a844078 | [
"self.continuous_schedule = continuous_schedule\nself.daily_schedule = daily_schedule\nself.monthly_schedule = monthly_schedule\nself.periodicity = periodicity\nself.rpo_schedule = rpo_schedule",
"if dictionary is None:\n return None\ncontinuous_schedule = cohesity_management_sdk.models.continuous_schedule.Con... | <|body_start_0|>
self.continuous_schedule = continuous_schedule
self.daily_schedule = daily_schedule
self.monthly_schedule = monthly_schedule
self.periodicity = periodicity
self.rpo_schedule = rpo_schedule
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime periods when new Job Runs should NOT be started.... | SchedulingPolicy | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime peri... | stack_v2_sparse_classes_75kplus_train_074467 | 4,041 | permissive | [
{
"docstring": "Constructor for the SchedulingPolicy class",
"name": "__init__",
"signature": "def __init__(self, continuous_schedule=None, daily_schedule=None, monthly_schedule=None, periodicity=None, rpo_schedule=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Arg... | 2 | stack_v2_sparse_classes_30k_train_022527 | Implement the Python class `SchedulingPolicy` described below.
Class description:
Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous... | Implement the Python class `SchedulingPolicy` described below.
Class description:
Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime peri... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SchedulingPolicy:
"""Implementation of the 'SchedulingPolicy' model. Specifies settings that define a backup schedule for a Protection Job. Attributes: continuous_schedule (ContinuousSchedule): Specifies the time interval between two Job Runs of a continuous backup schedule and any QuietTime periods when new ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduling_policy.py | cohesity/management-sdk-python | train | 24 |
181071323cb5ab6117220d113dd75efdcf39a63e | [
"super().__init__()\nself.segment_num = segment_num\nif self.segment_num != None:\n self.mask_embedding = nn.Embedding(segment_num + 1, segment_num)\n self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros((1, segment_num)), np.identity(segment_num)], axis=0)))\n self.mask_embeddi... | <|body_start_0|>
super().__init__()
self.segment_num = segment_num
if self.segment_num != None:
self.mask_embedding = nn.Embedding(segment_num + 1, segment_num)
self.mask_embedding.weight.data.copy_(torch.FloatTensor(np.concatenate([np.zeros((1, segment_num)), np.identity... | MaxPool | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxPool:
def __init__(self, kernel_size, segment_num=None):
"""Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: input features: (B... | stack_v2_sparse_classes_75kplus_train_074468 | 2,277 | permissive | [
{
"docstring": "Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size",
"name": "__init__",
"signature": "def __init__(self, kernel_size, segment_num=None)"
},
{
"docstring": "Args: input features: (B, L, I_EMBED) Return... | 2 | stack_v2_sparse_classes_30k_train_042568 | Implement the Python class `MaxPool` described below.
Class description:
Implement the MaxPool class.
Method signatures and docstrings:
- def __init__(self, kernel_size, segment_num=None): Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size... | Implement the Python class `MaxPool` described below.
Class description:
Implement the MaxPool class.
Method signatures and docstrings:
- def __init__(self, kernel_size, segment_num=None): Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size... | 53b6c9400775ab066dc4f462e81ce05ea2b128e7 | <|skeleton|>
class MaxPool:
def __init__(self, kernel_size, segment_num=None):
"""Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size"""
<|body_0|>
def forward(self, x, mask=None):
"""Args: input features: (B... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaxPool:
def __init__(self, kernel_size, segment_num=None):
"""Args: input_size: dimention of input embedding kernel_size: kernel_size for CNN padding: padding for CNN hidden_size: hidden size"""
super().__init__()
self.segment_num = segment_num
if self.segment_num != None:
... | the_stack_v2_python_sparse | opennre/module/pool/max_pool.py | thunlp/OpenNRE | train | 3,835 | |
394b10ed158286c957616e271e7903476e876a31 | [
"Block.__init__(self, scenario, args)\nif self.language is None:\n raise LoadingException('Language must be defined!')",
"tantum_match = re.search('_(s[ei])$', tnode.t_lemma)\nif tantum_match:\n refl_form = tantum_match.group(1)\n afun = 'AuxT'\nelif tnode.voice == 'reflexive_diathesis' or tnode.gram_dia... | <|body_start_0|>
Block.__init__(self, scenario, args)
if self.language is None:
raise LoadingException('Language must be defined!')
<|end_body_0|>
<|body_start_1|>
tantum_match = re.search('_(s[ei])$', tnode.t_lemma)
if tantum_match:
refl_form = tantum_match.grou... | Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree | AddReflexiveParticles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_75kplus_train_074469 | 1,857 | permissive | [
{
"docstring": "Constructor, just checking the argument values",
"name": "__init__",
"signature": "def __init__(self, scenario, args)"
},
{
"docstring": "Add reflexive particle to a node, if applicable.",
"name": "process_tnode",
"signature": "def process_tnode(self, tnode)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002733 | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | Implement the Python class `AddReflexiveParticles` described below.
Class description:
Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree
Method signatures and docstrings:
- def __init__(self, scenario... | 73af644ec35c8a1cd0c37cd478c2afc1db717e0b | <|skeleton|>
class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddReflexiveParticles:
"""Add reflexive particles to reflexiva tantum and reflexive passive verbs. Arguments: language: the language of the target tree selector: the selector of the target tree"""
def __init__(self, scenario, args):
"""Constructor, just checking the argument values"""
Blo... | the_stack_v2_python_sparse | alex/components/nlg/tectotpl/block/t2a/cs/addreflexiveparticles.py | oplatek/alex | train | 0 |
4dee331a8972b0091f2b72085c9fc1f39448707e | [
"path = self.get_path(file_extension_provider)\nif self.logger is not None:\n self.logger.info('Reading {0}', path)\nfileobj = None\ntry:\n fileobj = open(path, 'rb')\nexcept FileNotFoundError as ex:\n if self.must_exist():\n raise ex\nreturn fileobj",
"path = self.get_path(file_extension_provider... | <|body_start_0|>
path = self.get_path(file_extension_provider)
if self.logger is not None:
self.logger.info('Reading {0}', path)
fileobj = None
try:
fileobj = open(path, 'rb')
except FileNotFoundError as ex:
if self.must_exist():
... | Implementation of AbstractPersistenceMechanism which saves objects to a local file. | LocalFilePersistenceMechanism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from th... | stack_v2_sparse_classes_75kplus_train_074470 | 2,635 | no_license | [
{
"docstring": ":param read_to_fileobj: A fileobj into which we will put all data read in from the persisted instance. :param file_extension_provider: An implementation of the FileExtensionProvider interface which is often related to the Serialization implementation. :param logger: A logger to send messaging to... | 2 | stack_v2_sparse_classes_30k_train_053088 | Implement the Python class `LocalFilePersistenceMechanism` described below.
Class description:
Implementation of AbstractPersistenceMechanism which saves objects to a local file.
Method signatures and docstrings:
- def open_source_for_read(self, read_to_fileobj, file_extension_provider=None): :param read_to_fileobj: ... | Implement the Python class `LocalFilePersistenceMechanism` described below.
Class description:
Implementation of AbstractPersistenceMechanism which saves objects to a local file.
Method signatures and docstrings:
- def open_source_for_read(self, read_to_fileobj, file_extension_provider=None): :param read_to_fileobj: ... | 99c2f401d6c4b203ee439ed607985a918d0c3c7e | <|skeleton|>
class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalFilePersistenceMechanism:
"""Implementation of AbstractPersistenceMechanism which saves objects to a local file."""
def open_source_for_read(self, read_to_fileobj, file_extension_provider=None):
""":param read_to_fileobj: A fileobj into which we will put all data read in from the persisted i... | the_stack_v2_python_sparse | servicecommon/persistence/mechanism/local_file_persistence_mechanism.py | Cognizant-CDB-AIA-BAI-AI-OI/LEAF-ENN-Training-V2 | train | 0 |
bd9f185dffea325adbcb05533204c1c76c784b25 | [
"self.dims = np.zeros(len(dims), dtype='int')\nself.dres = dres\nself.pini = np.zeros(len(pini), dtype='float')\nfor n in range(len(dims)):\n self.dims[n] = int(dims[n] / self.dres)\n self.pini[n] = float(pini[n])\nself.dims_m = self.dims * self.dres\nreturn",
"cad = '+' + '-' * 80 + '+\\n'\ncad += '|' + ' ... | <|body_start_0|>
self.dims = np.zeros(len(dims), dtype='int')
self.dres = dres
self.pini = np.zeros(len(pini), dtype='float')
for n in range(len(dims)):
self.dims[n] = int(dims[n] / self.dres)
self.pini[n] = float(pini[n])
self.dims_m = self.dims * self.dr... | Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room. | Room | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Room:
"""Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room."""
def __init__(self, dims=[1, 1, 1], dres=0.1, pini=[0, 0, 0]):
"""INPUTS: dims -> (list of floats) Dimensions of room (x,y,z) [meters] Example: [1.3,1.3,1.3] dres -> (int) ... | stack_v2_sparse_classes_75kplus_train_074471 | 4,355 | no_license | [
{
"docstring": "INPUTS: dims -> (list of floats) Dimensions of room (x,y,z) [meters] Example: [1.3,1.3,1.3] dres -> (int) Mesh resolution or space between nodes in mesh [meters] Example: 0.1 pini -> (list of floats) Initial point in general coordinates (x,y,z) where mesh is created [meters] Example: [0.,0.,0.]"... | 2 | stack_v2_sparse_classes_30k_train_015096 | Implement the Python class `Room` described below.
Class description:
Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room.
Method signatures and docstrings:
- def __init__(self, dims=[1, 1, 1], dres=0.1, pini=[0, 0, 0]): INPUTS: dims -> (list of floats) Dimensions of ro... | Implement the Python class `Room` described below.
Class description:
Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room.
Method signatures and docstrings:
- def __init__(self, dims=[1, 1, 1], dres=0.1, pini=[0, 0, 0]): INPUTS: dims -> (list of floats) Dimensions of ro... | b0c7a2b97f7924915e037dc7bd25a6e2978fecab | <|skeleton|>
class Room:
"""Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room."""
def __init__(self, dims=[1, 1, 1], dres=0.1, pini=[0, 0, 0]):
"""INPUTS: dims -> (list of floats) Dimensions of room (x,y,z) [meters] Example: [1.3,1.3,1.3] dres -> (int) ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Room:
"""Room mesh generator for FDTD Method: Pressure and Velocity mesh and physical parameters in the room."""
def __init__(self, dims=[1, 1, 1], dres=0.1, pini=[0, 0, 0]):
"""INPUTS: dims -> (list of floats) Dimensions of room (x,y,z) [meters] Example: [1.3,1.3,1.3] dres -> (int) Mesh resoluti... | the_stack_v2_python_sparse | fdtd/room.py | dot-gabriel-ferrer/AcousticFDTD | train | 0 |
1e33c702767336518cfa8ceb88e4edd034f3dbf6 | [
"self.marker_size = size\nself.marker_scale = scale\nself.type = 'Chessboard'",
"if flags is None:\n flags = 0\n flags |= cv2.CALIB_CB_ADAPTIVE_THRESH\n flags |= cv2.CALIB_CB_FAST_CHECK\n flags |= cv2.CALIB_CB_NORMALIZE_IMAGE\nret, corners = cv2.findChessboardCorners(gray, self.marker_size, flags=flag... | <|body_start_0|>
self.marker_size = size
self.marker_scale = scale
self.type = 'Chessboard'
<|end_body_0|>
<|body_start_1|>
if flags is None:
flags = 0
flags |= cv2.CALIB_CB_ADAPTIVE_THRESH
flags |= cv2.CALIB_CB_FAST_CHECK
flags |= cv2.CAL... | ChessboardFinder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
<|body_0|>
def find(self, gray, flags=None):
"""Given an image, this will return the corners... | stack_v2_sparse_classes_75kplus_train_074472 | 1,909 | no_license | [
{
"docstring": "size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)",
"name": "__init__",
"signature": "def __init__(self, size, scale)"
},
{
"docstring": "Given an image, this will return the corners. Optionally you can enter fla... | 4 | stack_v2_sparse_classes_30k_train_037947 | Implement the Python class `ChessboardFinder` described below.
Class description:
Implement the ChessboardFinder class.
Method signatures and docstrings:
- def __init__(self, size, scale): size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)
- def find(... | Implement the Python class `ChessboardFinder` described below.
Class description:
Implement the ChessboardFinder class.
Method signatures and docstrings:
- def __init__(self, size, scale): size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)
- def find(... | 1d6342d5516e5110f4ee5186431d9b4e2f75b734 | <|skeleton|>
class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
<|body_0|>
def find(self, gray, flags=None):
"""Given an image, this will return the corners... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChessboardFinder:
def __init__(self, size, scale):
"""size: pattern of chess board, tuple(rows, columns) scale: real-world dimension of square side, example, 2 cm (0.02 m)"""
self.marker_size = size
self.marker_scale = scale
self.type = 'Chessboard'
def find(self, gray, fl... | the_stack_v2_python_sparse | venv/Lib/site-packages/opencv_camera/targets/chessboard.py | yuchen556/E3845_ZQ | train | 0 | |
3d6cb4a82092bed82b0b7818f2f697f3293a3073 | [
"for pair in self.non_infinite_loop_pairs:\n self.assertFalse(results_in_infinite_loop(pair[0], pair[1]))\n self.assertTrue(is_power_of_two(pair[0] + pair[1]))",
"for pair in self.infinite_loop_pairs:\n self.assertTrue(results_in_infinite_loop(pair[0], pair[1]))\n self.assertFalse(is_power_of_two(pair... | <|body_start_0|>
for pair in self.non_infinite_loop_pairs:
self.assertFalse(results_in_infinite_loop(pair[0], pair[1]))
self.assertTrue(is_power_of_two(pair[0] + pair[1]))
<|end_body_0|>
<|body_start_1|>
for pair in self.infinite_loop_pairs:
self.assertTrue(results_i... | LoopTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoopTests:
def test_no_loop_if_sum_is_power_of_two(self):
"""Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the sum of the pairs are powers of 2"""
<|body_0|>
def test_loop_if_sum_is_not_power_of_... | stack_v2_sparse_classes_75kplus_train_074473 | 23,320 | no_license | [
{
"docstring": "Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the sum of the pairs are powers of 2",
"name": "test_no_loop_if_sum_is_power_of_two",
"signature": "def test_no_loop_if_sum_is_power_of_two(self)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_054747 | Implement the Python class `LoopTests` described below.
Class description:
Implement the LoopTests class.
Method signatures and docstrings:
- def test_no_loop_if_sum_is_power_of_two(self): Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the... | Implement the Python class `LoopTests` described below.
Class description:
Implement the LoopTests class.
Method signatures and docstrings:
- def test_no_loop_if_sum_is_power_of_two(self): Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the... | d8b9bb69f9ca12565200e99efb575988de10185e | <|skeleton|>
class LoopTests:
def test_no_loop_if_sum_is_power_of_two(self):
"""Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the sum of the pairs are powers of 2"""
<|body_0|>
def test_loop_if_sum_is_not_power_of_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoopTests:
def test_no_loop_if_sum_is_power_of_two(self):
"""Do not loop when the sum of the pair of numbers IS a power of 2 i.e., if the pair of numbers will NOT enter an infinite loop, the sum of the pairs are powers of 2"""
for pair in self.non_infinite_loop_pairs:
self.assertFa... | the_stack_v2_python_sparse | Level_4/7_DistractTheTrainers/solution.py | ken-power/Foobar_Challenge | train | 5 | |
ef930bdd773811b62dc2dea6a51025e8a1972d01 | [
"if not nums:\n return 0\nif len(nums) == 1:\n return 1\ntemp_num = nums[0]\ncount = 0\nfor index, num in enumerate(nums[1:]):\n if temp_num == num:\n del nums[index - count]\n count += 1\n else:\n temp_num = num\nreturn len(nums)",
"i = 0\nj = 1\nwhile j < len(nums):\n if nums... | <|body_start_0|>
if not nums:
return 0
if len(nums) == 1:
return 1
temp_num = nums[0]
count = 0
for index, num in enumerate(nums[1:]):
if temp_num == num:
del nums[index - count]
count += 1
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicatesB(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
... | stack_v2_sparse_classes_75kplus_train_074474 | 1,187 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicates",
"signature": "def removeDuplicates(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "removeDuplicatesB",
"signature": "def removeDuplicatesB(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053008 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicatesB(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeDuplicates(self, nums): :type nums: List[int] :rtype: int
- def removeDuplicatesB(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def ... | 128b567a4aa9eecfee3dc2b6599da6823e56b404 | <|skeleton|>
class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def removeDuplicatesB(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def removeDuplicates(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) == 1:
return 1
temp_num = nums[0]
count = 0
for index, num in enumerate(nums[1:]):
if temp_num == num:
... | the_stack_v2_python_sparse | leetCodeLearning/removeDuplicateNum.py | lyqtiffany/learngit | train | 0 | |
9b59af4e98e0d0f495a173948530287e74e1f842 | [
"super(TransformerSeq2SeqEncoderLayer, self).__init__()\nself.d_model = d_model\nself.n_head = n_head\nself.dim_ff = dim_ff\nself.dropout = dropout\nself.self_attn = MultiHeadAttention(d_model, n_head, dropout)\nself.attn_layer_norm = LayerNorm(d_model)\nself.ffn_layer_norm = LayerNorm(d_model)\nself.ffn = nn.Seque... | <|body_start_0|>
super(TransformerSeq2SeqEncoderLayer, self).__init__()
self.d_model = d_model
self.n_head = n_head
self.dim_ff = dim_ff
self.dropout = dropout
self.self_attn = MultiHeadAttention(d_model, n_head, dropout)
self.attn_layer_norm = LayerNorm(d_model)
... | TransformerSeq2SeqEncoderLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerSeq2SeqEncoderLayer:
def __init__(self, d_model: int=512, n_head: int=8, dim_ff: int=2048, dropout: float=0.1):
"""Self-Attention的Layer, :param int d_model: input和output的输出维度 :param int n_head: 多少个head,每个head的维度为d_model/n_head :param int dim_ff: FFN的维度大小 :param float dropout: ... | stack_v2_sparse_classes_75kplus_train_074475 | 7,093 | permissive | [
{
"docstring": "Self-Attention的Layer, :param int d_model: input和output的输出维度 :param int n_head: 多少个head,每个head的维度为d_model/n_head :param int dim_ff: FFN的维度大小 :param float dropout: Self-attention和FFN的dropout大小,0表示不drop",
"name": "__init__",
"signature": "def __init__(self, d_model: int=512, n_head: int=8, ... | 2 | stack_v2_sparse_classes_30k_val_001503 | Implement the Python class `TransformerSeq2SeqEncoderLayer` described below.
Class description:
Implement the TransformerSeq2SeqEncoderLayer class.
Method signatures and docstrings:
- def __init__(self, d_model: int=512, n_head: int=8, dim_ff: int=2048, dropout: float=0.1): Self-Attention的Layer, :param int d_model: i... | Implement the Python class `TransformerSeq2SeqEncoderLayer` described below.
Class description:
Implement the TransformerSeq2SeqEncoderLayer class.
Method signatures and docstrings:
- def __init__(self, d_model: int=512, n_head: int=8, dim_ff: int=2048, dropout: float=0.1): Self-Attention的Layer, :param int d_model: i... | 148ad1dcb7aa4990ac30d9a62ae8b89b6e706f8c | <|skeleton|>
class TransformerSeq2SeqEncoderLayer:
def __init__(self, d_model: int=512, n_head: int=8, dim_ff: int=2048, dropout: float=0.1):
"""Self-Attention的Layer, :param int d_model: input和output的输出维度 :param int n_head: 多少个head,每个head的维度为d_model/n_head :param int dim_ff: FFN的维度大小 :param float dropout: ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TransformerSeq2SeqEncoderLayer:
def __init__(self, d_model: int=512, n_head: int=8, dim_ff: int=2048, dropout: float=0.1):
"""Self-Attention的Layer, :param int d_model: input和output的输出维度 :param int n_head: 多少个head,每个head的维度为d_model/n_head :param int dim_ff: FFN的维度大小 :param float dropout: Self-attention... | the_stack_v2_python_sparse | fastNLP/modules/encoder/seq2seq_encoder.py | irfan11111111/fastNLP | train | 1 | |
69681c6b9bb47eebeae376956f516b8e865f1b86 | [
"worksheet.write(0, 0, 'Accound ID')\nworksheet.write(0, 1, 'Account Name')\nworksheet.write(0, 2, 'Issue ID')\nworksheet.write(0, 3, 'Issue Name')\nworksheet.write(0, 4, 'Region')\nworksheet.write(0, 5, 'Jiraticket')\nworksheet.write(0, 6, 'Owner_Id')\nworksheet.write(0, 7, 'BU')\nworksheet.write(0, 8, 'Product')\... | <|body_start_0|>
worksheet.write(0, 0, 'Accound ID')
worksheet.write(0, 1, 'Account Name')
worksheet.write(0, 2, 'Issue ID')
worksheet.write(0, 3, 'Issue Name')
worksheet.write(0, 4, 'Region')
worksheet.write(0, 5, 'Jiraticket')
worksheet.write(0, 6, 'Owner_Id')
... | Class to add Excel worksheet's headers and row data. | AddRecordsToSheet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddRecordsToSheet:
"""Class to add Excel worksheet's headers and row data."""
def add_header_data(worksheet, sheet_name):
"""Adding Security group excel sheet headers. :param worksheet: :return:"""
<|body_0|>
def add_records(worksheet, sheet_name, account_id, account_nam... | stack_v2_sparse_classes_75kplus_train_074476 | 1,972 | permissive | [
{
"docstring": "Adding Security group excel sheet headers. :param worksheet: :return:",
"name": "add_header_data",
"signature": "def add_header_data(worksheet, sheet_name)"
},
{
"docstring": "Adding security group records. :param worksheet: :param account_id :param account_name: :param issue_det... | 2 | stack_v2_sparse_classes_30k_train_041033 | Implement the Python class `AddRecordsToSheet` described below.
Class description:
Class to add Excel worksheet's headers and row data.
Method signatures and docstrings:
- def add_header_data(worksheet, sheet_name): Adding Security group excel sheet headers. :param worksheet: :return:
- def add_records(worksheet, she... | Implement the Python class `AddRecordsToSheet` described below.
Class description:
Class to add Excel worksheet's headers and row data.
Method signatures and docstrings:
- def add_header_data(worksheet, sheet_name): Adding Security group excel sheet headers. :param worksheet: :return:
- def add_records(worksheet, she... | fd2b29754fd3d297aa0af6fa5f9f337196f04e6d | <|skeleton|>
class AddRecordsToSheet:
"""Class to add Excel worksheet's headers and row data."""
def add_header_data(worksheet, sheet_name):
"""Adding Security group excel sheet headers. :param worksheet: :return:"""
<|body_0|>
def add_records(worksheet, sheet_name, account_id, account_nam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AddRecordsToSheet:
"""Class to add Excel worksheet's headers and row data."""
def add_header_data(worksheet, sheet_name):
"""Adding Security group excel sheet headers. :param worksheet: :return:"""
worksheet.write(0, 0, 'Accound ID')
worksheet.write(0, 1, 'Account Name')
w... | the_stack_v2_python_sparse | hammer/reporting-remediation/analytics/add_excel_sheet_records.py | kurmiashish/hammer | train | 0 |
46387d7f47da692898cc02ef9a31660e46dc86dc | [
"device = get_object_or_404(Device, slug=slug)\nself.check_object_permissions(request, device)\nserializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)\nreturn Response(data=serializer.data, status=status.HTTP_200_OK)",
"device = get_object_or_404(Device, slug=slug)\nself.check_object_permissions(r... | <|body_start_0|>
device = get_object_or_404(Device, slug=slug)
self.check_object_permissions(request, device)
serializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)
return Response(data=serializer.data, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
d... | DeviceRetrieveUpdateDestroyAPIView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, slug=None):
"""Update"""
<|body_1|>
def delete(self, request, slug=None):
"""Delete"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_75kplus_train_074477 | 5,225 | permissive | [
{
"docstring": "Retrieve",
"name": "get",
"signature": "def get(self, request, slug=None)"
},
{
"docstring": "Update",
"name": "put",
"signature": "def put(self, request, slug=None)"
},
{
"docstring": "Delete",
"name": "delete",
"signature": "def delete(self, request, slu... | 3 | stack_v2_sparse_classes_30k_train_010205 | Implement the Python class `DeviceRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the DeviceRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, slug=None): Update
- def delete(self, request, slug=None)... | Implement the Python class `DeviceRetrieveUpdateDestroyAPIView` described below.
Class description:
Implement the DeviceRetrieveUpdateDestroyAPIView class.
Method signatures and docstrings:
- def get(self, request, slug=None): Retrieve
- def put(self, request, slug=None): Update
- def delete(self, request, slug=None)... | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | <|skeleton|>
class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
<|body_0|>
def put(self, request, slug=None):
"""Update"""
<|body_1|>
def delete(self, request, slug=None):
"""Delete"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeviceRetrieveUpdateDestroyAPIView:
def get(self, request, slug=None):
"""Retrieve"""
device = get_object_or_404(Device, slug=slug)
self.check_object_permissions(request, device)
serializer = DeviceRetrieveUpdateDestroySerializer(device, many=False)
return Response(data... | the_stack_v2_python_sparse | mikaponics/device/views/resources/device_crud_api_views.py | mikaponics/mikaponics-back | train | 4 | |
cc2b11a5423c0a22227250d7864cb64f00955fb1 | [
"self.source_scene_name = bpy.context.scene.name\nself.target_asset_list = target_asset_list\nself.jsonoutput = None\n' Initialize logging variables '\nself.conout = False\nself.conoutmessage = None\nself.check = []\nself.error = []\nself.fail = []\nself.log = []\nself.success = []\nself.conoutmessage = '----------... | <|body_start_0|>
self.source_scene_name = bpy.context.scene.name
self.target_asset_list = target_asset_list
self.jsonoutput = None
' Initialize logging variables '
self.conout = False
self.conoutmessage = None
self.check = []
self.error = []
self.f... | Write presets selections for each item in corresponding asset folder | JSONExportPresets | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONExportPresets:
"""Write presets selections for each item in corresponding asset folder"""
def __init__(self, target_asset_list):
"""Initialize general variables"""
<|body_0|>
def execute(self):
"""Process actions"""
<|body_1|>
def json_encoder(se... | stack_v2_sparse_classes_75kplus_train_074478 | 44,083 | no_license | [
{
"docstring": "Initialize general variables",
"name": "__init__",
"signature": "def __init__(self, target_asset_list)"
},
{
"docstring": "Process actions",
"name": "execute",
"signature": "def execute(self)"
},
{
"docstring": "Create JSON output from collection/sub-collection",
... | 5 | stack_v2_sparse_classes_30k_test_002454 | Implement the Python class `JSONExportPresets` described below.
Class description:
Write presets selections for each item in corresponding asset folder
Method signatures and docstrings:
- def __init__(self, target_asset_list): Initialize general variables
- def execute(self): Process actions
- def json_encoder(self):... | Implement the Python class `JSONExportPresets` described below.
Class description:
Write presets selections for each item in corresponding asset folder
Method signatures and docstrings:
- def __init__(self, target_asset_list): Initialize general variables
- def execute(self): Process actions
- def json_encoder(self):... | 0788f00283d7c8c083aa5d554eb1f32c201adbd6 | <|skeleton|>
class JSONExportPresets:
"""Write presets selections for each item in corresponding asset folder"""
def __init__(self, target_asset_list):
"""Initialize general variables"""
<|body_0|>
def execute(self):
"""Process actions"""
<|body_1|>
def json_encoder(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JSONExportPresets:
"""Write presets selections for each item in corresponding asset folder"""
def __init__(self, target_asset_list):
"""Initialize general variables"""
self.source_scene_name = bpy.context.scene.name
self.target_asset_list = target_asset_list
self.jsonoutpu... | the_stack_v2_python_sparse | repos/blender_addons/internal/2.7.x/addon_customprops_preset.py | BlenderCN-Org/working_files | train | 0 |
eb39cd6014d393a90854bd3bf949ff5ec25522e3 | [
"if not validated_data.get('created', None):\n validated_data['created'] = timezone.now()\nvalidated_data['updated'] = timezone.now()\nif validated_data.get('created_by', None) is None:\n validated_data['created_by'] = self.context['request'].user\nif not validated_data.get('updated_by', None):\n validated... | <|body_start_0|>
if not validated_data.get('created', None):
validated_data['created'] = timezone.now()
validated_data['updated'] = timezone.now()
if validated_data.get('created_by', None) is None:
validated_data['created_by'] = self.context['request'].user
if not... | Injects the fields in the abstract base model as a model instance is being saved. | AbstractFieldsMixin | [
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
<|body_0|>
def get_fields(self):
"""Overridden to tak... | stack_v2_sparse_classes_75kplus_train_074479 | 2,081 | permissive | [
{
"docstring": "`created` and `created_by` are only mutated if they are null",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Overridden to take advantage of partial response",
"name": "get_fields",
"signature": "def get_fields(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002456 | Implement the Python class `AbstractFieldsMixin` described below.
Class description:
Injects the fields in the abstract base model as a model instance is being saved.
Method signatures and docstrings:
- def create(self, validated_data): `created` and `created_by` are only mutated if they are null
- def get_fields(sel... | Implement the Python class `AbstractFieldsMixin` described below.
Class description:
Injects the fields in the abstract base model as a model instance is being saved.
Method signatures and docstrings:
- def create(self, validated_data): `created` and `created_by` are only mutated if they are null
- def get_fields(sel... | ecbb8954053be06bbcac7e1132811d73534c78d9 | <|skeleton|>
class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
<|body_0|>
def get_fields(self):
"""Overridden to tak... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AbstractFieldsMixin:
"""Injects the fields in the abstract base model as a model instance is being saved."""
def create(self, validated_data):
"""`created` and `created_by` are only mutated if they are null"""
if not validated_data.get('created', None):
validated_data['created... | the_stack_v2_python_sparse | common/serializers/serializer_base.py | MasterFacilityList/mfl_api | train | 20 |
7489cd6b63305d07bbd9f5614369e8e7c5e58839 | [
"id_ = cid.hex\nif flag:\n string_form = id_[12:16]\nelse:\n string_form = id_[0:8]\nstring_form += id_[8:12]\nif flag:\n string_form += id_[0:8]\nelse:\n string_form += id_[12:16]\nstring_form += id_[16:]\nval = uuid.UUID(string_form)\nreturn val.bytes",
"id_ = uuid.UUID(bytes=cid).hex\nif flag:\n ... | <|body_start_0|>
id_ = cid.hex
if flag:
string_form = id_[12:16]
else:
string_form = id_[0:8]
string_form += id_[8:12]
if flag:
string_form += id_[0:8]
else:
string_form += id_[12:16]
string_form += id_[16:]
... | Utility functions for UUID-BIN conversion. | UUIDConversion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UUIDConversion:
"""Utility functions for UUID-BIN conversion."""
def uuid_to_bin(cid, flag):
"""Converts UUID string into binary."""
<|body_0|>
def bin_to_uuid(cid, flag):
"""Converts binary to UUID string."""
<|body_1|>
def mongodb_uuid(cid):
... | stack_v2_sparse_classes_75kplus_train_074480 | 9,612 | no_license | [
{
"docstring": "Converts UUID string into binary.",
"name": "uuid_to_bin",
"signature": "def uuid_to_bin(cid, flag)"
},
{
"docstring": "Converts binary to UUID string.",
"name": "bin_to_uuid",
"signature": "def bin_to_uuid(cid, flag)"
},
{
"docstring": "Converts UUID string to th... | 3 | stack_v2_sparse_classes_30k_val_002412 | Implement the Python class `UUIDConversion` described below.
Class description:
Utility functions for UUID-BIN conversion.
Method signatures and docstrings:
- def uuid_to_bin(cid, flag): Converts UUID string into binary.
- def bin_to_uuid(cid, flag): Converts binary to UUID string.
- def mongodb_uuid(cid): Converts U... | Implement the Python class `UUIDConversion` described below.
Class description:
Utility functions for UUID-BIN conversion.
Method signatures and docstrings:
- def uuid_to_bin(cid, flag): Converts UUID string into binary.
- def bin_to_uuid(cid, flag): Converts binary to UUID string.
- def mongodb_uuid(cid): Converts U... | 733a48b20fbe45fe86f656d6a40afdc41be2c223 | <|skeleton|>
class UUIDConversion:
"""Utility functions for UUID-BIN conversion."""
def uuid_to_bin(cid, flag):
"""Converts UUID string into binary."""
<|body_0|>
def bin_to_uuid(cid, flag):
"""Converts binary to UUID string."""
<|body_1|>
def mongodb_uuid(cid):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UUIDConversion:
"""Utility functions for UUID-BIN conversion."""
def uuid_to_bin(cid, flag):
"""Converts UUID string into binary."""
id_ = cid.hex
if flag:
string_form = id_[12:16]
else:
string_form = id_[0:8]
string_form += id_[8:12]
... | the_stack_v2_python_sparse | archive_crawling (as on Neo)/models.py | Anacoder1/archive_crawling | train | 0 |
ab749d70b3e2c5d4ccbb31dad8d9d17655d41afe | [
"debate_handler = DebateHandler()\nrebuttal = debate_handler.get(kwargs.get('rebuttal_uuid'))\ndebate = rebuttal.pointer\nreturn Response(status=status.HTTP_200_OK, data={'debate': self.serializer_class(debate).data, 'rebuttal': self.serializer_class(rebuttal).data})",
"rebuttal_form_validation = RebuttalForm(dat... | <|body_start_0|>
debate_handler = DebateHandler()
rebuttal = debate_handler.get(kwargs.get('rebuttal_uuid'))
debate = rebuttal.pointer
return Response(status=status.HTTP_200_OK, data={'debate': self.serializer_class(debate).data, 'rebuttal': self.serializer_class(rebuttal).data})
<|end_b... | Handle all rebuttal operations. | RebuttalView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RebuttalView:
"""Handle all rebuttal operations."""
def get(self, request, *args, **kwargs):
"""Get rebuttal and associated debate."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Post rebuttal against a debate."""
<|body_1|>
def put(self,... | stack_v2_sparse_classes_75kplus_train_074481 | 6,734 | no_license | [
{
"docstring": "Get rebuttal and associated debate.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Post rebuttal against a debate.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Update rebut... | 3 | stack_v2_sparse_classes_30k_train_005544 | Implement the Python class `RebuttalView` described below.
Class description:
Handle all rebuttal operations.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Get rebuttal and associated debate.
- def post(self, request, *args, **kwargs): Post rebuttal against a debate.
- def put(self, req... | Implement the Python class `RebuttalView` described below.
Class description:
Handle all rebuttal operations.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Get rebuttal and associated debate.
- def post(self, request, *args, **kwargs): Post rebuttal against a debate.
- def put(self, req... | 02bfc05a87462c288d0bc2b4c1f5269668961960 | <|skeleton|>
class RebuttalView:
"""Handle all rebuttal operations."""
def get(self, request, *args, **kwargs):
"""Get rebuttal and associated debate."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Post rebuttal against a debate."""
<|body_1|>
def put(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RebuttalView:
"""Handle all rebuttal operations."""
def get(self, request, *args, **kwargs):
"""Get rebuttal and associated debate."""
debate_handler = DebateHandler()
rebuttal = debate_handler.get(kwargs.get('rebuttal_uuid'))
debate = rebuttal.pointer
return Respo... | the_stack_v2_python_sparse | debate/views/v1.py | Sunrit07/rozprava-backend | train | 0 |
5c9f05f46527f6dc76d6bf40e1d2fa43fcb5b29f | [
"if request.user.is_authenticated:\n return redirect('account')\nreturn render(request, 'auth_form.html', self.ctx)",
"form = LoginForm(data=request.POST)\nif form.is_valid():\n email = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(email=email, password=p... | <|body_start_0|>
if request.user.is_authenticated:
return redirect('account')
return render(request, 'auth_form.html', self.ctx)
<|end_body_0|>
<|body_start_1|>
form = LoginForm(data=request.POST)
if form.is_valid():
email = request.POST.get('username')
... | Class handling the login form | LoginView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoginView:
"""Class handling the login form"""
def get(self, request, *args, **kwargs):
"""Renders the signup form, or redirect to 'account' if the user is already authenticated"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles the form validatio... | stack_v2_sparse_classes_75kplus_train_074482 | 5,701 | no_license | [
{
"docstring": "Renders the signup form, or redirect to 'account' if the user is already authenticated",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Handles the form validation and user authentication",
"name": "post",
"signature": "def post(s... | 2 | stack_v2_sparse_classes_30k_train_052044 | Implement the Python class `LoginView` described below.
Class description:
Class handling the login form
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Renders the signup form, or redirect to 'account' if the user is already authenticated
- def post(self, request, *args, **kwargs): Handl... | Implement the Python class `LoginView` described below.
Class description:
Class handling the login form
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Renders the signup form, or redirect to 'account' if the user is already authenticated
- def post(self, request, *args, **kwargs): Handl... | 9a58efe4a4c1dd0b3d27bbc01ee945baa6dc4e97 | <|skeleton|>
class LoginView:
"""Class handling the login form"""
def get(self, request, *args, **kwargs):
"""Renders the signup form, or redirect to 'account' if the user is already authenticated"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Handles the form validatio... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LoginView:
"""Class handling the login form"""
def get(self, request, *args, **kwargs):
"""Renders the signup form, or redirect to 'account' if the user is already authenticated"""
if request.user.is_authenticated:
return redirect('account')
return render(request, 'aut... | the_stack_v2_python_sparse | accounts/views.py | SebGoliot/oc_p8-purbeurre | train | 0 |
988321bb3f0f3978f5f741829432c2bfdde4be58 | [
"if token.base_form == '*':\n return WordRepr(token.surface, token.surface)\nelse:\n return WordRepr(token.surface, token.base_form)",
"base_form = token_detail.feature.base_form\nif base_form == '*':\n return WordRepr(token_detail.surface, token_detail.surface)\nelse:\n return WordRepr(token_detail.s... | <|body_start_0|>
if token.base_form == '*':
return WordRepr(token.surface, token.surface)
else:
return WordRepr(token.surface, token.base_form)
<|end_body_0|>
<|body_start_1|>
base_form = token_detail.feature.base_form
if base_form == '*':
return Word... | 単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形 | WordRepr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordRepr:
"""単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形"""
def from_token(cls, token: Token):
"""TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス"""
<|body_0|>
def from_token_detail(cls, token_detail: TokenDetail):
... | stack_v2_sparse_classes_75kplus_train_074483 | 12,296 | no_license | [
{
"docstring": "TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス",
"name": "from_token",
"signature": "def from_token(cls, token: Token)"
},
{
"docstring": "TokenDetailインスタンスからWordReprインスタンスを作成 Args: token_detail (TokenDetail): TokenDetailインスタンス Returns: Wo... | 2 | stack_v2_sparse_classes_30k_train_009447 | Implement the Python class `WordRepr` described below.
Class description:
単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形
Method signatures and docstrings:
- def from_token(cls, token: Token): TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス
- def from_token_detail(cl... | Implement the Python class `WordRepr` described below.
Class description:
単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形
Method signatures and docstrings:
- def from_token(cls, token: Token): TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス
- def from_token_detail(cl... | a4c6334b779a94814b7798a0fbfe9a148bf18d3a | <|skeleton|>
class WordRepr:
"""単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形"""
def from_token(cls, token: Token):
"""TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス"""
<|body_0|>
def from_token_detail(cls, token_detail: TokenDetail):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class WordRepr:
"""単語の表現情報 Attributes: surface (str): 表層形 base_form (str): 原形"""
def from_token(cls, token: Token):
"""TokenインスタンスからWordReprインスタンスを作成 Args: token (Token): Tokenインスタンス Returns: WordReprインスタンス"""
if token.base_form == '*':
return WordRepr(token.surface, token.surface)
... | the_stack_v2_python_sparse | src/review_research/nlp/nlp_types.py | S38knt-ks/ReviewResearch | train | 0 |
205748b941dfe8bdaa322345a11ceb5aa0b242b0 | [
"super().__init__(parent=parent)\nself.setLabel('left', 'I1 (arb.)')\nself.setLabel('bottom', 'I0 (micro J)')\nself.setTitle(f'MCP{idx + 1} correlation')\nself._idx = idx\nself._plot = self.plotScatter(brush=FColor.mkBrush(_DIGITIZER_CHANNEL_COLORS[idx], alpha=150))",
"data = self._data\ni1 = data['i1'][self._idx... | <|body_start_0|>
super().__init__(parent=parent)
self.setLabel('left', 'I1 (arb.)')
self.setLabel('bottom', 'I0 (micro J)')
self.setTitle(f'MCP{idx + 1} correlation')
self._idx = idx
self._plot = self.plotScatter(brush=FColor.mkBrush(_DIGITIZER_CHANNEL_COLORS[idx], alpha=... | XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel. | XasTimCorrelationPlot | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XasTimCorrelationPlot:
"""XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel."""
def __init__(self, idx, *, parent=None):
"""Initialization. :param int idx: channel index."""
<|body_0|>
def refresh(self):
"""Override."""
... | stack_v2_sparse_classes_75kplus_train_074484 | 13,999 | permissive | [
{
"docstring": "Initialization. :param int idx: channel index.",
"name": "__init__",
"signature": "def __init__(self, idx, *, parent=None)"
},
{
"docstring": "Override.",
"name": "refresh",
"signature": "def refresh(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046421 | Implement the Python class `XasTimCorrelationPlot` described below.
Class description:
XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel.
Method signatures and docstrings:
- def __init__(self, idx, *, parent=None): Initialization. :param int idx: channel index.
- def refresh(self... | Implement the Python class `XasTimCorrelationPlot` described below.
Class description:
XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel.
Method signatures and docstrings:
- def __init__(self, idx, *, parent=None): Initialization. :param int idx: channel index.
- def refresh(self... | a6ee28040b15ae8d110570bd9f3c37e5a3e70fc0 | <|skeleton|>
class XasTimCorrelationPlot:
"""XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel."""
def __init__(self, idx, *, parent=None):
"""Initialization. :param int idx: channel index."""
<|body_0|>
def refresh(self):
"""Override."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class XasTimCorrelationPlot:
"""XasTimCorrelationPlot class. Visualize correlation between I0 and I1 for single channel."""
def __init__(self, idx, *, parent=None):
"""Initialization. :param int idx: channel index."""
super().__init__(parent=parent)
self.setLabel('left', 'I1 (arb.)')
... | the_stack_v2_python_sparse | extra_foam/special_suite/xas_tim_w.py | European-XFEL/EXtra-foam | train | 8 |
9661ae37690b56ce481a2c9fd6d627122c3c916b | [
"if Session.__instance is None:\n Session()\nreturn Session.__instance",
"if Session.__instance is not None:\n raise Exception('This class is a singleton!')\nelse:\n Session.__instance = self\nself.session_id = StringExtensions.random(5)"
] | <|body_start_0|>
if Session.__instance is None:
Session()
return Session.__instance
<|end_body_0|>
<|body_start_1|>
if Session.__instance is not None:
raise Exception('This class is a singleton!')
else:
Session.__instance = self
self.session_i... | Session | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
def instance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if Session.__instance is None:
Session()
return Session.__insta... | stack_v2_sparse_classes_75kplus_train_074485 | 718 | permissive | [
{
"docstring": "Static access method.",
"name": "instance",
"signature": "def instance()"
},
{
"docstring": "Virtually private constructor.",
"name": "__init__",
"signature": "def __init__(self)"
}
] | 2 | null | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def instance(): Static access method.
- def __init__(self): Virtually private constructor. | Implement the Python class `Session` described below.
Class description:
Implement the Session class.
Method signatures and docstrings:
- def instance(): Static access method.
- def __init__(self): Virtually private constructor.
<|skeleton|>
class Session:
def instance():
"""Static access method."""
... | 54c6a435cda61f3e43ba8ba9ae81bb1d6f096a84 | <|skeleton|>
class Session:
def instance():
"""Static access method."""
<|body_0|>
def __init__(self):
"""Virtually private constructor."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Session:
def instance():
"""Static access method."""
if Session.__instance is None:
Session()
return Session.__instance
def __init__(self):
"""Virtually private constructor."""
if Session.__instance is not None:
raise Exception('This class i... | the_stack_v2_python_sparse | utils/session.py | codeworm47/CrawlerKing | train | 0 | |
2cc36959d7dd50f8e617eecf256633abd3de5ec6 | [
"self.validate_parameters(lei=lei)\n_query_builder = Configuration.get_base_uri()\n_query_builder += '/information/lei/{lei}/lookup'\n_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'lei': lei})\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/jso... | <|body_start_0|>
self.validate_parameters(lei=lei)
_query_builder = Configuration.get_base_uri()
_query_builder += '/information/lei/{lei}/lookup'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'lei': lei})
_query_url = APIHelper.clean_url(_query_... | A Controller to access Endpoints in the idfy_rest_client API. | LeiController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeiController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_lei_record(self, lei):
"""Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei (string): LEI to retrieve Returns: LeiRecord: Response f... | stack_v2_sparse_classes_75kplus_train_074486 | 5,533 | permissive | [
{
"docstring": "Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei (string): LEI to retrieve Returns: LeiRecord: Response from the API. OK Raises: APIException: When an error occurs while fetching the data from the remote API. This exception includes the HT... | 2 | null | Implement the Python class `LeiController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def retrieve_lei_record(self, lei): Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei... | Implement the Python class `LeiController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def retrieve_lei_record(self, lei): Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class LeiController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_lei_record(self, lei):
"""Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei (string): LEI to retrieve Returns: LeiRecord: Response f... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LeiController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def retrieve_lei_record(self, lei):
"""Does a GET request to /information/lei/{lei}/lookup. Retrieve the entity record for a given LEI Args: lei (string): LEI to retrieve Returns: LeiRecord: Response from the API. ... | the_stack_v2_python_sparse | idfy_rest_client/controllers/lei_controller.py | dealflowteam/Idfy | train | 0 |
d1bc76aeddd45b1980bd538252a41c1e94e5ebc9 | [
"assert n >= f, 'Number of states must be greater than number of \\n final states.'\nself.k = k\nself.n = n\nself.f = f\nself.deltaSize = n * k\nself.stateF = [1 for i in range(f)] + [0 for i in range(n - f)]\nself.stateDelta = [0 for i in range(self.deltaSize)]\nself.initial = True\nself.f... | <|body_start_0|>
assert n >= f, 'Number of states must be greater than number of \n final states.'
self.k = k
self.n = n
self.f = f
self.deltaSize = n * k
self.stateF = [1 for i in range(f)] + [0 for i in range(n - f)]
self.stateDelta = [0... | A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fields stateDelta, stateF, representing delta and F of the current DFA (see '_df... | EnumState | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumState:
"""A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fields stateDelta, stateF, representing del... | stack_v2_sparse_classes_75kplus_train_074487 | 8,049 | no_license | [
{
"docstring": "Initializes an initial enumeration state. The stateF-field states that the first f states are final. The stateDelta-field states that all transition end in the first state. We set the 'initial'-flag to true, to indicate that the first DFA is already given and must not be gained by incrementing."... | 4 | null | Implement the Python class `EnumState` described below.
Class description:
A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fiel... | Implement the Python class `EnumState` described below.
Class description:
A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fiel... | db11028bc8e3ba5006ddbb8476be28734767e022 | <|skeleton|>
class EnumState:
"""A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fields stateDelta, stateF, representing del... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnumState:
"""A state in a DFA enumeration. Provides method to get next state. A DFA enumeration in this project is characterized by k, n, f, denoting what kind of DFAs are produced during the enumeration. A DFA enumeration state is characterized by two fields stateDelta, stateF, representing delta and F of t... | the_stack_v2_python_sparse | db_enum.py | gregorhcs/Automatic-Generation-of-DFA-Minimization-Problems | train | 0 |
66355feb918e37114b4ad27a89e7764d8359dd88 | [
"assert len(input_shape) == 2\nBaseModel.__init__(self, input_shape, num_outputs, optimizer, 'FC_CONV')\nassert len(arch_config_files) == 3\nself.arch_config_files = arch_config_files",
"conv_input = layers.Input(shape=self.input_shape[0])\nscalar_features = layers.Input(shape=self.input_shape[1])\nflattened_conv... | <|body_start_0|>
assert len(input_shape) == 2
BaseModel.__init__(self, input_shape, num_outputs, optimizer, 'FC_CONV')
assert len(arch_config_files) == 3
self.arch_config_files = arch_config_files
<|end_body_0|>
<|body_start_1|>
conv_input = layers.Input(shape=self.input_shape[0... | FcConv | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FcConv:
def __init__(self, input_shape, num_outputs, optimizer, arch_config_files):
"""params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not included) num_outputs:num of neurons in the last layer optimizer: optimizer function used during tr... | stack_v2_sparse_classes_75kplus_train_074488 | 2,110 | no_license | [
{
"docstring": "params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not included) num_outputs:num of neurons in the last layer optimizer: optimizer function used during training arch_config_files:list of 3 files that specify the design of conv network,fc network and... | 2 | null | Implement the Python class `FcConv` described below.
Class description:
Implement the FcConv class.
Method signatures and docstrings:
- def __init__(self, input_shape, num_outputs, optimizer, arch_config_files): params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not incl... | Implement the Python class `FcConv` described below.
Class description:
Implement the FcConv class.
Method signatures and docstrings:
- def __init__(self, input_shape, num_outputs, optimizer, arch_config_files): params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not incl... | e282a54fc09be31291e4db77c5b04e7203d81b78 | <|skeleton|>
class FcConv:
def __init__(self, input_shape, num_outputs, optimizer, arch_config_files):
"""params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not included) num_outputs:num of neurons in the last layer optimizer: optimizer function used during tr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FcConv:
def __init__(self, input_shape, num_outputs, optimizer, arch_config_files):
"""params: input_shape: a list that specifies input_shapes of all the inputs to the model (batch dim not included) num_outputs:num of neurons in the last layer optimizer: optimizer function used during training arch_co... | the_stack_v2_python_sparse | models/fc_conv2D/fc_conv.py | internaccounts123/internship.ai | train | 0 | |
eb61fcc3acc3bd9619406313a1e48c7f64e90ef5 | [
"self.multiengine = multiengine\nself.dist = dist\nself.targets = targets\nself.block = block",
"max_len = max((len(s) for s in sequences))\nfor s in sequences:\n if len(s) != max_len:\n raise ValueError('all sequences must have equal length')\nassert isinstance(func, (str, FunctionType)), 'func must be... | <|body_start_0|>
self.multiengine = multiengine
self.dist = dist
self.targets = targets
self.block = block
<|end_body_0|>
<|body_start_1|>
max_len = max((len(s) for s in sequences))
for s in sequences:
if len(s) != max_len:
raise ValueError('a... | A Mapper for `IMultiEngine` implementers. | MultiEngineMapper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiEngineMapper:
"""A Mapper for `IMultiEngine` implementers."""
def __init__(self, multiengine, dist='b', targets='all', block=True):
"""Create a Mapper for a multiengine. The value of all arguments are used for all calls to `map`. This class allows these arguemnts to be set for a... | stack_v2_sparse_classes_75kplus_train_074489 | 8,554 | permissive | [
{
"docstring": "Create a Mapper for a multiengine. The value of all arguments are used for all calls to `map`. This class allows these arguemnts to be set for a series of map calls. :Parameters: multiengine : `IMultiEngine` implementer The multiengine to use for running the map commands dist : str The type of d... | 2 | stack_v2_sparse_classes_30k_train_049834 | Implement the Python class `MultiEngineMapper` described below.
Class description:
A Mapper for `IMultiEngine` implementers.
Method signatures and docstrings:
- def __init__(self, multiengine, dist='b', targets='all', block=True): Create a Mapper for a multiengine. The value of all arguments are used for all calls to... | Implement the Python class `MultiEngineMapper` described below.
Class description:
A Mapper for `IMultiEngine` implementers.
Method signatures and docstrings:
- def __init__(self, multiengine, dist='b', targets='all', block=True): Create a Mapper for a multiengine. The value of all arguments are used for all calls to... | 1cf44de3833929a4cf9e0069e8c75ef9086eeaca | <|skeleton|>
class MultiEngineMapper:
"""A Mapper for `IMultiEngine` implementers."""
def __init__(self, multiengine, dist='b', targets='all', block=True):
"""Create a Mapper for a multiengine. The value of all arguments are used for all calls to `map`. This class allows these arguemnts to be set for a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiEngineMapper:
"""A Mapper for `IMultiEngine` implementers."""
def __init__(self, multiengine, dist='b', targets='all', block=True):
"""Create a Mapper for a multiengine. The value of all arguments are used for all calls to `map`. This class allows these arguemnts to be set for a series of ma... | the_stack_v2_python_sparse | IPython/kernel/mapper.py | omazapa/ipython | train | 3 |
da2a55412d5a053b87096105d6484e855feda29f | [
"questions = Question.get(limit=limit, offset=offset)\nserializer = serialize(QuestionListSerializer, questions)\nreturn QuaApiResponse(serializer.data)",
"serializer = deserialize(QuestionSerializer, data=request.data)\nserializer.save(user=request.user)\nreturn QuaApiResponse(serializer.data)"
] | <|body_start_0|>
questions = Question.get(limit=limit, offset=offset)
serializer = serialize(QuestionListSerializer, questions)
return QuaApiResponse(serializer.data)
<|end_body_0|>
<|body_start_1|>
serializer = deserialize(QuestionSerializer, data=request.data)
serializer.save(... | QuestionListView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionListView:
def get(self, request, limit=settings.PAGE_SIZE, offset=0):
"""Get list of questions"""
<|body_0|>
def post(self, request):
"""Create new question"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
questions = Question.get(limit=limit... | stack_v2_sparse_classes_75kplus_train_074490 | 1,772 | no_license | [
{
"docstring": "Get list of questions",
"name": "get",
"signature": "def get(self, request, limit=settings.PAGE_SIZE, offset=0)"
},
{
"docstring": "Create new question",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016932 | Implement the Python class `QuestionListView` described below.
Class description:
Implement the QuestionListView class.
Method signatures and docstrings:
- def get(self, request, limit=settings.PAGE_SIZE, offset=0): Get list of questions
- def post(self, request): Create new question | Implement the Python class `QuestionListView` described below.
Class description:
Implement the QuestionListView class.
Method signatures and docstrings:
- def get(self, request, limit=settings.PAGE_SIZE, offset=0): Get list of questions
- def post(self, request): Create new question
<|skeleton|>
class QuestionListV... | 670752a3b48619eeba2fa9f2cf133e6050737a73 | <|skeleton|>
class QuestionListView:
def get(self, request, limit=settings.PAGE_SIZE, offset=0):
"""Get list of questions"""
<|body_0|>
def post(self, request):
"""Create new question"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class QuestionListView:
def get(self, request, limit=settings.PAGE_SIZE, offset=0):
"""Get list of questions"""
questions = Question.get(limit=limit, offset=offset)
serializer = serialize(QuestionListSerializer, questions)
return QuaApiResponse(serializer.data)
def post(self, re... | the_stack_v2_python_sparse | controller/src/api/views/questions.py | Sapunov/qua | train | 1 | |
a0999f2a3adadb1cb48adf1fdfd24dfd49d46c98 | [
"create_label_url = f'https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={self.token}'\nreq = {'method': 'post', 'url': create_label_url, 'json': {'tagname': '测试', 'tagid': tagid}}\nr = self.send_requests(req)\nreturn r.json()",
"update_label_url = f'https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_... | <|body_start_0|>
create_label_url = f'https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={self.token}'
req = {'method': 'post', 'url': create_label_url, 'json': {'tagname': '测试', 'tagid': tagid}}
r = self.send_requests(req)
return r.json()
<|end_body_0|>
<|body_start_1|>
... | 标签管理 | Label | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Label:
"""标签管理"""
def create_label(self, tagid):
"""创建标签"""
<|body_0|>
def update_label(self, tagid):
"""修改标签名字"""
<|body_1|>
def delete_label(self, tagid):
"""删除标签"""
<|body_2|>
def get_label_memberlist(self):
"""获取标签列表"... | stack_v2_sparse_classes_75kplus_train_074491 | 2,805 | no_license | [
{
"docstring": "创建标签",
"name": "create_label",
"signature": "def create_label(self, tagid)"
},
{
"docstring": "修改标签名字",
"name": "update_label",
"signature": "def update_label(self, tagid)"
},
{
"docstring": "删除标签",
"name": "delete_label",
"signature": "def delete_label(se... | 4 | stack_v2_sparse_classes_30k_train_023028 | Implement the Python class `Label` described below.
Class description:
标签管理
Method signatures and docstrings:
- def create_label(self, tagid): 创建标签
- def update_label(self, tagid): 修改标签名字
- def delete_label(self, tagid): 删除标签
- def get_label_memberlist(self): 获取标签列表 | Implement the Python class `Label` described below.
Class description:
标签管理
Method signatures and docstrings:
- def create_label(self, tagid): 创建标签
- def update_label(self, tagid): 修改标签名字
- def delete_label(self, tagid): 删除标签
- def get_label_memberlist(self): 获取标签列表
<|skeleton|>
class Label:
"""标签管理"""
def ... | 26b4211a9548a96838bb571030c59bee7c1ad77a | <|skeleton|>
class Label:
"""标签管理"""
def create_label(self, tagid):
"""创建标签"""
<|body_0|>
def update_label(self, tagid):
"""修改标签名字"""
<|body_1|>
def delete_label(self, tagid):
"""删除标签"""
<|body_2|>
def get_label_memberlist(self):
"""获取标签列表"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Label:
"""标签管理"""
def create_label(self, tagid):
"""创建标签"""
create_label_url = f'https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token={self.token}'
req = {'method': 'post', 'url': create_label_url, 'json': {'tagname': '测试', 'tagid': tagid}}
r = self.send_requests(re... | the_stack_v2_python_sparse | Python_testing/Work10/api/label.py | Lcq-z/Pythontestpro | train | 0 |
3723b140e34e94025c6f6a8400bbe3361c257f7a | [
"for name, hook in what.iteritems():\n func = getattr(target, name)\n if not isinstance(func, HookedMethod):\n func = HookedMethod(func)\n setattr(target, name, func)\n func.pending.append(hook)",
"for name, hook in what.iteritems():\n hooked = getattr(target, name)\n if hook in hooke... | <|body_start_0|>
for name, hook in what.iteritems():
func = getattr(target, name)
if not isinstance(func, HookedMethod):
func = HookedMethod(func)
setattr(target, name, func)
func.pending.append(hook)
<|end_body_0|>
<|body_start_1|>
fo... | HookSet | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HookSet:
def install_hooks(target, **what):
""":param target: :param what: :return:"""
<|body_0|>
def remove_hooks(target, **what):
""":param target: :param what: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for name, hook in what.iterit... | stack_v2_sparse_classes_75kplus_train_074492 | 1,672 | permissive | [
{
"docstring": ":param target: :param what: :return:",
"name": "install_hooks",
"signature": "def install_hooks(target, **what)"
},
{
"docstring": ":param target: :param what: :return:",
"name": "remove_hooks",
"signature": "def remove_hooks(target, **what)"
}
] | 2 | stack_v2_sparse_classes_30k_val_001682 | Implement the Python class `HookSet` described below.
Class description:
Implement the HookSet class.
Method signatures and docstrings:
- def install_hooks(target, **what): :param target: :param what: :return:
- def remove_hooks(target, **what): :param target: :param what: :return: | Implement the Python class `HookSet` described below.
Class description:
Implement the HookSet class.
Method signatures and docstrings:
- def install_hooks(target, **what): :param target: :param what: :return:
- def remove_hooks(target, **what): :param target: :param what: :return:
<|skeleton|>
class HookSet:
d... | 18b77c72bd12de2e3c510a5792434386a79ccfa8 | <|skeleton|>
class HookSet:
def install_hooks(target, **what):
""":param target: :param what: :return:"""
<|body_0|>
def remove_hooks(target, **what):
""":param target: :param what: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HookSet:
def install_hooks(target, **what):
""":param target: :param what: :return:"""
for name, hook in what.iteritems():
func = getattr(target, name)
if not isinstance(func, HookedMethod):
func = HookedMethod(func)
setattr(target, name,... | the_stack_v2_python_sparse | angr/misc/hookset.py | ercoppa/angr | train | 1 | |
cbf39dd01ab213b98adfb0e9819135f85826e7d5 | [
"super().__init__()\nself._hass = hass\nself._update_interval = update_interval\nself._subscriptions = {}\nself._unsub_interval = None\nself._stop_interval = None",
"if not self._subscriptions:\n self._async_setup_listeners()\nself._subscriptions.setdefault(device_id, []).append(update_callback)\n\ndef _unsubs... | <|body_start_0|>
super().__init__()
self._hass = hass
self._update_interval = update_interval
self._subscriptions = {}
self._unsub_interval = None
self._stop_interval = None
<|end_body_0|>
<|body_start_1|>
if not self._subscriptions:
self._async_setup... | Base implementation for a subscriber. | AugustSubscriberMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugustSubscriberMixin:
"""Base implementation for a subscriber."""
def __init__(self, hass, update_interval):
"""Initialize an subscriber."""
<|body_0|>
def async_subscribe_device_id(self, device_id, update_callback):
"""Add an callback subscriber. Returns a call... | stack_v2_sparse_classes_75kplus_train_074493 | 2,429 | permissive | [
{
"docstring": "Initialize an subscriber.",
"name": "__init__",
"signature": "def __init__(self, hass, update_interval)"
},
{
"docstring": "Add an callback subscriber. Returns a callable that can be used to unsubscribe.",
"name": "async_subscribe_device_id",
"signature": "def async_subsc... | 5 | null | Implement the Python class `AugustSubscriberMixin` described below.
Class description:
Base implementation for a subscriber.
Method signatures and docstrings:
- def __init__(self, hass, update_interval): Initialize an subscriber.
- def async_subscribe_device_id(self, device_id, update_callback): Add an callback subsc... | Implement the Python class `AugustSubscriberMixin` described below.
Class description:
Base implementation for a subscriber.
Method signatures and docstrings:
- def __init__(self, hass, update_interval): Initialize an subscriber.
- def async_subscribe_device_id(self, device_id, update_callback): Add an callback subsc... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class AugustSubscriberMixin:
"""Base implementation for a subscriber."""
def __init__(self, hass, update_interval):
"""Initialize an subscriber."""
<|body_0|>
def async_subscribe_device_id(self, device_id, update_callback):
"""Add an callback subscriber. Returns a call... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AugustSubscriberMixin:
"""Base implementation for a subscriber."""
def __init__(self, hass, update_interval):
"""Initialize an subscriber."""
super().__init__()
self._hass = hass
self._update_interval = update_interval
self._subscriptions = {}
self._unsub_i... | the_stack_v2_python_sparse | homeassistant/components/august/subscriber.py | konnected-io/home-assistant | train | 24 |
47bf006c512ea26638ffafcfc6020ebef3bf880a | [
"Idevice.__init__(self, x_(u'Multi-select'), x_(u'University of Auckland'), x_(u'Unlike the MCQ the SCORM quiz is used to test \\nthe learners knowledge on a topic without providing the learner with feedback \\nto the correct answer. The quiz will often be given once the learner has had \\ntime to learn and practic... | <|body_start_0|>
Idevice.__init__(self, x_(u'Multi-select'), x_(u'University of Auckland'), x_(u'Unlike the MCQ the SCORM quiz is used to test \nthe learners knowledge on a topic without providing the learner with feedback \nto the correct answer. The quiz will often be given once the learner has had \ntime to ... | A MultiSelect Idevice is one built up from question and options | MultiSelectIdevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSelectIdevice:
"""A MultiSelect Idevice is one built up from question and options"""
def __init__(self):
"""Initialize"""
<|body_0|>
def addQuestion(self):
"""Add a new question to this iDevice."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074494 | 1,341 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add a new question to this iDevice.",
"name": "addQuestion",
"signature": "def addQuestion(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001013 | Implement the Python class `MultiSelectIdevice` described below.
Class description:
A MultiSelect Idevice is one built up from question and options
Method signatures and docstrings:
- def __init__(self): Initialize
- def addQuestion(self): Add a new question to this iDevice. | Implement the Python class `MultiSelectIdevice` described below.
Class description:
A MultiSelect Idevice is one built up from question and options
Method signatures and docstrings:
- def __init__(self): Initialize
- def addQuestion(self): Add a new question to this iDevice.
<|skeleton|>
class MultiSelectIdevice:
... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class MultiSelectIdevice:
"""A MultiSelect Idevice is one built up from question and options"""
def __init__(self):
"""Initialize"""
<|body_0|>
def addQuestion(self):
"""Add a new question to this iDevice."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiSelectIdevice:
"""A MultiSelect Idevice is one built up from question and options"""
def __init__(self):
"""Initialize"""
Idevice.__init__(self, x_(u'Multi-select'), x_(u'University of Auckland'), x_(u'Unlike the MCQ the SCORM quiz is used to test \nthe learners knowledge on a topic ... | the_stack_v2_python_sparse | eXe/rev2283-2409/left-trunk-2409/exe/engine/multiselectidevice.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
15df7f7977e22b51840ba30fbf38d582dd726cda | [
"for i in range(3):\n try:\n redis_obj.rpush(submit_key, product_info)\n break\n except Exception as e:\n print(e)\n continue",
"if Recommend_product_url_list:\n for one_Recommend_product_url in Recommend_product_url_list:\n if one_Recommend_product_url:\n tr... | <|body_start_0|>
for i in range(3):
try:
redis_obj.rpush(submit_key, product_info)
break
except Exception as e:
print(e)
continue
<|end_body_0|>
<|body_start_1|>
if Recommend_product_url_list:
for one_Re... | 提供scrapy使用打扩展功能模块 | MYREDIS | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MYREDIS:
"""提供scrapy使用打扩展功能模块"""
def submit_Product_info(self, redis_obj, product_info):
"""往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:"""
<|body_0|>
def add_Url(self, redis_obj, submit_key, Recommend_product_url_list):
"""添加获取下来的u... | stack_v2_sparse_classes_75kplus_train_074495 | 2,144 | no_license | [
{
"docstring": "往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:",
"name": "submit_Product_info",
"signature": "def submit_Product_info(self, redis_obj, product_info)"
},
{
"docstring": "添加获取下来的url :param redis_obj: :param submit_key: :param product_info: :return:",
... | 3 | stack_v2_sparse_classes_30k_train_015726 | Implement the Python class `MYREDIS` described below.
Class description:
提供scrapy使用打扩展功能模块
Method signatures and docstrings:
- def submit_Product_info(self, redis_obj, product_info): 往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:
- def add_Url(self, redis_obj, submit_key, Recommend_produc... | Implement the Python class `MYREDIS` described below.
Class description:
提供scrapy使用打扩展功能模块
Method signatures and docstrings:
- def submit_Product_info(self, redis_obj, product_info): 往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:
- def add_Url(self, redis_obj, submit_key, Recommend_produc... | c959fd20bb76d6a72236352471d7e8aa6f3ff812 | <|skeleton|>
class MYREDIS:
"""提供scrapy使用打扩展功能模块"""
def submit_Product_info(self, redis_obj, product_info):
"""往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:"""
<|body_0|>
def add_Url(self, redis_obj, submit_key, Recommend_product_url_list):
"""添加获取下来的u... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MYREDIS:
"""提供scrapy使用打扩展功能模块"""
def submit_Product_info(self, redis_obj, product_info):
"""往远程数传输数据 :param redis_obj: :param submit_key: :param product_info: :return:"""
for i in range(3):
try:
redis_obj.rpush(submit_key, product_info)
break
... | the_stack_v2_python_sparse | AMA_DATABASE/Xuggest_myredis.py | Darren-kun/Xuggest | train | 0 |
b3c1daa337ed1b01db05f4dd3a428f4de5ececc4 | [
"self.last_protection_run_summary = last_protection_run_summary\nself.pagination_cookie = pagination_cookie\nself.protected_sources_summary = protected_sources_summary\nself.protection_jobs_summary = protection_jobs_summary\nself.protection_policy = protection_policy\nself.protection_runs_summary = protection_runs_... | <|body_start_0|>
self.last_protection_run_summary = last_protection_run_summary
self.pagination_cookie = pagination_cookie
self.protected_sources_summary = protected_sources_summary
self.protection_jobs_summary = protection_jobs_summary
self.protection_policy = protection_policy
... | Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the related Protection Sources and Protection Jobs. pagin... | ProtectionPolicySummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the re... | stack_v2_sparse_classes_75kplus_train_074496 | 5,366 | permissive | [
{
"docstring": "Constructor for the ProtectionPolicySummary class",
"name": "__init__",
"signature": "def __init__(self, last_protection_run_summary=None, pagination_cookie=None, protected_sources_summary=None, protection_jobs_summary=None, protection_policy=None, protection_runs_summary=None)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_043007 | Implement the Python class `ProtectionPolicySummary` described below.
Class description:
Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of... | Implement the Python class `ProtectionPolicySummary` described below.
Class description:
Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectionPolicySummary:
"""Implementation of the 'ProtectionPolicySummary' model. ProtectionPolicySummary specifies protection summary of a given Protection Policy. Attributes: last_protection_run_summary (LastProtectionRunSummary): Specifies the summary of the last Protection Runs of all the related Protect... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protection_policy_summary.py | cohesity/management-sdk-python | train | 24 |
1dc69becaf9409ddb79041ac07f7d8d1bdc19513 | [
"self.dbname = dbname\nself.username = username\nself.passwd = passwd\nself.hostname = hostname\nself.sport = sport\nself.racflag = racflag\nself.__name__ = 'Connect'",
"try:\n connect = pgsql.connect(database=self.dbname, user=self.username, password=self.passwd, host=self.hostname, port=self.sport)\nexcept p... | <|body_start_0|>
self.dbname = dbname
self.username = username
self.passwd = passwd
self.hostname = hostname
self.sport = sport
self.racflag = racflag
self.__name__ = 'Connect'
<|end_body_0|>
<|body_start_1|>
try:
connect = pgsql.connect(datab... | Class to connect DB. | Connect | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Connect:
"""Class to connect DB."""
def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False):
"""Constructor."""
<|body_0|>
def tns_connect(self):
"""Connect with tnscon string."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_074497 | 9,898 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False)"
},
{
"docstring": "Connect with tnscon string.",
"name": "tns_connect",
"signature": "def tns_connect(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037938 | Implement the Python class `Connect` described below.
Class description:
Class to connect DB.
Method signatures and docstrings:
- def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False): Constructor.
- def tns_connect(self): Connect with tnscon string. | Implement the Python class `Connect` described below.
Class description:
Class to connect DB.
Method signatures and docstrings:
- def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False): Constructor.
- def tns_connect(self): Connect with tnscon string.
<|skeleton|>
class Connect:
"""Cla... | d1f626969bca70ca1c0309fc501d4e3848540a58 | <|skeleton|>
class Connect:
"""Class to connect DB."""
def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False):
"""Constructor."""
<|body_0|>
def tns_connect(self):
"""Connect with tnscon string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Connect:
"""Class to connect DB."""
def __init__(self, dbname, username, passwd, hostname, sport=5432, racflag=False):
"""Constructor."""
self.dbname = dbname
self.username = username
self.passwd = passwd
self.hostname = hostname
self.sport = sport
... | the_stack_v2_python_sparse | swarms/utils/db.py | aadeshnpn/swarm | train | 12 |
e312b1d5d6279ab5fa4cae313f044f9ed3b4a023 | [
"actual = clean_text('check out this link: https://cyphon.io')\nexpected = 'check out this link'\nself.assertEqual(actual, expected)",
"actual = clean_text('@foobar hey there')\nexpected = 'hey there'\nself.assertEqual(actual, expected)",
"actual = clean_text('#foobar hey there')\nexpected = 'foobar hey there'\... | <|body_start_0|>
actual = clean_text('check out this link: https://cyphon.io')
expected = 'check out this link'
self.assertEqual(actual, expected)
<|end_body_0|>
<|body_start_1|>
actual = clean_text('@foobar hey there')
expected = 'hey there'
self.assertEqual(actual, exp... | Tests the clean_text() function. | CleanTextTestCase | [
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleanTextTestCase:
"""Tests the clean_text() function."""
def test_clean_url(self):
"""Tests the clean_text() function for text containing a URL."""
<|body_0|>
def test_clean_at(self):
"""Tests the clean_text() function for text containing an @ symbol."""
... | stack_v2_sparse_classes_75kplus_train_074498 | 4,456 | permissive | [
{
"docstring": "Tests the clean_text() function for text containing a URL.",
"name": "test_clean_url",
"signature": "def test_clean_url(self)"
},
{
"docstring": "Tests the clean_text() function for text containing an @ symbol.",
"name": "test_clean_at",
"signature": "def test_clean_at(se... | 3 | stack_v2_sparse_classes_30k_train_033491 | Implement the Python class `CleanTextTestCase` described below.
Class description:
Tests the clean_text() function.
Method signatures and docstrings:
- def test_clean_url(self): Tests the clean_text() function for text containing a URL.
- def test_clean_at(self): Tests the clean_text() function for text containing an... | Implement the Python class `CleanTextTestCase` described below.
Class description:
Tests the clean_text() function.
Method signatures and docstrings:
- def test_clean_url(self): Tests the clean_text() function for text containing a URL.
- def test_clean_at(self): Tests the clean_text() function for text containing an... | a379a134c0c5af14df4ed2afa066c1626506b754 | <|skeleton|>
class CleanTextTestCase:
"""Tests the clean_text() function."""
def test_clean_url(self):
"""Tests the clean_text() function for text containing a URL."""
<|body_0|>
def test_clean_at(self):
"""Tests the clean_text() function for text containing an @ symbol."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CleanTextTestCase:
"""Tests the clean_text() function."""
def test_clean_url(self):
"""Tests the clean_text() function for text containing a URL."""
actual = clean_text('check out this link: https://cyphon.io')
expected = 'check out this link'
self.assertEqual(actual, expe... | the_stack_v2_python_sparse | Incident-Response/Tools/cyphon/cyphon/lab/sentiment/test_sentiment.py | foss2cyber/Incident-Playbook | train | 1 |
7d30add9a01cecdcd566bca67de339a4bf9ba343 | [
"SpsSequence.__init__(self, cams, **seqKeys)\ncameraWithHexapodPowerCycled = [cam for cam in cams if cam.specName in hexapodOff]\nif cameraWithHexapodPowerCycled:\n self.expose('arc', lampsKeys, cameraWithHexapodPowerCycled, duplicate=duplicate)\nself.add('sps', 'slit start', cams=cams)\nself.add('sps', 'slit ho... | <|body_start_0|>
SpsSequence.__init__(self, cams, **seqKeys)
cameraWithHexapodPowerCycled = [cam for cam in cams if cam.specName in hexapodOff]
if cameraWithHexapodPowerCycled:
self.expose('arc', lampsKeys, cameraWithHexapodPowerCycled, duplicate=duplicate)
self.add('sps', 's... | hexapod stability sequence | HexapodStability | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HexapodStability:
"""hexapod stability sequence"""
def __init__(self, cams, lampsKeys, duplicate, positions, hexapodOff, **seqKeys):
"""Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions for the slit dither and shift grid. Default=[0.05, 0.04,... | stack_v2_sparse_classes_75kplus_train_074499 | 4,346 | no_license | [
{
"docstring": "Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions for the slit dither and shift grid. Default=[0.05, 0.04, 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0.03, -0.04, -0.05] duplicate : `int` the number of exposures to take at each position. Notes ----- The cams/sm... | 2 | stack_v2_sparse_classes_30k_train_017987 | Implement the Python class `HexapodStability` described below.
Class description:
hexapod stability sequence
Method signatures and docstrings:
- def __init__(self, cams, lampsKeys, duplicate, positions, hexapodOff, **seqKeys): Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions... | Implement the Python class `HexapodStability` described below.
Class description:
hexapod stability sequence
Method signatures and docstrings:
- def __init__(self, cams, lampsKeys, duplicate, positions, hexapodOff, **seqKeys): Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions... | 4de50d621193346af0933e85ecdc6fe8b82eed3e | <|skeleton|>
class HexapodStability:
"""hexapod stability sequence"""
def __init__(self, cams, lampsKeys, duplicate, positions, hexapodOff, **seqKeys):
"""Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions for the slit dither and shift grid. Default=[0.05, 0.04,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HexapodStability:
"""hexapod stability sequence"""
def __init__(self, cams, lampsKeys, duplicate, positions, hexapodOff, **seqKeys):
"""Acquire a hexapod repeatability grid. Args ---- positions : vector of `float` the positions for the slit dither and shift grid. Default=[0.05, 0.04, 0.03, 0.02, ... | the_stack_v2_python_sparse | python/ics/iicActor/sequenceList/sps/engineering.py | Subaru-PFS/ics_iicActor | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.