blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43125d3259fb43e379c618c84efcdd3900264e48 | [
"if numRows == 1 or numRows >= len(s):\n return s\noutput = [''] * numRows\nindex, step = (0, 0)\nfor c in s:\n output[index] += c\n if index == 0:\n step = 1\n elif index == numRows - 1:\n step = -1\n index += step\nreturn ''.join(output)",
"if numRows == 1:\n return s\nstep = 2 *... | <|body_start_0|>
if numRows == 1 or numRows >= len(s):
return s
output = [''] * numRows
index, step = (0, 0)
for c in s:
output[index] += c
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if numRows == 1 or nu... | stack_v2_sparse_classes_36k_train_003100 | 1,777 | no_license | [
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "convert",
"signature": "def convert(self, s, numRows)"
},
{
"docstring": ":type s: str :type numRows: int :rtype: str",
"name": "convert",
"signature": "def convert(self, s, numRows)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
- def convert(self, s, numRows): :type s: str :type numRows: int :rtype: str
<|skeleton|>
class Soluti... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_0|>
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def convert(self, s, numRows):
""":type s: str :type numRows: int :rtype: str"""
if numRows == 1 or numRows >= len(s):
return s
output = [''] * numRows
index, step = (0, 0)
for c in s:
output[index] += c
if index == 0:
... | the_stack_v2_python_sparse | src/lt_6.py | oxhead/CodingYourWay | train | 0 | |
bb52941cf047374e96790e03d6d0108ab0dc7e61 | [
"wf_service = netsvc.LocalService('workflow')\nsuper(stock_picking, self).action_done(cr, uid, ids, context=context)\npicking_obj = self.pool.get('stock.picking')\nfor picking_record in self.browse(cr, uid, ids):\n if picking_record.type == 'in':\n if picking_record.purchase_id:\n if picking_re... | <|body_start_0|>
wf_service = netsvc.LocalService('workflow')
super(stock_picking, self).action_done(cr, uid, ids, context=context)
picking_obj = self.pool.get('stock.picking')
for picking_record in self.browse(cr, uid, ids):
if picking_record.type == 'in':
if... | stock_picking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
<|body_0|>
def goods_recieved(self, cr, uid, ids, context=None):
"""Change State To Picking confirmed"""
<|b... | stack_v2_sparse_classes_36k_train_003101 | 3,934 | no_license | [
{
"docstring": "Checks if Goods avaiable in stock after Purchases Procedure done @return: True",
"name": "action_done",
"signature": "def action_done(self, cr, uid, ids, context=None)"
},
{
"docstring": "Change State To Picking confirmed",
"name": "goods_recieved",
"signature": "def good... | 2 | stack_v2_sparse_classes_30k_train_018852 | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def action_done(self, cr, uid, ids, context=None): Checks if Goods avaiable in stock after Purchases Procedure done @return: True
- def goods_recieved(self, cr, uid, id... | Implement the Python class `stock_picking` described below.
Class description:
Implement the stock_picking class.
Method signatures and docstrings:
- def action_done(self, cr, uid, ids, context=None): Checks if Goods avaiable in stock after Purchases Procedure done @return: True
- def goods_recieved(self, cr, uid, id... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
<|body_0|>
def goods_recieved(self, cr, uid, ids, context=None):
"""Change State To Picking confirmed"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class stock_picking:
def action_done(self, cr, uid, ids, context=None):
"""Checks if Goods avaiable in stock after Purchases Procedure done @return: True"""
wf_service = netsvc.LocalService('workflow')
super(stock_picking, self).action_done(cr, uid, ids, context=context)
picking_obj ... | the_stack_v2_python_sparse | v_7/Dongola/ntc/purchase_ntc/wizard/stock_partial_picking.py | musabahmed/baba | train | 0 | |
8fb919f2a151a8a579f812aecd079f6dab826d28 | [
"super(Punisher, self).__init__()\nself.mem_length = 1\nself.grudged = False\nself.grudge_memory = 1",
"if self.grudge_memory >= self.mem_length:\n self.grudge_memory = 0\n self.grudged = False\nif self.grudged:\n self.grudge_memory += 1\n return 'D'\nelif 'D' in opponent.history[-1:]:\n self.mem_l... | <|body_start_0|>
super(Punisher, self).__init__()
self.mem_length = 1
self.grudged = False
self.grudge_memory = 1
<|end_body_0|>
<|body_start_1|>
if self.grudge_memory >= self.mem_length:
self.grudge_memory = 0
self.grudged = False
if self.grudged... | A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for playing 'D' too often. | Punisher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for playing 'D' too often."""
def __i... | stack_v2_sparse_classes_36k_train_003102 | 3,311 | permissive | [
{
"docstring": "Initialised the player",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Begins by playing C, then plays D for an amount of rounds proportional to the opponents historical '%' of playing 'D' if the opponent ever plays D",
"name": "strategy",
"sign... | 3 | stack_v2_sparse_classes_30k_train_008485 | Implement the Python class `Punisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for... | Implement the Python class `Punisher` described below.
Class description:
A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for... | 0ce3aa29eb239b9a9055cd7bebb627602851b65a | <|skeleton|>
class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for playing 'D' too often."""
def __i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Punisher:
"""A player starts by cooperating however will defect if at any point the opponent has defected, but forgets after meme_length matches, with 1<=mem_length<=20 proportional to the amount of time the opponent has played 'D', punishing that player for playing 'D' too often."""
def __init__(self):
... | the_stack_v2_python_sparse | axelrod/strategies/punisher.py | jamesbroadhead/Axelrod | train | 1 |
cc31aba5b664993468fc4c55dbafdfa022526468 | [
"if not root or not p or (not q):\n return None\nif root == p or root == q:\n return root\np1 = self.path(root, p)\np2 = self.path(root, q)\ni = 0\nm = min(len(p1), len(p2))\nwhile i + 1 < m and p1[i + 1] == p2[i + 1]:\n i += 1\nreturn p1[i]",
"if not root or not node:\n return False\nif root == node:... | <|body_start_0|>
if not root or not p or (not q):
return None
if root == p or root == q:
return root
p1 = self.path(root, p)
p2 = self.path(root, q)
i = 0
m = min(len(p1), len(p2))
while i + 1 < m and p1[i + 1] == p2[i + 1]:
i +... | 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 contains(self, root, node):
"""does tree root contains node?"""
<|body_1|>
def path(self, root, node):
... | stack_v2_sparse_classes_36k_train_003103 | 5,241 | no_license | [
{
"docstring": ":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode",
"name": "lowestCommonAncestor",
"signature": "def lowestCommonAncestor(self, root, p, q)"
},
{
"docstring": "does tree root contains node?",
"name": "contains",
"signature": "def contains(self, ro... | 3 | null | 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 contains(self, root, node): does tree root contains no... | 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 contains(self, root, node): does tree root contains no... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def contains(self, root, node):
"""does tree root contains node?"""
<|body_1|>
def path(self, root, node):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if not root or not p or (not q):
return None
if root == p or root == q:
return root
p1 = self.path(root, p)
p2 =... | the_stack_v2_python_sparse | tree/prob236.py | binchen15/leet-python | train | 1 | |
097673aa070bfc33a82922705b908788a97d3d69 | [
"with get_oss_fuzz_repo() as oss_fuzz_repo:\n repo_man = repo_manager.RepoManager(oss_fuzz_repo)\n commit_to_test = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'\n repo_man.checkout_commit(commit_to_test)\n self.assertEqual(commit_to_test, repo_man.get_current_commit())",
"with get_oss_fuzz_repo() as oss... | <|body_start_0|>
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
commit_to_test = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
repo_man.checkout_commit(commit_to_test)
self.assertEqual(commit_to_test, repo_man.get_curren... | Tests the checkout functionality of RepoManager. | RepoManagerCheckoutTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepoManagerCheckoutTest:
"""Tests the checkout functionality of RepoManager."""
def test_checkout_valid_commit(self):
"""Tests that the git checkout command works."""
<|body_0|>
def test_checkout_invalid_commit(self):
"""Tests that the git checkout invalid commit... | stack_v2_sparse_classes_36k_train_003104 | 8,172 | permissive | [
{
"docstring": "Tests that the git checkout command works.",
"name": "test_checkout_valid_commit",
"signature": "def test_checkout_valid_commit(self)"
},
{
"docstring": "Tests that the git checkout invalid commit fails.",
"name": "test_checkout_invalid_commit",
"signature": "def test_che... | 2 | null | Implement the Python class `RepoManagerCheckoutTest` described below.
Class description:
Tests the checkout functionality of RepoManager.
Method signatures and docstrings:
- def test_checkout_valid_commit(self): Tests that the git checkout command works.
- def test_checkout_invalid_commit(self): Tests that the git ch... | Implement the Python class `RepoManagerCheckoutTest` described below.
Class description:
Tests the checkout functionality of RepoManager.
Method signatures and docstrings:
- def test_checkout_valid_commit(self): Tests that the git checkout command works.
- def test_checkout_invalid_commit(self): Tests that the git ch... | f0275421f84b8f80ee767fb9230134ac97cb687b | <|skeleton|>
class RepoManagerCheckoutTest:
"""Tests the checkout functionality of RepoManager."""
def test_checkout_valid_commit(self):
"""Tests that the git checkout command works."""
<|body_0|>
def test_checkout_invalid_commit(self):
"""Tests that the git checkout invalid commit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepoManagerCheckoutTest:
"""Tests the checkout functionality of RepoManager."""
def test_checkout_valid_commit(self):
"""Tests that the git checkout command works."""
with get_oss_fuzz_repo() as oss_fuzz_repo:
repo_man = repo_manager.RepoManager(oss_fuzz_repo)
comm... | the_stack_v2_python_sparse | infra/repo_manager_test.py | google/oss-fuzz | train | 9,438 |
1f129b32690030aa5b21e971a5a0c7864e8f7cb5 | [
"loader = self.loader(self)\nobj = loader.get_object_from_aws(self.app.pargs.pk)\nassert hasattr(obj, 'ssh_target'), f'Objects of type {obj.__class__.__name__} do not support SSH actions'\ntarget = get_ssh_target(self.app, obj, choose=self.app.pargs.choose)\ntarget.ssh_interactive(verbose=self.app.pargs.verbose)",
... | <|body_start_0|>
loader = self.loader(self)
obj = loader.get_object_from_aws(self.app.pargs.pk)
assert hasattr(obj, 'ssh_target'), f'Objects of type {obj.__class__.__name__} do not support SSH actions'
target = get_ssh_target(self.app, obj, choose=self.app.pargs.choose)
target.ss... | ObjectSSHController | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectSSHController:
def ssh(self):
"""SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or Task is of launch type EC2. You cannot ssh to the container machine of a FARGATE Service or task."""
... | stack_v2_sparse_classes_36k_train_003105 | 13,998 | permissive | [
{
"docstring": "SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or Task is of launch type EC2. You cannot ssh to the container machine of a FARGATE Service or task.",
"name": "ssh",
"signature": "def ssh(self)"
},... | 2 | stack_v2_sparse_classes_30k_train_013264 | Implement the Python class `ObjectSSHController` described below.
Class description:
Implement the ObjectSSHController class.
Method signatures and docstrings:
- def ssh(self): SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or T... | Implement the Python class `ObjectSSHController` described below.
Class description:
Implement the ObjectSSHController class.
Method signatures and docstrings:
- def ssh(self): SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or T... | caa4698da812f5291a47366f307c1abebb4a989c | <|skeleton|>
class ObjectSSHController:
def ssh(self):
"""SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or Task is of launch type EC2. You cannot ssh to the container machine of a FARGATE Service or task."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectSSHController:
def ssh(self):
"""SSH to a container machine running one of the tasks for an existing Service or Task in AWS. NOTE: this is only available if your Service or Task is of launch type EC2. You cannot ssh to the container machine of a FARGATE Service or task."""
loader = self.... | the_stack_v2_python_sparse | deployfish/controllers/network.py | caltechads/deployfish | train | 98 | |
b01b045560974ed8e326e8ebeb4f91ffbaee1c7c | [
"super(Criterion, self).__init__()\nself.n_classes = opt.n_classes\nself.pos_weight = opt.loss_multisimilarity_pos_weight\nself.neg_weight = opt.loss_multisimilarity_neg_weight\nself.margin = opt.loss_multisimilarity_margin\nself.thresh = opt.loss_multisimilarity_thresh\nself.name = 'multisimilarity'",
"similarit... | <|body_start_0|>
super(Criterion, self).__init__()
self.n_classes = opt.n_classes
self.pos_weight = opt.loss_multisimilarity_pos_weight
self.neg_weight = opt.loss_multisimilarity_neg_weight
self.margin = opt.loss_multisimilarity_margin
self.thresh = opt.loss_multisimilari... | Criterion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
<|body_0|>
def forward(self, batch, labels):
"... | stack_v2_sparse_classes_36k_train_003106 | 2,496 | permissive | [
{
"docstring": "Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training.",
"name": "__init__",
"signature": "def __init__(self, opt)"
},
{
"docstring": "Args: batch: torch.Te... | 2 | stack_v2_sparse_classes_30k_train_019026 | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of differe... | Implement the Python class `Criterion` described below.
Class description:
Implement the Criterion class.
Method signatures and docstrings:
- def __init__(self, opt): Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of differe... | 01a7220bac7ebb1e70416ef663f3ba7cee9e8bf5 | <|skeleton|>
class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
<|body_0|>
def forward(self, batch, labels):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Criterion:
def __init__(self, opt):
"""Args: margin: Triplet Margin. nu: Regularisation Parameter for beta values if they are learned. beta: Class-Margin values. n_classes: Number of different classes during training."""
super(Criterion, self).__init__()
self.n_classes = opt.n_classes
... | the_stack_v2_python_sparse | criteria/multisimilarity.py | chenyanlinzhugoushou/DCML | train | 0 | |
d3c65211b08fbfd445bb2306bbde230d4b74429a | [
"assert issubclass(rnn_type, nn.RNNBase), 'rnn_type must be a class inheriting from torch.nn.RNNBase'\nsuper(Seq2SeqEncoder, self).__init__()\nself.rnn_type = rnn_type\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.bias = bias\nself.dropout = dropout\nself.bidirect... | <|body_start_0|>
assert issubclass(rnn_type, nn.RNNBase), 'rnn_type must be a class inheriting from torch.nn.RNNBase'
super(Seq2SeqEncoder, self).__init__()
self.rnn_type = rnn_type
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
... | RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and that need to be passed through a RNN. The sequences are sorted in descending order... | Seq2SeqEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Seq2SeqEncoder:
"""RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and that need to be passed through a RNN. Th... | stack_v2_sparse_classes_36k_train_003107 | 30,263 | no_license | [
{
"docstring": "Args: rnn_type: The type of RNN to use as encoder in the module. Must be a class inheriting from torch.nn.RNNBase (such as torch.nn.LSTM for example). input_size: The number of expected features in the input of the module. hidden_size: The number of features in the hidden state of the RNN used a... | 2 | stack_v2_sparse_classes_30k_train_003673 | Implement the Python class `Seq2SeqEncoder` described below.
Class description:
RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and t... | Implement the Python class `Seq2SeqEncoder` described below.
Class description:
RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and t... | e52909f401279351d1589cb8b755d30b38ae0091 | <|skeleton|>
class Seq2SeqEncoder:
"""RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and that need to be passed through a RNN. Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Seq2SeqEncoder:
"""RNN taking variable length padded sequences of vectors as input and encoding them into padded sequences of vectors of the same length. This module is useful to handle batches of padded sequences of vectors that have different lengths and that need to be passed through a RNN. The sequences a... | the_stack_v2_python_sparse | code/model.py | FairyFali/macer-certified-word-sub-2.0 | train | 0 |
de9879acaddc7098bf25d042806c5e77e472e9e1 | [
"self.output = []\nself.curr = -1\nq = collections.deque()\nq.append(('', 0))\nn = len(characters)\nwhile q:\n temp, count = q.popleft()\n if len(temp) == combinationLength:\n self.output.append(temp)\n continue\n for i in range(count, n):\n q.append((temp + characters[i], i + 1))",
... | <|body_start_0|>
self.output = []
self.curr = -1
q = collections.deque()
q.append(('', 0))
n = len(characters)
while q:
temp, count = q.popleft()
if len(temp) == combinationLength:
self.output.append(temp)
continue
... | CombinationIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_003108 | 1,143 | no_license | [
{
"docstring": ":type characters: str :type combinationLength: int",
"name": "__init__",
"signature": "def __init__(self, characters, combinationLength)"
},
{
"docstring": ":rtype: str",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "... | 3 | null | Implement the Python class `CombinationIterator` described below.
Class description:
Implement the CombinationIterator class.
Method signatures and docstrings:
- def __init__(self, characters, combinationLength): :type characters: str :type combinationLength: int
- def next(self): :rtype: str
- def hasNext(self): :rt... | Implement the Python class `CombinationIterator` described below.
Class description:
Implement the CombinationIterator class.
Method signatures and docstrings:
- def __init__(self, characters, combinationLength): :type characters: str :type combinationLength: int
- def next(self): :rtype: str
- def hasNext(self): :rt... | 0be5b51e409ae479284452ab24f55b7811583653 | <|skeleton|>
class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
<|body_0|>
def next(self):
""":rtype: str"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CombinationIterator:
def __init__(self, characters, combinationLength):
""":type characters: str :type combinationLength: int"""
self.output = []
self.curr = -1
q = collections.deque()
q.append(('', 0))
n = len(characters)
while q:
temp, coun... | the_stack_v2_python_sparse | IteratorForCombinations.py | juhideshpande/LeetCode | train | 0 | |
5aef20d5f59cc6618328ccf4456ddbc28457dea0 | [
"try:\n f = open('.\\\\etc\\\\Name_Highscore.txt', 'r')\n self.NAME_HIGHSCORE_TABLE = {}\n text = f.readline()\n while text != '':\n temp = text.split(' ')\n self.NAME_HIGHSCORE_TABLE[temp[0]] = int(temp[1])\n text = f.readline()\n f.close()\n self.scores = tuple(self.NAME_HIG... | <|body_start_0|>
try:
f = open('.\\etc\\Name_Highscore.txt', 'r')
self.NAME_HIGHSCORE_TABLE = {}
text = f.readline()
while text != '':
temp = text.split(' ')
self.NAME_HIGHSCORE_TABLE[temp[0]] = int(temp[1])
text = f... | This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore | Player | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
... | stack_v2_sparse_classes_36k_train_003109 | 8,822 | no_license | [
{
"docstring": ":param grid_size: Is the size of one square side in Pixel",
"name": "__init__",
"signature": "def __init__(self, grid_size)"
},
{
"docstring": "Gets the name the Player Enters, but has following restrictionsto the name: - has to be 1-10 chars - no ' ' are allowed :param DISP: The... | 5 | stack_v2_sparse_classes_30k_train_020714 | Implement the Python class `Player` described below.
Class description:
This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore
Met... | Implement the Python class `Player` described below.
Class description:
This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore
Met... | 0aea111fe5335047f123a3afac0cbe42669df4ae | <|skeleton|>
class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Player:
"""This class outputs Graphical content on the Display such as: - Highscore table in the start screen - Own Points while playing - Next Highscore that you can reach It also reads the Highscore table file and writes in it when beating a highscore"""
def __init__(self, grid_size):
""":param... | the_stack_v2_python_sparse | Player.py | free43/Pac-Man-in-Python-with-pygame | train | 0 |
e10e134a238f5df1a738377c4169438565d34513 | [
"OpenPMDDiagnostic.__init__(self, period, comm, write_dir, iteration_min, iteration_max, dt_period=dt_period, dt_sim=dt_sim)\nself._input_script = self._get_input_script()\nself.param_dict = param_dict",
"args = sys.argv\npy_files = [f for f in args if '.py' in f]\nif not py_files:\n return\nwith open(py_files... | <|body_start_0|>
OpenPMDDiagnostic.__init__(self, period, comm, write_dir, iteration_min, iteration_max, dt_period=dt_period, dt_sim=dt_sim)
self._input_script = self._get_input_script()
self.param_dict = param_dict
<|end_body_0|>
<|body_start_1|>
args = sys.argv
py_files = [f f... | Class that allows saving input decks to dumps. | InputScriptDiagnostic | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputScriptDiagnostic:
"""Class that allows saving input decks to dumps."""
def __init__(self, period=None, comm=None, param_dict=None, write_dir=None, iteration_min=0, iteration_max=np.inf, dt_period=None, dt_sim=None):
"""Setup of the input script diagnostic Parameters ---------- p... | stack_v2_sparse_classes_36k_train_003110 | 4,330 | permissive | [
{
"docstring": "Setup of the input script diagnostic Parameters ---------- period : int, optional The period of the diagnostics, in number of timesteps. (i.e. the diagnostics are written whenever the number of iterations is divisible by `period`). Specify either this or `dt_period`. comm : an fbpic BoundaryComm... | 3 | null | Implement the Python class `InputScriptDiagnostic` described below.
Class description:
Class that allows saving input decks to dumps.
Method signatures and docstrings:
- def __init__(self, period=None, comm=None, param_dict=None, write_dir=None, iteration_min=0, iteration_max=np.inf, dt_period=None, dt_sim=None): Set... | Implement the Python class `InputScriptDiagnostic` described below.
Class description:
Class that allows saving input decks to dumps.
Method signatures and docstrings:
- def __init__(self, period=None, comm=None, param_dict=None, write_dir=None, iteration_min=0, iteration_max=np.inf, dt_period=None, dt_sim=None): Set... | 5744598571eab40c4fb45cc3db21f346b69b1f37 | <|skeleton|>
class InputScriptDiagnostic:
"""Class that allows saving input decks to dumps."""
def __init__(self, period=None, comm=None, param_dict=None, write_dir=None, iteration_min=0, iteration_max=np.inf, dt_period=None, dt_sim=None):
"""Setup of the input script diagnostic Parameters ---------- p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InputScriptDiagnostic:
"""Class that allows saving input decks to dumps."""
def __init__(self, period=None, comm=None, param_dict=None, write_dir=None, iteration_min=0, iteration_max=np.inf, dt_period=None, dt_sim=None):
"""Setup of the input script diagnostic Parameters ---------- period : int, ... | the_stack_v2_python_sparse | fbpic/openpmd_diag/inputscript_diag.py | fbpic/fbpic | train | 163 |
408cf8dca71d1b0663b75feef34cc0e280081b32 | [
"self.bandit_returns = bandit_returns\nself.n_bandits = len(bandit_returns)\nself.bandits = list(range(self.n_bandits))\nself.epsilon = epsilon\nself.batch_size = batch_size\nself.batches = batches\nself.simulations = simulations\nself.df_bids = pd.DataFrame(columns=self.bandit_returns)\nself.df_clicks = pd.DataFra... | <|body_start_0|>
self.bandit_returns = bandit_returns
self.n_bandits = len(bandit_returns)
self.bandits = list(range(self.n_bandits))
self.epsilon = epsilon
self.batch_size = batch_size
self.batches = batches
self.simulations = simulations
self.df_bids = p... | Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches. simulations: Number of simulations. Methods: init_bandits: Prepares everything for n... | EpsilonGreedyRunner | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EpsilonGreedyRunner:
"""Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches. simulations: Number of simulations. M... | stack_v2_sparse_classes_36k_train_003111 | 6,083 | permissive | [
{
"docstring": "Initializes a new instance of RunEpsilonGreedy with the passed parameters. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches. simulations: Number of simulations.",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_000825 | Implement the Python class `EpsilonGreedyRunner` described below.
Class description:
Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches... | Implement the Python class `EpsilonGreedyRunner` described below.
Class description:
Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches... | 3bf673bb7980a2ba972241b0ba4bae7ca3af1870 | <|skeleton|>
class EpsilonGreedyRunner:
"""Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches. simulations: Number of simulations. M... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EpsilonGreedyRunner:
"""Class that is used to run simulations of Thompson sampling tests. Attributes: bandit_returns: List of average returns per bandit. epsilon: Percentage of exploration. batch_size: Number of examples per batch. batches: Number of batches. simulations: Number of simulations. Methods: init_... | the_stack_v2_python_sparse | recohut/models/epsilon.py | recohut/recohut | train | 2 |
90077ee9449eaea10968f05d5f2bd77980e51799 | [
"string_io = StringIO()\nfor string in strs:\n string_io.write(string.replace(',', ',,'))\n string_io.write(u', ')\nreturn string_io.getvalue()",
"rv = []\nlast_start = 0\ni = 0\nlast_is_comma = False\nwhile i < len(s):\n if last_is_comma:\n last_is_comma = False\n if s[i] == ' ':\n ... | <|body_start_0|>
string_io = StringIO()
for string in strs:
string_io.write(string.replace(',', ',,'))
string_io.write(u', ')
return string_io.getvalue()
<|end_body_0|>
<|body_start_1|>
rv = []
last_start = 0
i = 0
last_is_comma = False
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_003112 | 1,516 | no_license | [
{
"docstring": "Encodes a list of strings to a single string. :type strs: List[str] :rtype: str",
"name": "encode",
"signature": "def encode(self, strs)"
},
{
"docstring": "Decodes a single string to a list of strings. :type s: str :rtype: List[str]",
"name": "decode",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_015563 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs): Encodes a list of strings to a single string. :type strs: List[str] :rtype: str
- def decode(self, s): Decodes a single string to a list of strings. :type s: st... | 488d93280d45ea686d30b0928e96aa5ed5498e6b | <|skeleton|>
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
<|body_0|>
def decode(self, s):
"""Decodes a single string to a list of strings. :type s: str :rtype: List[str]"""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string. :type strs: List[str] :rtype: str"""
string_io = StringIO()
for string in strs:
string_io.write(string.replace(',', ',,'))
string_io.write(u', ')
return string_io.getvalue()
... | the_stack_v2_python_sparse | leetcode/lc271.py | JasonXJ/algorithms | train | 1 | |
e7cfa87a9d556bbafe2b7b82cb82f2c2de694aa9 | [
"return_fields = ['timestamp']\nevents = self.event_stream(query_string=self.query, return_fields=return_fields)\nsession_num = 0\ntry:\n first_event = next(events)\n last_timestamp = first_event.source.get('timestamp')\n session_num = 1\n self.annotateEvent(first_event, session_num)\n for event in e... | <|body_start_0|>
return_fields = ['timestamp']
events = self.event_stream(query_string=self.query, return_fields=return_fields)
session_num = 0
try:
first_event = next(events)
last_timestamp = first_event.source.get('timestamp')
session_num = 1
... | Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal then max_time_diff_micros. Attributes: NAME (str): The name of the sessionizer. max_time_di... | SessionizerSketchPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionizerSketchPlugin:
"""Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal then max_time_diff_micros. Attributes: N... | stack_v2_sparse_classes_36k_train_003113 | 3,075 | permissive | [
{
"docstring": "Entry point for the analyzer. Allocates each event a session_id attribute. Returns: String containing the number of sessions created.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Annotate an event with a session ID. Store IDs as dictionary entries correspondin... | 2 | stack_v2_sparse_classes_30k_train_007651 | Implement the Python class `SessionizerSketchPlugin` described below.
Class description:
Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal t... | Implement the Python class `SessionizerSketchPlugin` described below.
Class description:
Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal t... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class SessionizerSketchPlugin:
"""Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal then max_time_diff_micros. Attributes: N... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionizerSketchPlugin:
"""Sessionizing analyzer. All events in sketch with id sketch_id are grouped in sessions based on the time difference between them. Two consecutive events are in the same session if the time difference between them is less or equal then max_time_diff_micros. Attributes: NAME (str): Th... | the_stack_v2_python_sparse | timesketch/lib/analyzers/sessionizer.py | google/timesketch | train | 2,263 |
ad1489dd8bc9b5ac5511ad9eee3241352f0a4824 | [
"self.tokenizer = transformers.AutoTokenizer.from_pretrained(context.artifacts['repository'], padding_side='left')\nself.model = transformers.AutoModelForCausalLM.from_pretrained(context.artifacts['repository'], torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, trust_remote_code=True, device_map='auto', pad_token... | <|body_start_0|>
self.tokenizer = transformers.AutoTokenizer.from_pretrained(context.artifacts['repository'], padding_side='left')
self.model = transformers.AutoModelForCausalLM.from_pretrained(context.artifacts['repository'], torch_dtype=torch.bfloat16, low_cpu_mem_usage=True, trust_remote_code=True, d... | LLaMA2 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LLaMA2:
def load_context(self, context):
"""This method initializes the tokenizer and language model using the specified model repository."""
<|body_0|>
def _build_prompt(self, instruction):
"""This method generates the prompt for the model."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_003114 | 7,872 | permissive | [
{
"docstring": "This method initializes the tokenizer and language model using the specified model repository.",
"name": "load_context",
"signature": "def load_context(self, context)"
},
{
"docstring": "This method generates the prompt for the model.",
"name": "_build_prompt",
"signature... | 4 | stack_v2_sparse_classes_30k_train_017194 | Implement the Python class `LLaMA2` described below.
Class description:
Implement the LLaMA2 class.
Method signatures and docstrings:
- def load_context(self, context): This method initializes the tokenizer and language model using the specified model repository.
- def _build_prompt(self, instruction): This method ge... | Implement the Python class `LLaMA2` described below.
Class description:
Implement the LLaMA2 class.
Method signatures and docstrings:
- def load_context(self, context): This method initializes the tokenizer and language model using the specified model repository.
- def _build_prompt(self, instruction): This method ge... | d96022268820dc7ab5c83e1becb4b8c7d60393ce | <|skeleton|>
class LLaMA2:
def load_context(self, context):
"""This method initializes the tokenizer and language model using the specified model repository."""
<|body_0|>
def _build_prompt(self, instruction):
"""This method generates the prompt for the model."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LLaMA2:
def load_context(self, context):
"""This method initializes the tokenizer and language model using the specified model repository."""
self.tokenizer = transformers.AutoTokenizer.from_pretrained(context.artifacts['repository'], padding_side='left')
self.model = transformers.Auto... | the_stack_v2_python_sparse | llm-models/llamav2/llamav2-13b/02_mlflow_logging_inference.py | databricks/databricks-ml-examples | train | 144 | |
de1ae10bd489eea98332426e38b9124e4a0ddf34 | [
"Window.size = (600, 400)\nself.title = 'Convert Miles to Kilometers'\nself.root = Builder.load_file('miles_to_km.kv')\nreturn self.root",
"value = self.get_valid_distance()\nresult = value * KM_PER_MILE\nself.root.ids.output_label.text = str(result)",
"value = self.get_valid_distance() + increment\nself.root.i... | <|body_start_0|>
Window.size = (600, 400)
self.title = 'Convert Miles to Kilometers'
self.root = Builder.load_file('miles_to_km.kv')
return self.root
<|end_body_0|>
<|body_start_1|>
value = self.get_valid_distance()
result = value * KM_PER_MILE
self.root.ids.outp... | SquareNumberApp is a Kivy App for squaring a number | MileToKmApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MileToKmApp:
"""SquareNumberApp is a Kivy App for squaring a number"""
def build(self):
"""build the Kivy app from the kv file"""
<|body_0|>
def handle_calculate(self):
"""handle calculation (could be button press or other call), output result to label widget"""
... | stack_v2_sparse_classes_36k_train_003115 | 1,654 | no_license | [
{
"docstring": "build the Kivy app from the kv file",
"name": "build",
"signature": "def build(self)"
},
{
"docstring": "handle calculation (could be button press or other call), output result to label widget",
"name": "handle_calculate",
"signature": "def handle_calculate(self)"
},
... | 4 | stack_v2_sparse_classes_30k_train_006483 | Implement the Python class `MileToKmApp` described below.
Class description:
SquareNumberApp is a Kivy App for squaring a number
Method signatures and docstrings:
- def build(self): build the Kivy app from the kv file
- def handle_calculate(self): handle calculation (could be button press or other call), output resul... | Implement the Python class `MileToKmApp` described below.
Class description:
SquareNumberApp is a Kivy App for squaring a number
Method signatures and docstrings:
- def build(self): build the Kivy app from the kv file
- def handle_calculate(self): handle calculation (could be button press or other call), output resul... | 16ba9cc74ea882aa3e7239dd9e73e1f33331211e | <|skeleton|>
class MileToKmApp:
"""SquareNumberApp is a Kivy App for squaring a number"""
def build(self):
"""build the Kivy app from the kv file"""
<|body_0|>
def handle_calculate(self):
"""handle calculation (could be button press or other call), output result to label widget"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MileToKmApp:
"""SquareNumberApp is a Kivy App for squaring a number"""
def build(self):
"""build the Kivy app from the kv file"""
Window.size = (600, 400)
self.title = 'Convert Miles to Kilometers'
self.root = Builder.load_file('miles_to_km.kv')
return self.root
... | the_stack_v2_python_sparse | Prac_07/miles_to_km.py | Mampson/Cp1404 | train | 0 |
26c33ec77c16085c7f7e677efaea8f76732eff79 | [
"branches = Branch.objects.filter(repository_id=kwargs['repository_id'])\nserializer = BranchSerializer(branches, context={'request': Request(request)}, many=True)\nreturn Response(serializer.data)",
"super(BranchList, self).check_object_permissions(request, Branch(repository_id=kwargs['repository_id']))\nseriali... | <|body_start_0|>
branches = Branch.objects.filter(repository_id=kwargs['repository_id'])
serializer = BranchSerializer(branches, context={'request': Request(request)}, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
super(BranchList, self).check_object_permis... | Basic view for handle all http requests to branch-list endpoint | BranchList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchList:
"""Basic view for handle all http requests to branch-list endpoint"""
def get(self, request: Request, *args, **kwargs) -> Response:
"""This method needs for handle GET request on branch-list endpoint and return all branches for specific repository :param request: http req... | stack_v2_sparse_classes_36k_train_003116 | 4,560 | permissive | [
{
"docstring": "This method needs for handle GET request on branch-list endpoint and return all branches for specific repository :param request: http request :param args: other parameters :param kwargs: dict parsed url variables {repository_id:id} :return: json with all branches for repository",
"name": "ge... | 2 | stack_v2_sparse_classes_30k_train_004344 | Implement the Python class `BranchList` described below.
Class description:
Basic view for handle all http requests to branch-list endpoint
Method signatures and docstrings:
- def get(self, request: Request, *args, **kwargs) -> Response: This method needs for handle GET request on branch-list endpoint and return all ... | Implement the Python class `BranchList` described below.
Class description:
Basic view for handle all http requests to branch-list endpoint
Method signatures and docstrings:
- def get(self, request: Request, *args, **kwargs) -> Response: This method needs for handle GET request on branch-list endpoint and return all ... | fdb911dfafbd2609b7f96561ab6780b4131a77bd | <|skeleton|>
class BranchList:
"""Basic view for handle all http requests to branch-list endpoint"""
def get(self, request: Request, *args, **kwargs) -> Response:
"""This method needs for handle GET request on branch-list endpoint and return all branches for specific repository :param request: http req... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BranchList:
"""Basic view for handle all http requests to branch-list endpoint"""
def get(self, request: Request, *args, **kwargs) -> Response:
"""This method needs for handle GET request on branch-list endpoint and return all branches for specific repository :param request: http request :param a... | the_stack_v2_python_sparse | branches/views.py | Kh-011-WebUIPython/lit | train | 4 |
0c3c1d313039885d916b11af7b2de1063b38f102 | [
"if not root:\n return ''\n\ndef recursion(node, string):\n if not node:\n return string + 'None,'\n else:\n string += str(node.val) + ','\n string = recursion(node.left, string)\n string = recursion(node.right, string)\n return string\nreturn recursion(root, '')",
"if data... | <|body_start_0|>
if not root:
return ''
def recursion(node, string):
if not node:
return string + 'None,'
else:
string += str(node.val) + ','
string = recursion(node.left, string)
string = recursion(node... | 递归实现 | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
"""递归实现"""
def serialize(root):
"""前序遍历.将树转换成序列字符输出 :param root: :return:"""
<|body_0|>
def deserialize(data):
"""将字符序列转换成树 :param data: (str) :return: (TreeNode)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
r... | stack_v2_sparse_classes_36k_train_003117 | 5,822 | no_license | [
{
"docstring": "前序遍历.将树转换成序列字符输出 :param root: :return:",
"name": "serialize",
"signature": "def serialize(root)"
},
{
"docstring": "将字符序列转换成树 :param data: (str) :return: (TreeNode)",
"name": "deserialize",
"signature": "def deserialize(data)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011558 | Implement the Python class `Codec1` described below.
Class description:
递归实现
Method signatures and docstrings:
- def serialize(root): 前序遍历.将树转换成序列字符输出 :param root: :return:
- def deserialize(data): 将字符序列转换成树 :param data: (str) :return: (TreeNode) | Implement the Python class `Codec1` described below.
Class description:
递归实现
Method signatures and docstrings:
- def serialize(root): 前序遍历.将树转换成序列字符输出 :param root: :return:
- def deserialize(data): 将字符序列转换成树 :param data: (str) :return: (TreeNode)
<|skeleton|>
class Codec1:
"""递归实现"""
def serialize(root):
... | 497c9717d783bb9f2d2675a3b254ec406582d849 | <|skeleton|>
class Codec1:
"""递归实现"""
def serialize(root):
"""前序遍历.将树转换成序列字符输出 :param root: :return:"""
<|body_0|>
def deserialize(data):
"""将字符序列转换成树 :param data: (str) :return: (TreeNode)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec1:
"""递归实现"""
def serialize(root):
"""前序遍历.将树转换成序列字符输出 :param root: :return:"""
if not root:
return ''
def recursion(node, string):
if not node:
return string + 'None,'
else:
string += str(node.val) + ','
... | the_stack_v2_python_sparse | 297.二叉树的序列化与反序列化/Codec.py | boyshen/leetcode_Algorithm_problem | train | 0 |
7bb72138c6ebe24e8fa0bcb7e4bbcf1c7fca1a4e | [
"awilt = self.env['account.wh.iva.line.tax']\npartner = self.env['res.partner']\nfor rec in self:\n if rec.invoice_id:\n rate = rec.retention_id.type == 'out_invoice' and partner._find_accounting_partner(rec.invoice_id.company_id.partner_id).wh_iva_rate or partner._find_accounting_partner(rec.invoice_id.p... | <|body_start_0|>
awilt = self.env['account.wh.iva.line.tax']
partner = self.env['res.partner']
for rec in self:
if rec.invoice_id:
rate = rec.retention_id.type == 'out_invoice' and partner._find_accounting_partner(rec.invoice_id.company_id.partner_id).wh_iva_rate or p... | AccountWhIvaLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
<|body_0|>
def _amount_all(self):
"""Return amount total each line"""
<|body_1|>
def invoice_id_change(self, invoice_id):
"""Return invoice da... | stack_v2_sparse_classes_36k_train_003118 | 40,203 | no_license | [
{
"docstring": "Clean and load again tax lines of the withholding voucher",
"name": "load_taxes",
"signature": "def load_taxes(self)"
},
{
"docstring": "Return amount total each line",
"name": "_amount_all",
"signature": "def _amount_all(self)"
},
{
"docstring": "Return invoice d... | 3 | null | Implement the Python class `AccountWhIvaLine` described below.
Class description:
Implement the AccountWhIvaLine class.
Method signatures and docstrings:
- def load_taxes(self): Clean and load again tax lines of the withholding voucher
- def _amount_all(self): Return amount total each line
- def invoice_id_change(sel... | Implement the Python class `AccountWhIvaLine` described below.
Class description:
Implement the AccountWhIvaLine class.
Method signatures and docstrings:
- def load_taxes(self): Clean and load again tax lines of the withholding voucher
- def _amount_all(self): Return amount total each line
- def invoice_id_change(sel... | 718327d01e5b4408add58682c5ad1901fa35b450 | <|skeleton|>
class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
<|body_0|>
def _amount_all(self):
"""Return amount total each line"""
<|body_1|>
def invoice_id_change(self, invoice_id):
"""Return invoice da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AccountWhIvaLine:
def load_taxes(self):
"""Clean and load again tax lines of the withholding voucher"""
awilt = self.env['account.wh.iva.line.tax']
partner = self.env['res.partner']
for rec in self:
if rec.invoice_id:
rate = rec.retention_id.type == ... | the_stack_v2_python_sparse | l10n_ve_withholding_iva/model/wh_iva.py | Vauxoo/odoo-venezuela | train | 15 | |
7b96d74e4a927b8f9d62078d8796131a3efa8fad | [
"test_map = dict(working_map)\nabs_rooms = []\nfor i in range(100):\n generator_pos = GeneratorUtil.random_pos(map_size, False)\n room = RoomGenerator.__generate_room(map_size)\n abs_room = GeneratorUtil.offset(generator_pos, room)\n room_clear = GeneratorUtil.check_clearance(test_map, abs_room)\n if... | <|body_start_0|>
test_map = dict(working_map)
abs_rooms = []
for i in range(100):
generator_pos = GeneratorUtil.random_pos(map_size, False)
room = RoomGenerator.__generate_room(map_size)
abs_room = GeneratorUtil.offset(generator_pos, room)
room_cle... | RoomGenerator | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
<|body_0|>
def __generate_room(map_size):
"""Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_003119 | 1,518 | permissive | [
{
"docstring": "Generate a list of absoulte-positioned rooms",
"name": "generate_rooms",
"signature": "def generate_rooms(working_map, map_size)"
},
{
"docstring": "Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor.",
"name": "__generate_room",
"signa... | 2 | stack_v2_sparse_classes_30k_test_000692 | Implement the Python class `RoomGenerator` described below.
Class description:
Implement the RoomGenerator class.
Method signatures and docstrings:
- def generate_rooms(working_map, map_size): Generate a list of absoulte-positioned rooms
- def __generate_room(map_size): Generate a room, and return it. A room is defin... | Implement the Python class `RoomGenerator` described below.
Class description:
Implement the RoomGenerator class.
Method signatures and docstrings:
- def generate_rooms(working_map, map_size): Generate a list of absoulte-positioned rooms
- def __generate_room(map_size): Generate a room, and return it. A room is defin... | bce8c262bc80912045a9e5394447b937f9b08f83 | <|skeleton|>
class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
<|body_0|>
def __generate_room(map_size):
"""Generate a room, and return it. A room is defined as a 2D list with MapTileTypes.Floor."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoomGenerator:
def generate_rooms(working_map, map_size):
"""Generate a list of absoulte-positioned rooms"""
test_map = dict(working_map)
abs_rooms = []
for i in range(100):
generator_pos = GeneratorUtil.random_pos(map_size, False)
room = RoomGenerator._... | the_stack_v2_python_sparse | ageofwinds/map/mapGenerator/roomGenerator.py | pbrn46/ageofwinds | train | 0 | |
0400f2bdcce387ddb9c3baab807eca0cdcf061ea | [
"l = [i * i for i in range(1, n + 1) if i * i <= n]\ndp = [0] * (n + 1)\nfor i in range(1, n + 1):\n m = float('INF')\n for j in l:\n if j <= i:\n m = min(dp[i - j] + 1, m)\n dp[i] = m\nreturn dp[-1]",
"l = [i * i for i in range(1, n + 1) if i * i <= n]\nqueue = set([n])\nlevel = 0\nwhi... | <|body_start_0|>
l = [i * i for i in range(1, n + 1) if i * i <= n]
dp = [0] * (n + 1)
for i in range(1, n + 1):
m = float('INF')
for j in l:
if j <= i:
m = min(dp[i - j] + 1, m)
dp[i] = m
return dp[-1]
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSquares_dp(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_bfs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = [i * i for i in range(1, n + 1) if i * i <= n]
dp = ... | stack_v2_sparse_classes_36k_train_003120 | 1,297 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares_dp",
"signature": "def numSquares_dp(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "numSquares_bfs",
"signature": "def numSquares_bfs(self, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_dp(self, n): :type n: int :rtype: int
- def numSquares_bfs(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSquares_dp(self, n): :type n: int :rtype: int
- def numSquares_bfs(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def numSquares_dp(self, n):
... | 0e99f9a5226507706b3ee66fd04bae813755ef40 | <|skeleton|>
class Solution:
def numSquares_dp(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def numSquares_bfs(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSquares_dp(self, n):
""":type n: int :rtype: int"""
l = [i * i for i in range(1, n + 1) if i * i <= n]
dp = [0] * (n + 1)
for i in range(1, n + 1):
m = float('INF')
for j in l:
if j <= i:
m = min(dp[i ... | the_stack_v2_python_sparse | medium/dp/test_279_Perfect_Squares.py | wuxu1019/leetcode_sophia | train | 1 | |
8f540844ba35df23b5dd0188d3d9d7fd9f0228b4 | [
"self.timeout = timeout\ntry:\n self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)\nexcept Exception as e:\n self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])\nfor stp in steps.details:\n if stp.result.name == 'skipped':\n ... | <|body_start_0|>
self.timeout = timeout
try:
self.pre_snap = self.mapping.learn_ops(device=uut, abstract=abstract, steps=steps, timeout=self.timeout)
except Exception as e:
self.skipped('Cannot learn the feature', from_exception=e, goto=['next_tc'])
for stp in ste... | Trigger class for ISSU action | TriggerIssu | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): A... | stack_v2_sparse_classes_36k_train_003121 | 20,969 | permissive | [
{
"docstring": "Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract object. steps (`step obj`): aetest step object timeout (`timeout obj`): Timeout Object Returns: None Raises: pyATS Res... | 5 | null | Implement the Python class `TriggerIssu` described below.
Class description:
Trigger class for ISSU action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testca... | Implement the Python class `TriggerIssu` described below.
Class description:
Trigger class for ISSU action
Method signatures and docstrings:
- def verify_prerequisite(self, uut, abstract, steps, timeout): Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testca... | e42e51475cddcb10f5c7814d0fe892ac865742ba | <|skeleton|>
class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): A... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriggerIssu:
"""Trigger class for ISSU action"""
def verify_prerequisite(self, uut, abstract, steps, timeout):
"""Learn Ops object and verify the requirements. If the requirements are not satisfied, then skip to the next testcase. Args: uut (`obj`): Device object. abstract (`obj`): Abstract objec... | the_stack_v2_python_sparse | pkgs/sdk-pkg/src/genie/libs/sdk/triggers/ha/ha.py | CiscoTestAutomation/genielibs | train | 109 |
2c1ce9b33fc0b7ac96c0e683692982322e64f2ae | [
"q = quantity.Area(1.0, 'm^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)\nself.assertEqual(q.units, 'm^2')",
"q = quantity.Area(1.0, 'cm^2')\nself.assertAlmostEqual(q.value, 1.0, 6)\nself.assertAlmostEqual(q.value_si, 0.0001, delta=1e-10)\nself.assertEqual(q.un... | <|body_start_0|>
q = quantity.Area(1.0, 'm^2')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
self.assertEqual(q.units, 'm^2')
<|end_body_0|>
<|body_start_1|>
q = quantity.Area(1.0, 'cm^2')
self.assertAlmostEqual(q.value, 1.0... | Contains unit tests of the Area unit type object. | TestArea | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestArea:
"""Contains unit tests of the Area unit type object."""
def test_m2(self):
"""Test the creation of an area quantity with units of m^2."""
<|body_0|>
def test_cm2(self):
"""Test the creation of an area quantity with units of m^2."""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_003122 | 33,010 | permissive | [
{
"docstring": "Test the creation of an area quantity with units of m^2.",
"name": "test_m2",
"signature": "def test_m2(self)"
},
{
"docstring": "Test the creation of an area quantity with units of m^2.",
"name": "test_cm2",
"signature": "def test_cm2(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018330 | Implement the Python class `TestArea` described below.
Class description:
Contains unit tests of the Area unit type object.
Method signatures and docstrings:
- def test_m2(self): Test the creation of an area quantity with units of m^2.
- def test_cm2(self): Test the creation of an area quantity with units of m^2. | Implement the Python class `TestArea` described below.
Class description:
Contains unit tests of the Area unit type object.
Method signatures and docstrings:
- def test_m2(self): Test the creation of an area quantity with units of m^2.
- def test_cm2(self): Test the creation of an area quantity with units of m^2.
<|... | 0937b2e0a955dcf21b79674a4e89f43941c0dd85 | <|skeleton|>
class TestArea:
"""Contains unit tests of the Area unit type object."""
def test_m2(self):
"""Test the creation of an area quantity with units of m^2."""
<|body_0|>
def test_cm2(self):
"""Test the creation of an area quantity with units of m^2."""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestArea:
"""Contains unit tests of the Area unit type object."""
def test_m2(self):
"""Test the creation of an area quantity with units of m^2."""
q = quantity.Area(1.0, 'm^2')
self.assertAlmostEqual(q.value, 1.0, 6)
self.assertAlmostEqual(q.value_si, 1.0, delta=1e-06)
... | the_stack_v2_python_sparse | rmgpy/quantityTest.py | vrlambert/RMG-Py | train | 1 |
6530a97d02c14b7e1355817d81594f39ed9d5d55 | [
"self.k = k\nself.h_train = None\nself.bsk_label_train = None\nself.clf = None",
"assert self.k is not None, 'k cannot be none before train'\nself.h_train = h_train.sign()\nif isinstance(bsk_label_train, pd.DataFrame):\n bsk_label_train = bsk_label_train.values\nself.bsk_label_train = bsk_label_train\nself.clf... | <|body_start_0|>
self.k = k
self.h_train = None
self.bsk_label_train = None
self.clf = None
<|end_body_0|>
<|body_start_1|>
assert self.k is not None, 'k cannot be none before train'
self.h_train = h_train.sign()
if isinstance(bsk_label_train, pd.DataFrame):
... | A knn prediction class | knn_Predictor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_36k_train_003123 | 4,002 | no_license | [
{
"docstring": "The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')",
"name": "__init__",
"signature": "def __init__(self, k=None)"
},
{
"docstring": "The train method of class :param h_train... | 4 | stack_v2_sparse_classes_30k_train_004095 | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | Implement the Python class `knn_Predictor` described below.
Class description:
A knn prediction class
Method signatures and docstrings:
- def __init__(self, k=None): The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normaliz... | 7f9ef25bb9c50f996534ff9067da0d95ac3fdbd5 | <|skeleton|>
class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
<|body_0|>
def fit(self, h_train, bs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class knn_Predictor:
"""A knn prediction class"""
def __init__(self, k=None):
"""The constructor of the baseline predictor :param method: only Jaccard method is supported :param type: one of the two options ('Unnormalized', 'Normalized')"""
self.k = k
self.h_train = None
self.bs... | the_stack_v2_python_sparse | src/knn_prediction_cls.py | bigdatamatta/HyperGo | train | 0 |
3e8814d8e7bdab7cce7065a342b9f6295ad8b299 | [
"self.contig = contig\nself.range = simulation_range\nself.simulation_number = simulation_number\nself.simulation_directories = None\nitems = glob.glob('run_*')\ndirs = [s for s in items if '.config' not in s]\nif len(dirs) == self.simulation_number:\n self.simulation_directories = sorted(dirs, key=lambda x: int... | <|body_start_0|>
self.contig = contig
self.range = simulation_range
self.simulation_number = simulation_number
self.simulation_directories = None
items = glob.glob('run_*')
dirs = [s for s in items if '.config' not in s]
if len(dirs) == self.simulation_number:
... | Organizer Class Function To Move Through The Simulation Structure | Organizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Organizer:
"""Organizer Class Function To Move Through The Simulation Structure"""
def __init__(self, contig, simulation_range, simulation_number):
"""Initialize Organizer Instance"""
<|body_0|>
def move_configs(self):
"""Move all of the config files created for ... | stack_v2_sparse_classes_36k_train_003124 | 1,865 | no_license | [
{
"docstring": "Initialize Organizer Instance",
"name": "__init__",
"signature": "def __init__(self, contig, simulation_range, simulation_number)"
},
{
"docstring": "Move all of the config files created for forqsprep, into the forqsprep directory the config file created",
"name": "move_confi... | 2 | null | Implement the Python class `Organizer` described below.
Class description:
Organizer Class Function To Move Through The Simulation Structure
Method signatures and docstrings:
- def __init__(self, contig, simulation_range, simulation_number): Initialize Organizer Instance
- def move_configs(self): Move all of the conf... | Implement the Python class `Organizer` described below.
Class description:
Organizer Class Function To Move Through The Simulation Structure
Method signatures and docstrings:
- def __init__(self, contig, simulation_range, simulation_number): Initialize Organizer Instance
- def move_configs(self): Move all of the conf... | 13ccb51ab30bbd8a45228986017b23038c04357d | <|skeleton|>
class Organizer:
"""Organizer Class Function To Move Through The Simulation Structure"""
def __init__(self, contig, simulation_range, simulation_number):
"""Initialize Organizer Instance"""
<|body_0|>
def move_configs(self):
"""Move all of the config files created for ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Organizer:
"""Organizer Class Function To Move Through The Simulation Structure"""
def __init__(self, contig, simulation_range, simulation_number):
"""Initialize Organizer Instance"""
self.contig = contig
self.range = simulation_range
self.simulation_number = simulation_nu... | the_stack_v2_python_sparse | presimulation/forqsprep/forq_organizer.py | transferome/Simulations | train | 0 |
0cddd321c8605d3577342705d76f15694818bd5f | [
"pubDate = datetime.date.today().strftime('%d %B %Y')\npubTime = time.strftime('%H:%M')\nreturn pubDate + ' ' + pubTime",
"for viewRow in response.css('li.views-row'):\n title = viewRow.css('a::attr(\"title\")').extract_first()\n link = viewRow.css('a::attr(\"href\")').extract_first()\n yield {'title': t... | <|body_start_0|>
pubDate = datetime.date.today().strftime('%d %B %Y')
pubTime = time.strftime('%H:%M')
return pubDate + ' ' + pubTime
<|end_body_0|>
<|body_start_1|>
for viewRow in response.css('li.views-row'):
title = viewRow.css('a::attr("title")').extract_first()
... | PersonalAssetsSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PersonalAssetsSpider:
def getPubDate(self):
"""Creates a RSS date/time"""
<|body_0|>
def parse(self, response):
"""Select page elements to pick for the generated xml element"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pubDate = datetime.date.tod... | stack_v2_sparse_classes_36k_train_003125 | 1,869 | no_license | [
{
"docstring": "Creates a RSS date/time",
"name": "getPubDate",
"signature": "def getPubDate(self)"
},
{
"docstring": "Select page elements to pick for the generated xml element",
"name": "parse",
"signature": "def parse(self, response)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008886 | Implement the Python class `PersonalAssetsSpider` described below.
Class description:
Implement the PersonalAssetsSpider class.
Method signatures and docstrings:
- def getPubDate(self): Creates a RSS date/time
- def parse(self, response): Select page elements to pick for the generated xml element | Implement the Python class `PersonalAssetsSpider` described below.
Class description:
Implement the PersonalAssetsSpider class.
Method signatures and docstrings:
- def getPubDate(self): Creates a RSS date/time
- def parse(self, response): Select page elements to pick for the generated xml element
<|skeleton|>
class ... | f218e78e65fbff867ade841a4f6325863415da2b | <|skeleton|>
class PersonalAssetsSpider:
def getPubDate(self):
"""Creates a RSS date/time"""
<|body_0|>
def parse(self, response):
"""Select page elements to pick for the generated xml element"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PersonalAssetsSpider:
def getPubDate(self):
"""Creates a RSS date/time"""
pubDate = datetime.date.today().strftime('%d %B %Y')
pubTime = time.strftime('%H:%M')
return pubDate + ' ' + pubTime
def parse(self, response):
"""Select page elements to pick for the generat... | the_stack_v2_python_sparse | SiteCrawler/SiteCrawler/spiders/patplc_co_uk_spider.py | 0x3F3F/RssTools | train | 1 | |
b694038827755ab440247ccaf8ff6e52658e1b97 | [
"self.nesting = False\nself.debug = False\nself.tracing = False\nself.storage_conf = ''\nself.stream_backend = ''\nself.stream_master_name = ''\nself.stream_master_port = ''\nself.tasks_x_node = 0\nself.exec_ids = []\nself.pipes = []\nself.control_pipe = Pipe()\nself.cache = False\nself.cache_profiler = ''\nself.ea... | <|body_start_0|>
self.nesting = False
self.debug = False
self.tracing = False
self.storage_conf = ''
self.stream_backend = ''
self.stream_master_name = ''
self.stream_master_port = ''
self.tasks_x_node = 0
self.exec_ids = []
self.pipes = []... | Configuration parameters for the Piper Worker class. | PiperWorkerConfiguration | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PiperWorkerConfiguration:
"""Configuration parameters for the Piper Worker class."""
def __init__(self) -> None:
"""Construct an empty configuration description for the piper worker. :returns: None."""
<|body_0|>
def update_params(self, argv: typing.List[str]) -> None:
... | stack_v2_sparse_classes_36k_train_003126 | 6,292 | permissive | [
{
"docstring": "Construct an empty configuration description for the piper worker. :returns: None.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Update the PiperWorkerConfiguration parameters from arguments. Construct a configuration description for the piper... | 3 | stack_v2_sparse_classes_30k_train_012269 | Implement the Python class `PiperWorkerConfiguration` described below.
Class description:
Configuration parameters for the Piper Worker class.
Method signatures and docstrings:
- def __init__(self) -> None: Construct an empty configuration description for the piper worker. :returns: None.
- def update_params(self, ar... | Implement the Python class `PiperWorkerConfiguration` described below.
Class description:
Configuration parameters for the Piper Worker class.
Method signatures and docstrings:
- def __init__(self) -> None: Construct an empty configuration description for the piper worker. :returns: None.
- def update_params(self, ar... | 5f7a31436d0e6f5acbeb66fa36ab8aad18dc4092 | <|skeleton|>
class PiperWorkerConfiguration:
"""Configuration parameters for the Piper Worker class."""
def __init__(self) -> None:
"""Construct an empty configuration description for the piper worker. :returns: None."""
<|body_0|>
def update_params(self, argv: typing.List[str]) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PiperWorkerConfiguration:
"""Configuration parameters for the Piper Worker class."""
def __init__(self) -> None:
"""Construct an empty configuration description for the piper worker. :returns: None."""
self.nesting = False
self.debug = False
self.tracing = False
se... | the_stack_v2_python_sparse | compss/programming_model/bindings/python/src/pycompss/worker/piper/commons/utils.py | bsc-wdc/compss | train | 39 |
a882fa8a40c0ccfb6f84b73582bf3cc90d9e8bee | [
"if node1 < self._numVerts and node2 < self._numVerts:\n self._adjMatrix[node1][node2] = weight\n self._adjMatrix[node2][node1] = weight\n return True\nelif node1 >= self._numVerts:\n raise NodeIndexOutOfRangeException(0, self._numVerts, node1)\nelse:\n raise NodeIndexOutOfRangeException(0, self._num... | <|body_start_0|>
if node1 < self._numVerts and node2 < self._numVerts:
self._adjMatrix[node1][node2] = weight
self._adjMatrix[node2][node1] = weight
return True
elif node1 >= self._numVerts:
raise NodeIndexOutOfRangeException(0, self._numVerts, node1)
... | A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False | WeightedMatrixGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WeightedMatrixGraph:
"""A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False"""
def addEdge(self, node1, node2, weight):
"""Takes two node indices and a weight value, and adds an edge between th... | stack_v2_sparse_classes_36k_train_003127 | 16,606 | no_license | [
{
"docstring": "Takes two node indices and a weight value, and adds an edge between them. This class represents undirected graphs",
"name": "addEdge",
"signature": "def addEdge(self, node1, node2, weight)"
},
{
"docstring": "Takes in a node index, and returns a list of the indices of the node's ... | 3 | null | Implement the Python class `WeightedMatrixGraph` described below.
Class description:
A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False
Method signatures and docstrings:
- def addEdge(self, node1, node2, weight): Takes two nod... | Implement the Python class `WeightedMatrixGraph` described below.
Class description:
A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False
Method signatures and docstrings:
- def addEdge(self, node1, node2, weight): Takes two nod... | 97bb378a325b1639110de06b88d6e237dffc7330 | <|skeleton|>
class WeightedMatrixGraph:
"""A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False"""
def addEdge(self, node1, node2, weight):
"""Takes two node indices and a weight value, and adds an edge between th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WeightedMatrixGraph:
"""A weighted graph, represented as an adjacency matrix... Allows for positive or negative weights, because absence of an edge is done with False"""
def addEdge(self, node1, node2, weight):
"""Takes two node indices and a weight value, and adds an edge between them. This clas... | the_stack_v2_python_sparse | backups/speedy_nav-2/scripts/Graphs.py | FoxRobotLab/catkin_ws | train | 6 |
7f25ff3c268519db7fe3fbbea3af68e2204fb1b7 | [
"super().__init__()\nself.multioutputWrapper = True\nimport sklearn\nimport sklearn.ensemble\nself.model = sklearn.ensemble.VotingRegressor",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{VotingRegressor} is an ensemble meta-estimator that fits several base\\n ... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = True
import sklearn
import sklearn.ensemble
self.model = sklearn.ensemble.VotingRegressor
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{Voti... | Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions. | VotingRegressor | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VotingRegressor:
"""Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions."""
def __init__(self):
"""C... | stack_v2_sparse_classes_36k_train_003128 | 5,013 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 4 | stack_v2_sparse_classes_30k_test_000293 | Implement the Python class `VotingRegressor` described below.
Class description:
Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions.
... | Implement the Python class `VotingRegressor` described below.
Class description:
Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions.
... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class VotingRegressor:
"""Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions."""
def __init__(self):
"""C... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VotingRegressor:
"""Prediction voting regressor for unfitted estimators. A voting regressor is an ensemble meta-estimator that fits several base regressors, each on the whole dataset. Then it averages the individual predictions to form a final predictions."""
def __init__(self):
"""Constructor th... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/Ensemble/VotingRegressor.py | idaholab/raven | train | 201 |
352916463f336f6edd384d4d928660e2e87be7dd | [
"self.data_folder = data_folder\nself.dataset_name = dataset_name\nself.cols_dict = cols_dict\nself.clean_names = clean_names\nself.final_csv_path = final_csv_path\nself.raw_df = None\nself.cols_to_extract = list(self.cols_dict.keys())[3:]",
"df_full = pd.DataFrame(columns=list(self.cols_dict.keys()))\nlgd_url = ... | <|body_start_0|>
self.data_folder = data_folder
self.dataset_name = dataset_name
self.cols_dict = cols_dict
self.clean_names = clean_names
self.final_csv_path = final_csv_path
self.raw_df = None
self.cols_to_extract = list(self.cols_dict.keys())[3:]
<|end_body_0|>... | An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain column names and values contains StatVar names) | NHMDataLoaderBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain col... | stack_v2_sparse_classes_36k_train_003129 | 7,077 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, data_folder, dataset_name, cols_dict, clean_names, final_csv_path)"
},
{
"docstring": "Class method to preprocess the data file for each available year, extract t he columns and map the columns to schema. The data... | 4 | stack_v2_sparse_classes_30k_train_008624 | Implement the Python class `NHMDataLoaderBase` described below.
Class description:
An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data fil... | Implement the Python class `NHMDataLoaderBase` described below.
Class description:
An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data fil... | 615cc10bbee274d888c1bc58a78ffc93d424861c | <|skeleton|>
class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain col... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NHMDataLoaderBase:
"""An object to clean .xls files under 'data/' folder and convert it to csv Attributes: data_folder: folder containing all the data files dataset_name: name given to the dataset cols_dict: dictionary containing column names in the data files mapped to StatVars (keys contain column names and... | the_stack_v2_python_sparse | scripts/india_nhm/base/data_cleaner.py | Ghaiyur-wipro/data | train | 0 |
cf9ec76dac9fbe5f467fb8b66415d108fe7eb25e | [
"mes = {'message': 'success'}\nrole_name = kwargs.get('role_name', '')\ndb = orm_module.get_client()\nconn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db)\nwrite_concern = WriteConcern(w=1, j=True)\nwith db.start_session(causal_consistency=True) as ses:\n with ses.start_transaction(write_con... | <|body_start_0|>
mes = {'message': 'success'}
role_name = kwargs.get('role_name', '')
db = orm_module.get_client()
conn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db)
write_concern = WriteConcern(w=1, j=True)
with db.start_session(causal_consistency=... | 角色/权限组 | Role | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Role:
"""角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
<|body_0|>
def all_rules(cls) -> list:
"""查询所有的rule,不包括root :return:"""
<|body_1|>
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10, can... | stack_v2_sparse_classes_36k_train_003130 | 27,644 | no_license | [
{
"docstring": "添加角色 :param kwargs: :return:",
"name": "add",
"signature": "def add(cls, **kwargs) -> dict"
},
{
"docstring": "查询所有的rule,不包括root :return:",
"name": "all_rules",
"signature": "def all_rules(cls) -> list"
},
{
"docstring": "分页查看角色信息 :param filter_dict: 过滤器,由用户的权限生成 ... | 3 | null | Implement the Python class `Role` described below.
Class description:
角色/权限组
Method signatures and docstrings:
- def add(cls, **kwargs) -> dict: 添加角色 :param kwargs: :return:
- def all_rules(cls) -> list: 查询所有的rule,不包括root :return:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10, can_jso... | Implement the Python class `Role` described below.
Class description:
角色/权限组
Method signatures and docstrings:
- def add(cls, **kwargs) -> dict: 添加角色 :param kwargs: :return:
- def all_rules(cls) -> list: 查询所有的rule,不包括root :return:
- def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10, can_jso... | 3a2bdfd1598bfcdfe56386ec0c46fcede772cbfe | <|skeleton|>
class Role:
"""角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
<|body_0|>
def all_rules(cls) -> list:
"""查询所有的rule,不包括root :return:"""
<|body_1|>
def paging_info(cls, filter_dict: dict, page_index: int=1, page_size: int=10, can... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Role:
"""角色/权限组"""
def add(cls, **kwargs) -> dict:
"""添加角色 :param kwargs: :return:"""
mes = {'message': 'success'}
role_name = kwargs.get('role_name', '')
db = orm_module.get_client()
conn = orm_module.get_conn(table_name=cls.get_table_name(), db_client=db)
... | the_stack_v2_python_sparse | query_server/module/system_module.py | SYYDSN/py_projects | train | 0 |
518865fc0081d6d4bfdf911ec34b5a2614b8cd1e | [
"if len(num1) == 0 or len(num2) == 0:\n return ''\nans = ''\nif len(num1) > len(num2):\n num1, num2 = (num2, num1)\nfor digit in num1:\n temp = self.single_mul(digit, num2)\n ans = self.add(ans + '0', temp)\nreturn ans",
"if digit == '0':\n return '0'\nif digit == '1':\n return num\ndigit = ord(... | <|body_start_0|>
if len(num1) == 0 or len(num2) == 0:
return ''
ans = ''
if len(num1) > len(num2):
num1, num2 = (num2, num1)
for digit in num1:
temp = self.single_mul(digit, num2)
ans = self.add(ans + '0', temp)
return ans
<|end_bod... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def single_mul(self, digit, num):
"""digit: a single digit string num: a str of number of any length"""
<|body_1|>
def add(self, num1, num2):
... | stack_v2_sparse_classes_36k_train_003131 | 3,242 | no_license | [
{
"docstring": ":type num1: str :type num2: str :rtype: str",
"name": "multiply",
"signature": "def multiply(self, num1, num2)"
},
{
"docstring": "digit: a single digit string num: a str of number of any length",
"name": "single_mul",
"signature": "def single_mul(self, digit, num)"
},
... | 3 | stack_v2_sparse_classes_30k_train_002544 | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def single_mul(self, digit, num): digit: a single digit string num: a str of number of any length
... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def multiply(self, num1, num2): :type num1: str :type num2: str :rtype: str
- def single_mul(self, digit, num): digit: a single digit string num: a str of number of any length
... | 188befbfb7080ba1053ee1f7187b177b64cf42d2 | <|skeleton|>
class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
<|body_0|>
def single_mul(self, digit, num):
"""digit: a single digit string num: a str of number of any length"""
<|body_1|>
def add(self, num1, num2):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def multiply(self, num1, num2):
""":type num1: str :type num2: str :rtype: str"""
if len(num1) == 0 or len(num2) == 0:
return ''
ans = ''
if len(num1) > len(num2):
num1, num2 = (num2, num1)
for digit in num1:
temp = self.si... | the_stack_v2_python_sparse | 0043. Multiply Strings.py | pwang867/LeetCode-Solutions-Python | train | 0 | |
b97c5d03774577aabae46632a1a9428a132df0c7 | [
"try:\n book = BookInfo.objects.get(pk=pk)\nexcept BookInfo.DoesNotExist:\n return HttpResponse(status=404)\ndata = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if book.image else ''}\nreturn JsonResponse(data)",
... | <|body_start_0|>
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bread, 'bcomment': book.bcomment, 'image': book.image.url if boo... | BookDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
<|body_0|>
def put(self, request, pk):
"""修改指定的图书信息"""
<|body_1|>
def delete(self, request, pk):
"""删除指定的图书信息"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:
... | stack_v2_sparse_classes_36k_train_003132 | 4,373 | no_license | [
{
"docstring": "获取指定的图书信息",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "修改指定的图书信息",
"name": "put",
"signature": "def put(self, request, pk)"
},
{
"docstring": "删除指定的图书信息",
"name": "delete",
"signature": "def delete(self, request, pk)"
}
] | 3 | stack_v2_sparse_classes_30k_train_017945 | Implement the Python class `BookDetailView` described below.
Class description:
Implement the BookDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): 获取指定的图书信息
- def put(self, request, pk): 修改指定的图书信息
- def delete(self, request, pk): 删除指定的图书信息 | Implement the Python class `BookDetailView` described below.
Class description:
Implement the BookDetailView class.
Method signatures and docstrings:
- def get(self, request, pk): 获取指定的图书信息
- def put(self, request, pk): 修改指定的图书信息
- def delete(self, request, pk): 删除指定的图书信息
<|skeleton|>
class BookDetailView:
def ... | f8ec0bec399253e481e16443ba9a3e45e61486f4 | <|skeleton|>
class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
<|body_0|>
def put(self, request, pk):
"""修改指定的图书信息"""
<|body_1|>
def delete(self, request, pk):
"""删除指定的图书信息"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BookDetailView:
def get(self, request, pk):
"""获取指定的图书信息"""
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
data = {'id': book.id, 'btitle': book.btitle, 'bpub_date': book.bpub_date, 'bread': book.bre... | the_stack_v2_python_sparse | drf_demo/booktest/views-01-Django自定义RestAPI接口.py | cz495969281/2019_- | train | 0 | |
75165da7ff331d52d1019aa2d32756261183f5ff | [
"adjudicator = Adjudicator.query.get(adjudicator_id)\nif adjudicator is not None:\n return adjudicator.json()\nabort(404, 'Unknown adjudicator_id')",
"adjudicator = Adjudicator.query.get(adjudicator_id)\nif adjudicator is not None:\n adjudicator.name = api.payload['name']\n adjudicator.tag = api.payload[... | <|body_start_0|>
adjudicator = Adjudicator.query.get(adjudicator_id)
if adjudicator is not None:
return adjudicator.json()
abort(404, 'Unknown adjudicator_id')
<|end_body_0|>
<|body_start_1|>
adjudicator = Adjudicator.query.get(adjudicator_id)
if adjudicator is not N... | AdjudicatorsAPISpecific | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdjudicatorsAPISpecific:
def get(self, adjudicator_id):
"""Specific adjudicator"""
<|body_0|>
def patch(self, adjudicator_id):
"""Update existing adjudicator"""
<|body_1|>
def delete(self, adjudicator_id):
"""Delete adjudicator"""
<|body_... | stack_v2_sparse_classes_36k_train_003133 | 3,112 | no_license | [
{
"docstring": "Specific adjudicator",
"name": "get",
"signature": "def get(self, adjudicator_id)"
},
{
"docstring": "Update existing adjudicator",
"name": "patch",
"signature": "def patch(self, adjudicator_id)"
},
{
"docstring": "Delete adjudicator",
"name": "delete",
"s... | 3 | stack_v2_sparse_classes_30k_train_017322 | Implement the Python class `AdjudicatorsAPISpecific` described below.
Class description:
Implement the AdjudicatorsAPISpecific class.
Method signatures and docstrings:
- def get(self, adjudicator_id): Specific adjudicator
- def patch(self, adjudicator_id): Update existing adjudicator
- def delete(self, adjudicator_id... | Implement the Python class `AdjudicatorsAPISpecific` described below.
Class description:
Implement the AdjudicatorsAPISpecific class.
Method signatures and docstrings:
- def get(self, adjudicator_id): Specific adjudicator
- def patch(self, adjudicator_id): Update existing adjudicator
- def delete(self, adjudicator_id... | 079b109fd13683a31d1d632faa5ab72cf0e78ddf | <|skeleton|>
class AdjudicatorsAPISpecific:
def get(self, adjudicator_id):
"""Specific adjudicator"""
<|body_0|>
def patch(self, adjudicator_id):
"""Update existing adjudicator"""
<|body_1|>
def delete(self, adjudicator_id):
"""Delete adjudicator"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdjudicatorsAPISpecific:
def get(self, adjudicator_id):
"""Specific adjudicator"""
adjudicator = Adjudicator.query.get(adjudicator_id)
if adjudicator is not None:
return adjudicator.json()
abort(404, 'Unknown adjudicator_id')
def patch(self, adjudicator_id):
... | the_stack_v2_python_sparse | backend/apis/adjudicators/apis.py | AlenAlic/DANCE | train | 0 | |
624a0723b90324fdc737f34bb8ec9d0fe32a5e20 | [
"v = utils.splitpath_root_file_ext('F:\\\\foo\\\\bar.py')\nself.assertEqual(v, ('F:\\\\foo', 'bar', '.py'))\nv = utils.splitpath_root_file_ext('J:\\\\spam.py')\nself.assertEqual(v, ('J:\\\\', 'spam', '.py'))",
"v = utils.splitpath_root_file_ext('C:\\\\foo\\\\bar')\nself.assertEqual(v, ('C:\\\\foo', 'bar', ''))\nv... | <|body_start_0|>
v = utils.splitpath_root_file_ext('F:\\foo\\bar.py')
self.assertEqual(v, ('F:\\foo', 'bar', '.py'))
v = utils.splitpath_root_file_ext('J:\\spam.py')
self.assertEqual(v, ('J:\\', 'spam', '.py'))
<|end_body_0|>
<|body_start_1|>
v = utils.splitpath_root_file_ext('C... | TestSplitRootFileExt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
<|body_0|>
def testDirOnly(self):
"""Test behavior when passed a path only."""
<|body_1|>
def testFileOnly(self):
"""Test behavior when passed a f... | stack_v2_sparse_classes_36k_train_003134 | 2,610 | permissive | [
{
"docstring": "Test the method's behavior on regular paths.",
"name": "testRegularPath",
"signature": "def testRegularPath(self)"
},
{
"docstring": "Test behavior when passed a path only.",
"name": "testDirOnly",
"signature": "def testDirOnly(self)"
},
{
"docstring": "Test behav... | 3 | stack_v2_sparse_classes_30k_train_008079 | Implement the Python class `TestSplitRootFileExt` described below.
Class description:
Implement the TestSplitRootFileExt class.
Method signatures and docstrings:
- def testRegularPath(self): Test the method's behavior on regular paths.
- def testDirOnly(self): Test behavior when passed a path only.
- def testFileOnly... | Implement the Python class `TestSplitRootFileExt` described below.
Class description:
Implement the TestSplitRootFileExt class.
Method signatures and docstrings:
- def testRegularPath(self): Test the method's behavior on regular paths.
- def testDirOnly(self): Test behavior when passed a path only.
- def testFileOnly... | 679397c86992fe434e3aabff7edf4f6867424bc9 | <|skeleton|>
class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
<|body_0|>
def testDirOnly(self):
"""Test behavior when passed a path only."""
<|body_1|>
def testFileOnly(self):
"""Test behavior when passed a f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestSplitRootFileExt:
def testRegularPath(self):
"""Test the method's behavior on regular paths."""
v = utils.splitpath_root_file_ext('F:\\foo\\bar.py')
self.assertEqual(v, ('F:\\foo', 'bar', '.py'))
v = utils.splitpath_root_file_ext('J:\\spam.py')
self.assertEqual(v, (... | the_stack_v2_python_sparse | pynocle-0.3.2/build/lib.linux-x86_64-2.7/pynocle/test_utils.py | 1147279/SoftwareProject | train | 0 | |
4d3b08e31bf040e50a28556fb0d8863e3b4c16a4 | [
"if self.GUI.machinefamily.lower().startswith('scroll'):\n return True\nelse:\n return False",
"chunk = []\nfor line in self.injection_panel.Lines:\n l = {}\n l['Length'] = float(line.Lval.GetValue())\n l['ID'] = float(line.IDval.GetValue())\n State = line.state.GetState()\n l['inletState'] =... | <|body_start_0|>
if self.GUI.machinefamily.lower().startswith('scroll'):
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
chunk = []
for line in self.injection_panel.Lines:
l = {}
l['Length'] = float(line.Lval.GetValue())
... | A plugin that adds the injection ports for the scroll compressor | ScrollInjectionPlugin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScrollInjectionPlugin:
"""A plugin that adds the injection ports for the scroll compressor"""
def should_enable(self):
"""Only enable if it is a scroll type compressor"""
<|body_0|>
def get_config_chunk(self):
"""The chunk for the configuration file"""
<|... | stack_v2_sparse_classes_36k_train_003135 | 40,548 | permissive | [
{
"docstring": "Only enable if it is a scroll type compressor",
"name": "should_enable",
"signature": "def should_enable(self)"
},
{
"docstring": "The chunk for the configuration file",
"name": "get_config_chunk",
"signature": "def get_config_chunk(self)"
},
{
"docstring": "Calle... | 4 | stack_v2_sparse_classes_30k_train_012472 | Implement the Python class `ScrollInjectionPlugin` described below.
Class description:
A plugin that adds the injection ports for the scroll compressor
Method signatures and docstrings:
- def should_enable(self): Only enable if it is a scroll type compressor
- def get_config_chunk(self): The chunk for the configurati... | Implement the Python class `ScrollInjectionPlugin` described below.
Class description:
A plugin that adds the injection ports for the scroll compressor
Method signatures and docstrings:
- def should_enable(self): Only enable if it is a scroll type compressor
- def get_config_chunk(self): The chunk for the configurati... | 2e33166fdbb3b868a196607c3d06de54e429824d | <|skeleton|>
class ScrollInjectionPlugin:
"""A plugin that adds the injection ports for the scroll compressor"""
def should_enable(self):
"""Only enable if it is a scroll type compressor"""
<|body_0|>
def get_config_chunk(self):
"""The chunk for the configuration file"""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScrollInjectionPlugin:
"""A plugin that adds the injection ports for the scroll compressor"""
def should_enable(self):
"""Only enable if it is a scroll type compressor"""
if self.GUI.machinefamily.lower().startswith('scroll'):
return True
else:
return False... | the_stack_v2_python_sparse | GUI/plugins/scroll_plugins.py | ibell/pdsim | train | 36 |
0276d3d6cbb6dc792a5d137dc811b4cd5900f615 | [
"if self.is_property_available('IsComplete'):\n return bool(self.properties['IsComplete'])\nreturn None",
"if self.is_property_available('PollingInterval'):\n return int(self.properties['PollingInterval']) / 1000\nreturn None"
] | <|body_start_0|>
if self.is_property_available('IsComplete'):
return bool(self.properties['IsComplete'])
return None
<|end_body_0|>
<|body_start_1|>
if self.is_property_available('PollingInterval'):
return int(self.properties['PollingInterval']) / 1000
return Non... | Represents an operation on a site collection. | SpoOperation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpoOperation:
"""Represents an operation on a site collection."""
def is_complete(self):
"""Gets a value that indicates whether the operation has completed."""
<|body_0|>
def polling_interval_secs(self):
"""Gets the recommended interval to poll for the IsComplete... | stack_v2_sparse_classes_36k_train_003136 | 675 | permissive | [
{
"docstring": "Gets a value that indicates whether the operation has completed.",
"name": "is_complete",
"signature": "def is_complete(self)"
},
{
"docstring": "Gets the recommended interval to poll for the IsComplete property.",
"name": "polling_interval_secs",
"signature": "def pollin... | 2 | null | Implement the Python class `SpoOperation` described below.
Class description:
Represents an operation on a site collection.
Method signatures and docstrings:
- def is_complete(self): Gets a value that indicates whether the operation has completed.
- def polling_interval_secs(self): Gets the recommended interval to po... | Implement the Python class `SpoOperation` described below.
Class description:
Represents an operation on a site collection.
Method signatures and docstrings:
- def is_complete(self): Gets a value that indicates whether the operation has completed.
- def polling_interval_secs(self): Gets the recommended interval to po... | cbd245d1af8d69e013c469cfc2a9851f51c91417 | <|skeleton|>
class SpoOperation:
"""Represents an operation on a site collection."""
def is_complete(self):
"""Gets a value that indicates whether the operation has completed."""
<|body_0|>
def polling_interval_secs(self):
"""Gets the recommended interval to poll for the IsComplete... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpoOperation:
"""Represents an operation on a site collection."""
def is_complete(self):
"""Gets a value that indicates whether the operation has completed."""
if self.is_property_available('IsComplete'):
return bool(self.properties['IsComplete'])
return None
def ... | the_stack_v2_python_sparse | office365/sharepoint/tenant/administration/spo_operation.py | vgrem/Office365-REST-Python-Client | train | 1,006 |
2f5ccad2d1fba4c608abe198d9c772f45a7cd808 | [
"count = len(prices)\nif count < 2:\n return 0\ndp = [0 for _ in xrange(count)]\nfor i in xrange(1, count):\n if prices[i] >= prices[i - 1]:\n dp[i] = dp[i - 1] + (prices[i] - prices[i - 1])\n else:\n dp[i] = dp[i - 1]\nreturn dp[-1]",
"count = len(prices)\nif count < 2:\n return 0\nprof... | <|body_start_0|>
count = len(prices)
if count < 2:
return 0
dp = [0 for _ in xrange(count)]
for i in xrange(1, count):
if prices[i] >= prices[i - 1]:
dp[i] = dp[i - 1] + (prices[i] - prices[i - 1])
else:
dp[i] = dp[i - 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_O_1_space(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = len(prices)
if ... | stack_v2_sparse_classes_36k_train_003137 | 854 | no_license | [
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit",
"signature": "def maxProfit(self, prices)"
},
{
"docstring": ":type prices: List[int] :rtype: int",
"name": "maxProfit_O_1_space",
"signature": "def maxProfit_O_1_space(self, prices)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002219 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_O_1_space(self, prices): :type prices: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices): :type prices: List[int] :rtype: int
- def maxProfit_O_1_space(self, prices): :type prices: List[int] :rtype: int
<|skeleton|>
class Solution:
d... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit_O_1_space(self, prices):
""":type prices: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices):
""":type prices: List[int] :rtype: int"""
count = len(prices)
if count < 2:
return 0
dp = [0 for _ in xrange(count)]
for i in xrange(1, count):
if prices[i] >= prices[i - 1]:
dp[i] = dp[i - 1... | the_stack_v2_python_sparse | 122_best_time_to_buy_and_sell_stock_2/sol.py | lianke123321/leetcode_sol | train | 0 | |
b2fbdc572174b4974b0cc4bfee1c8f6203e9fe5d | [
"IPAddress.__init__(self)\nif not self.IsValid(address):\n raise errors.IPAddressError('IPv6 Address [%s] invalid' % address)\nself.address = address",
"doublecolons = address.count('::')\nassert not doublecolons > 1\nif doublecolons == 1:\n parts = []\n twoparts = address.split('::')\n sep = len(twop... | <|body_start_0|>
IPAddress.__init__(self)
if not self.IsValid(address):
raise errors.IPAddressError('IPv6 Address [%s] invalid' % address)
self.address = address
<|end_body_0|>
<|body_start_1|>
doublecolons = address.count('::')
assert not doublecolons > 1
if... | IPv6 address class. | IP6Address | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
<|body_0|>
def _GetIPIntFromString(address):
"""Get integer valu... | stack_v2_sparse_classes_36k_train_003138 | 20,645 | permissive | [
{
"docstring": "Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid",
"name": "__init__",
"signature": "def __init__(self, address)"
},
{
"docstring": "Get integer value of IPv6 address. @type address: str @param address: ... | 2 | null | Implement the Python class `IP6Address` described below.
Class description:
IPv6 address class.
Method signatures and docstrings:
- def __init__(self, address): Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid
- def _GetIPIntFromString(addre... | Implement the Python class `IP6Address` described below.
Class description:
IPv6 address class.
Method signatures and docstrings:
- def __init__(self, address): Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid
- def _GetIPIntFromString(addre... | 456ea285a7583183c2c8e5bcffe9006ec8a9d658 | <|skeleton|>
class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
<|body_0|>
def _GetIPIntFromString(address):
"""Get integer valu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IP6Address:
"""IPv6 address class."""
def __init__(self, address):
"""Constructor for IPv6 address. @type address: str @param address: IP address @raises errors.IPAddressError: if address invalid"""
IPAddress.__init__(self)
if not self.IsValid(address):
raise errors.IP... | the_stack_v2_python_sparse | lib/netutils.py | ganeti/ganeti | train | 465 |
a8f692c5ccc1fb8d13e313b95847776a77df2470 | [
"s = s.strip()\nif not s:\n return 0\nsign = -1 if s[0] == '-' else 1\nval = 0\nfor c in s:\n if c.isdigit():\n val = val * 10 + ord(c) - ord('0')\nreturn sign * val",
"s = s.strip()\nif not s:\n return 0\nsign = -1 if s[0] == '-' else 1\nval, index = (0, 0)\nif s[0] in ['+', '-']:\n index = 1\... | <|body_start_0|>
s = s.strip()
if not s:
return 0
sign = -1 if s[0] == '-' else 1
val = 0
for c in s:
if c.isdigit():
val = val * 10 + ord(c) - ord('0')
return sign * val
<|end_body_0|>
<|body_start_1|>
s = s.strip()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss... | stack_v2_sparse_classes_36k_train_003139 | 1,416 | no_license | [
{
"docstring": ":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss.leetcode.com/topic/26920/60ms-python-solu... | 2 | stack_v2_sparse_classes_30k_train_009239 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetco... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myAtoi(self, s): :type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetco... | 57212d700dfba0db4925d9d4896f7f0b9635a5b5 | <|skeleton|>
class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def myAtoi(self, s):
""":type str: str :rtype: int This is the sane version of the Idea ATOI where illegal chars in the given string 's' are ignored as one would. The version leetcode required was to quit when an illegal char is encountered and can be found here https://discuss.leetcode.com/... | the_stack_v2_python_sparse | atoi.py | baloooo/coding_practice | train | 0 | |
8c2d19fafcaef16e436b295694713b2fc759d5a9 | [
"super(DenseQNetwork, self).__init__()\nself.seed = torch.manual_seed(seed)\nself.fc1 = nn.Linear(state_size, fc1_units)\nself.fc2 = nn.Linear(fc1_units, fc2_units)\nself.fc3 = nn.Linear(fc2_units, action_size)",
"x = F.relu(self.fc1(state))\nx = F.relu(self.fc2(x))\nreturn self.fc3(x)"
] | <|body_start_0|>
super(DenseQNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.fc1 = nn.Linear(state_size, fc1_units)
self.fc2 = nn.Linear(fc1_units, fc2_units)
self.fc3 = nn.Linear(fc2_units, action_size)
<|end_body_0|>
<|body_start_1|>
x = F.relu(self.... | Actor (Policy) Model. | DenseQNetwork | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DenseQNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128):
"""Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be continuous) action_size (int): number of actions in the d... | stack_v2_sparse_classes_36k_train_003140 | 9,301 | permissive | [
{
"docstring": "Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be continuous) action_size (int): number of actions in the discrete action domain seed (int): random seed fc1_units (int): size of the hidden layer fc2_units (int): size of the hidden layer",
"na... | 2 | stack_v2_sparse_classes_30k_train_018747 | Implement the Python class `DenseQNetwork` described below.
Class description:
Actor (Policy) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128): Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be ... | Implement the Python class `DenseQNetwork` described below.
Class description:
Actor (Policy) Model.
Method signatures and docstrings:
- def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128): Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be ... | ed868916d06dbf68f4af23bea83b0e852e88df6e | <|skeleton|>
class DenseQNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128):
"""Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be continuous) action_size (int): number of actions in the d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DenseQNetwork:
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128):
"""Set up the layers of the DQN Args: state_size (int): number of states in the state variable (can be continuous) action_size (int): number of actions in the discrete actio... | the_stack_v2_python_sparse | simple_rl/agents/func_approx/sam_stuff/model.py | samlobel/simple_rl_mbrl | train | 1 |
7102898c76ab92c702557deb0f20aa42967d2770 | [
"with mute_signals(post_save):\n profile = ProfileFactory(first_name='First', last_name='Last', preferred_name='Pref')\nassert profile.display_name == 'First Last (Pref)'",
"with mute_signals(post_save):\n profile = ProfileFactory(first_name='First', last_name='Last', preferred_name=pref_name)\nassert profi... | <|body_start_0|>
with mute_signals(post_save):
profile = ProfileFactory(first_name='First', last_name='Last', preferred_name='Pref')
assert profile.display_name == 'First Last (Pref)'
<|end_body_0|>
<|body_start_1|>
with mute_signals(post_save):
profile = ProfileFactory(... | Tests for profile display name | ProfileDisplayNameTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileDisplayNameTests:
"""Tests for profile display name"""
def test_full_display_name(self):
"""Test the profile display name with all name components set"""
<|body_0|>
def test_display_name_without_preferred(self, pref_name):
"""Test the profile display name ... | stack_v2_sparse_classes_36k_train_003141 | 10,083 | permissive | [
{
"docstring": "Test the profile display name with all name components set",
"name": "test_full_display_name",
"signature": "def test_full_display_name(self)"
},
{
"docstring": "Test the profile display name with a preferred name that is blank or equal to first name",
"name": "test_display_n... | 5 | null | Implement the Python class `ProfileDisplayNameTests` described below.
Class description:
Tests for profile display name
Method signatures and docstrings:
- def test_full_display_name(self): Test the profile display name with all name components set
- def test_display_name_without_preferred(self, pref_name): Test the ... | Implement the Python class `ProfileDisplayNameTests` described below.
Class description:
Tests for profile display name
Method signatures and docstrings:
- def test_full_display_name(self): Test the profile display name with all name components set
- def test_display_name_without_preferred(self, pref_name): Test the ... | d6564caca0b7bbfd31e67a751564107fd17d6eb0 | <|skeleton|>
class ProfileDisplayNameTests:
"""Tests for profile display name"""
def test_full_display_name(self):
"""Test the profile display name with all name components set"""
<|body_0|>
def test_display_name_without_preferred(self, pref_name):
"""Test the profile display name ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileDisplayNameTests:
"""Tests for profile display name"""
def test_full_display_name(self):
"""Test the profile display name with all name components set"""
with mute_signals(post_save):
profile = ProfileFactory(first_name='First', last_name='Last', preferred_name='Pref')
... | the_stack_v2_python_sparse | profiles/models_test.py | mitodl/micromasters | train | 35 |
228918554449272c924e9a6dc7166e6b20f876d8 | [
"self.input_dim = input_dim\nself.sequence_length = sequence_length\nself.data_type = data_type\nself.last_avg = last_avg\nself.classes_list = classes_list\nself.model = KNNC(num_neighbors, weights=weights, metric=metric)\nself.data_dir = data_dir\nself.classes_dict = {}\nfor i, c in enumerate(classes_list):\n s... | <|body_start_0|>
self.input_dim = input_dim
self.sequence_length = sequence_length
self.data_type = data_type
self.last_avg = last_avg
self.classes_list = classes_list
self.model = KNNC(num_neighbors, weights=weights, metric=metric)
self.data_dir = data_dir
... | KNN | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KNN:
def __init__(self, input_dim: int=62, last_avg: int=3, data_dir: str='../data_train', sequence_length: int=45, data_type: DataType=DataType.HIGH_PASS, classes_list: list=['acetone', 'isopropanol', 'orange_juice', 'pinot_noir', 'raisin', 'wodka'], weights: str='distance', metric: str='euclid... | stack_v2_sparse_classes_36k_train_003142 | 4,079 | permissive | [
{
"docstring": "Class for a classifier based on k-nearest-neighbor approach defining training and prediction function. The saturated sensor values of the same class are assumed to have a small distance, whereas the distance between data points of different classes should be large. During inference the classes o... | 3 | stack_v2_sparse_classes_30k_train_007916 | Implement the Python class `KNN` described below.
Class description:
Implement the KNN class.
Method signatures and docstrings:
- def __init__(self, input_dim: int=62, last_avg: int=3, data_dir: str='../data_train', sequence_length: int=45, data_type: DataType=DataType.HIGH_PASS, classes_list: list=['acetone', 'isopr... | Implement the Python class `KNN` described below.
Class description:
Implement the KNN class.
Method signatures and docstrings:
- def __init__(self, input_dim: int=62, last_avg: int=3, data_dir: str='../data_train', sequence_length: int=45, data_type: DataType=DataType.HIGH_PASS, classes_list: list=['acetone', 'isopr... | fdf2d58b96464db2d639baeebf9cd4b2e08306dd | <|skeleton|>
class KNN:
def __init__(self, input_dim: int=62, last_avg: int=3, data_dir: str='../data_train', sequence_length: int=45, data_type: DataType=DataType.HIGH_PASS, classes_list: list=['acetone', 'isopropanol', 'orange_juice', 'pinot_noir', 'raisin', 'wodka'], weights: str='distance', metric: str='euclid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KNN:
def __init__(self, input_dim: int=62, last_avg: int=3, data_dir: str='../data_train', sequence_length: int=45, data_type: DataType=DataType.HIGH_PASS, classes_list: list=['acetone', 'isopropanol', 'orange_juice', 'pinot_noir', 'raisin', 'wodka'], weights: str='distance', metric: str='euclidean', num_neig... | the_stack_v2_python_sparse | classification/knn.py | Roboy/roboy_smells | train | 0 | |
f1969c4e270089b7c5638ec07650f164737182ae | [
"self.absolute_path = absolute_path\nself.attached_disk_id = attached_disk_id\nself.disk_partition_id = disk_partition_id\nself.fs_uuid = fs_uuid\nself.inode_number = inode_number\nself.is_directory = is_directory\nself.is_non_simple_ldm_vol = is_non_simple_ldm_vol\nself.restore_base_directory = restore_base_direct... | <|body_start_0|>
self.absolute_path = absolute_path
self.attached_disk_id = attached_disk_id
self.disk_partition_id = disk_partition_id
self.fs_uuid = fs_uuid
self.inode_number = inode_number
self.is_directory = is_directory
self.is_non_simple_ldm_vol = is_non_sim... | Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_disk_id (int): Disk information of where the source file is currently located. disk_pa... | RestoredFileInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoredFileInfo:
"""Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_disk_id (int): Disk information of where t... | stack_v2_sparse_classes_36k_train_003143 | 5,823 | permissive | [
{
"docstring": "Constructor for the RestoredFileInfo class",
"name": "__init__",
"signature": "def __init__(self, absolute_path=None, attached_disk_id=None, disk_partition_id=None, fs_uuid=None, inode_number=None, is_directory=None, is_non_simple_ldm_vol=None, restore_base_directory=None, restore_mount_... | 2 | null | Implement the Python class `RestoredFileInfo` described below.
Class description:
Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_dis... | Implement the Python class `RestoredFileInfo` described below.
Class description:
Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_dis... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoredFileInfo:
"""Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_disk_id (int): Disk information of where t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoredFileInfo:
"""Implementation of the 'RestoredFileInfo' model. TODO: type description here. Attributes: absolute_path (string): Full path of the file being restored: the actual file path without the disk. E.g.: \\Program Files\\App ile.txt attached_disk_id (int): Disk information of where the source fil... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restored_file_info.py | cohesity/management-sdk-python | train | 24 |
90ce7ace693bfa9bedbf483ab21789c9cfb8b792 | [
"super().__init__(ws, session_id, target_id)\nself._dom_enable_count = 0\nself._dom_enable_lock = trio.Lock()\nself._page_enable_count = 0\nself._page_enable_lock = trio.Lock()",
"global devtools\nasync with self._dom_enable_lock:\n self._dom_enable_count += 1\n if self._dom_enable_count == 1:\n awai... | <|body_start_0|>
super().__init__(ws, session_id, target_id)
self._dom_enable_count = 0
self._dom_enable_lock = trio.Lock()
self._page_enable_count = 0
self._page_enable_lock = trio.Lock()
<|end_body_0|>
<|body_start_1|>
global devtools
async with self._dom_enabl... | Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`. | CdpSession | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CdpSession:
"""Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`."""
def __init__(self, ws, session_id, target_id):
"""Constructor. :param trio_websocket.WebSocketConnection ws: :param d... | stack_v2_sparse_classes_36k_train_003144 | 17,960 | permissive | [
{
"docstring": "Constructor. :param trio_websocket.WebSocketConnection ws: :param devtools.target.SessionID session_id: :param devtools.target.TargetID target_id:",
"name": "__init__",
"signature": "def __init__(self, ws, session_id, target_id)"
},
{
"docstring": "A context manager that executes... | 3 | null | Implement the Python class `CdpSession` described below.
Class description:
Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`.
Method signatures and docstrings:
- def __init__(self, ws, session_id, target_id): Constructo... | Implement the Python class `CdpSession` described below.
Class description:
Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`.
Method signatures and docstrings:
- def __init__(self, ws, session_id, target_id): Constructo... | cc41a883b5138962c6b4408a0fdf4e932bd08071 | <|skeleton|>
class CdpSession:
"""Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`."""
def __init__(self, ws, session_id, target_id):
"""Constructor. :param trio_websocket.WebSocketConnection ws: :param d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CdpSession:
"""Contains the state for a CDP session. Generally you should not instantiate this object yourself; you should call :meth:`CdpConnection.open_session`."""
def __init__(self, ws, session_id, target_id):
"""Constructor. :param trio_websocket.WebSocketConnection ws: :param devtools.targe... | the_stack_v2_python_sparse | py/selenium/webdriver/common/bidi/cdp.py | SeleniumHQ/selenium | train | 30,383 |
b2633b0ae1a2ad1899a790f52e4b4e47facdc21a | [
"timestamp = self._GetRowValue(query_hash, row, value_name)\nif timestamp is None:\n return None\nreturn dfdatetime_filetime.Filetime(timestamp=timestamp)",
"query_hash = hash(query)\nevent_data = WindowsEventTranscriptEventData()\nevent_data.compressed_payload_size = self._GetRowValue(query_hash, row, 'compre... | <|body_start_0|>
timestamp = self._GetRowValue(query_hash, row, value_name)
if timestamp is None:
return None
return dfdatetime_filetime.Filetime(timestamp=timestamp)
<|end_body_0|>
<|body_start_1|>
query_hash = hash(query)
event_data = WindowsEventTranscriptEventDat... | SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db | EventTranscriptPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventTranscriptPlugin:
"""SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and ... | stack_v2_sparse_classes_36k_train_003145 | 7,833 | permissive | [
{
"docstring": "Retrieves a date and time value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: dfdatetime.Filetime: date and time value or None if not available.",
"name"... | 2 | null | Implement the Python class `EventTranscriptPlugin` described below.
Class description:
SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db
Method signatures and docstrings:
- def _GetDateTimeRowValue(... | Implement the Python class `EventTranscriptPlugin` described below.
Class description:
SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db
Method signatures and docstrings:
- def _GetDateTimeRowValue(... | d6022f8cfebfddf2d08ab2d300a41b61f3349933 | <|skeleton|>
class EventTranscriptPlugin:
"""SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventTranscriptPlugin:
"""SQLite parser plugin for Windows diagnosis EventTranscript database files. The Windows diagnosis EventTranscript database file is typically stored in: EventTranscript.db"""
def _GetDateTimeRowValue(self, query_hash, row, value_name):
"""Retrieves a date and time value fr... | the_stack_v2_python_sparse | plaso/parsers/sqlite_plugins/windows_eventtranscript.py | log2timeline/plaso | train | 1,506 |
61f9f95cc907194523a5891c8c60bfeb31e76a72 | [
"genre_data = Genre.query.get(genre_id)\nif genre_data:\n logging.info('Genre returned from ID %d. Genre %s', genre_id, genre_data.genre_name)\n return (genre_schema.dump(genre_data), 200)\nlogging.info('Genre with ID %d was not found', genre_id)\nreturn {'status': 404, 'message': GENRE_NOT_FOUND}",
"if cur... | <|body_start_0|>
genre_data = Genre.query.get(genre_id)
if genre_data:
logging.info('Genre returned from ID %d. Genre %s', genre_id, genre_data.genre_name)
return (genre_schema.dump(genre_data), 200)
logging.info('Genre with ID %d was not found', genre_id)
return ... | Genre Data Resource Class | GenreListId | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenreListId:
"""Genre Data Resource Class"""
def get(cls, genre_id) -> (dict, int):
"""Get method :param genre_id: genre`s id :return: error message or json with information about the genre"""
<|body_0|>
def delete(cls, genre_id) -> dict:
"""Delete method :param ... | stack_v2_sparse_classes_36k_train_003146 | 4,244 | no_license | [
{
"docstring": "Get method :param genre_id: genre`s id :return: error message or json with information about the genre",
"name": "get",
"signature": "def get(cls, genre_id) -> (dict, int)"
},
{
"docstring": "Delete method :param genre_id: genre`s id :return: error message or successful message",... | 3 | stack_v2_sparse_classes_30k_train_004806 | Implement the Python class `GenreListId` described below.
Class description:
Genre Data Resource Class
Method signatures and docstrings:
- def get(cls, genre_id) -> (dict, int): Get method :param genre_id: genre`s id :return: error message or json with information about the genre
- def delete(cls, genre_id) -> dict: ... | Implement the Python class `GenreListId` described below.
Class description:
Genre Data Resource Class
Method signatures and docstrings:
- def get(cls, genre_id) -> (dict, int): Get method :param genre_id: genre`s id :return: error message or json with information about the genre
- def delete(cls, genre_id) -> dict: ... | 1033f7e4eb636aa30bf4088353a4af272ba226b6 | <|skeleton|>
class GenreListId:
"""Genre Data Resource Class"""
def get(cls, genre_id) -> (dict, int):
"""Get method :param genre_id: genre`s id :return: error message or json with information about the genre"""
<|body_0|>
def delete(cls, genre_id) -> dict:
"""Delete method :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenreListId:
"""Genre Data Resource Class"""
def get(cls, genre_id) -> (dict, int):
"""Get method :param genre_id: genre`s id :return: error message or json with information about the genre"""
genre_data = Genre.query.get(genre_id)
if genre_data:
logging.info('Genre re... | the_stack_v2_python_sparse | services/web/project/resources/genres.py | SvetlanaSumets11/nix_project | train | 0 |
2a29a36b777df39430757662e49ec5b5cf865c67 | [
"super(Lien, self).__init__(resource_id=name, resource_type=resource.ResourceType.LIEN, name='{}/liens/{}'.format(parent.name, name), display_name=name, parent=parent)\nself.full_name = '{}lien/{}/'.format(parent.full_name, name)\nself.restrictions = restrictions\nself.raw_json = raw_json",
"lien_dict = json.load... | <|body_start_0|>
super(Lien, self).__init__(resource_id=name, resource_type=resource.ResourceType.LIEN, name='{}/liens/{}'.format(parent.name, name), display_name=name, parent=parent)
self.full_name = '{}lien/{}/'.format(parent.full_name, name)
self.restrictions = restrictions
self.raw_j... | Lien Resource. | Lien | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json... | stack_v2_sparse_classes_36k_train_003147 | 2,171 | permissive | [
{
"docstring": "Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json of this lien.",
"name": "__init__",
"signature": "def __init__(self, parent, name, restrict... | 2 | null | Implement the Python class `Lien` described below.
Class description:
Lien Resource.
Method signatures and docstrings:
- def __init__(self, parent, name, restrictions, raw_json): Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrict... | Implement the Python class `Lien` described below.
Class description:
Lien Resource.
Method signatures and docstrings:
- def __init__(self, parent, name, restrictions, raw_json): Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrict... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lien:
"""Lien Resource."""
def __init__(self, parent, name, restrictions, raw_json):
"""Initialize a Lien. Args: parent (Resource): resource this lien belongs to. name (str): name of the lien. restrictions (List[str]): restrictions this lien protects against. raw_json (str): raw json of this lien... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_type/lien.py | kevensen/forseti-security | train | 1 |
819816c45841713c2c480874b96abf0cfe25ff3b | [
"self.optimizers = []\nself.sample_x = []\nself.sample_y = []\nself.best_y = []\nself.pending_x = []\nself.next_optim = 0\nself.num_optim = len(optim_list)\nself.path = save_path\nself.save_each_iter = save_each_iter\nself.__create_optimizers(optim_list, acq_func_list, h_space, num_init_rand)",
"for algo_name in ... | <|body_start_0|>
self.optimizers = []
self.sample_x = []
self.sample_y = []
self.best_y = []
self.pending_x = []
self.next_optim = 0
self.num_optim = len(optim_list)
self.path = save_path
self.save_each_iter = save_each_iter
self.__create_o... | Manager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manager:
def __init__(self, optim_list, acq_func_list, h_space, num_init_rand, save_path='', save_each_iter=False):
"""The Manager constructor :param optim_list: A list of optimizer algorithm to instantiate :param acq_func_list: A list of acquisition function that will be used the optimi... | stack_v2_sparse_classes_36k_train_003148 | 5,707 | no_license | [
{
"docstring": "The Manager constructor :param optim_list: A list of optimizer algorithm to instantiate :param acq_func_list: A list of acquisition function that will be used the optimizer of type gaussian process :param h_space: The hyperparameters space that will be used by each optimizer to construct the sur... | 5 | stack_v2_sparse_classes_30k_test_000440 | Implement the Python class `Manager` described below.
Class description:
Implement the Manager class.
Method signatures and docstrings:
- def __init__(self, optim_list, acq_func_list, h_space, num_init_rand, save_path='', save_each_iter=False): The Manager constructor :param optim_list: A list of optimizer algorithm ... | Implement the Python class `Manager` described below.
Class description:
Implement the Manager class.
Method signatures and docstrings:
- def __init__(self, optim_list, acq_func_list, h_space, num_init_rand, save_path='', save_each_iter=False): The Manager constructor :param optim_list: A list of optimizer algorithm ... | 45057f45b1397db429a0ed7f7ee5b3edbf1c1728 | <|skeleton|>
class Manager:
def __init__(self, optim_list, acq_func_list, h_space, num_init_rand, save_path='', save_each_iter=False):
"""The Manager constructor :param optim_list: A list of optimizer algorithm to instantiate :param acq_func_list: A list of acquisition function that will be used the optimi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Manager:
def __init__(self, optim_list, acq_func_list, h_space, num_init_rand, save_path='', save_each_iter=False):
"""The Manager constructor :param optim_list: A list of optimizer algorithm to instantiate :param acq_func_list: A list of acquisition function that will be used the optimizer of type ga... | the_stack_v2_python_sparse | Scheduler/Manager.py | AleAyotte/HyperPara | train | 6 | |
7463025b5c37c6c76729f761891d1b0f75677aba | [
"for name, layer in self._tf_layers.items():\n if isinstance(layer, RasaCustomLayer):\n layer.adjust_sparse_layers_for_incremental_training(new_sparse_feature_sizes=new_sparse_feature_sizes, old_sparse_feature_sizes=old_sparse_feature_sizes, reg_lambda=reg_lambda)\n elif isinstance(layer, layers.DenseF... | <|body_start_0|>
for name, layer in self._tf_layers.items():
if isinstance(layer, RasaCustomLayer):
layer.adjust_sparse_layers_for_incremental_training(new_sparse_feature_sizes=new_sparse_feature_sizes, old_sparse_feature_sizes=old_sparse_feature_sizes, reg_lambda=reg_lambda)
... | Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this happens, we need to adjust our `DenseForSparse` layers to a new size. `Concatenat... | RasaCustomLayer | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RasaCustomLayer:
"""Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this happens, we need to adjust our `DenseF... | stack_v2_sparse_classes_36k_train_003149 | 49,066 | permissive | [
{
"docstring": "Finds and adjusts `DenseForSparse` layers during incremental training. Recursively looks through the layers until it finds all the `DenseForSparse` ones and adjusts those which have their sparse feature sizes increased. This function heavily relies on the name of `DenseForSparse` layer being in ... | 2 | null | Implement the Python class `RasaCustomLayer` described below.
Class description:
Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this... | Implement the Python class `RasaCustomLayer` described below.
Class description:
Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this... | 50857610bdf0c26dc61f3203a6cbb4bcf193768c | <|skeleton|>
class RasaCustomLayer:
"""Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this happens, we need to adjust our `DenseF... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RasaCustomLayer:
"""Parent class for all classes in `rasa_layers.py`. Allows a shared implementation for adjusting `DenseForSparse` layers during incremental training. During fine-tuning, sparse feature sizes might change due to addition of new data. If this happens, we need to adjust our `DenseForSparse` lay... | the_stack_v2_python_sparse | rasa/utils/tensorflow/rasa_layers.py | RasaHQ/rasa | train | 13,167 |
876513cfc06f68a1e625a4b0dc4914375eb7201a | [
"bug_priority = BugPriority()\nbug_priority.label = request.data['label']\ntry:\n bug_priority.save()\n serializer = BugPrioritySerializer(bug_priority, context={'request': request})\n return Response(serializer.data)\nexcept ValidationError as ex:\n return Response({'reason': ex.message}, status=status... | <|body_start_0|>
bug_priority = BugPriority()
bug_priority.label = request.data['label']
try:
bug_priority.save()
serializer = BugPrioritySerializer(bug_priority, context={'request': request})
return Response(serializer.data)
except ValidationError as ... | Level up bug priorities | BugPriorityView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BugPriorityView:
"""Level up bug priorities"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_priority instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug_priority Retur... | stack_v2_sparse_classes_36k_train_003150 | 3,503 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized bug_priority instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle GET requests for single bug_priority Returns: Response -- JSON serialized bug_priority",
"name": "retrieve"... | 5 | stack_v2_sparse_classes_30k_test_001124 | Implement the Python class `BugPriorityView` described below.
Class description:
Level up bug priorities
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug_priority instance
- def retrieve(self, request, pk=None): Handle GET requests for sing... | Implement the Python class `BugPriorityView` described below.
Class description:
Level up bug priorities
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug_priority instance
- def retrieve(self, request, pk=None): Handle GET requests for sing... | 2a74a967bf891d5ddd212f371abef1bf72ebb327 | <|skeleton|>
class BugPriorityView:
"""Level up bug priorities"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_priority instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug_priority Retur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BugPriorityView:
"""Level up bug priorities"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug_priority instance"""
bug_priority = BugPriority()
bug_priority.label = request.data['label']
try:
bug_priority.save()
... | the_stack_v2_python_sparse | bugboapi/views/bug_priority.py | S-L-Murphey/Bugbo-server | train | 1 |
7ef910140a9d2f63ef34668f89c8462a3792b35d | [
"self.prefix_sums = []\nprefix_sum = 0\nfor weight in w:\n prefix_sum += weight\n self.prefix_sums.append(prefix_sum)\nself.total_sum = prefix_sum",
"target = self.total_sum * random()\nlow, high = (0, len(self.prefix_sums))\nwhile low < high:\n mid = low + (high - low) // 2\n if target > self.prefix_... | <|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
<|end_body_0|>
<|body_start_1|>
target = self.total_sum * random()
low, high = (0, len(self... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.prefix_sums = []
prefix_sum = 0
for weight in w:
... | stack_v2_sparse_classes_36k_train_003151 | 4,170 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w: List[int])"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_test_000489 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w: List[int]): :type w: List[int]
- def pickIndex(self) -> int: :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":ty... | 3c0943ee9b373e4297aa43a4813f0033c284a5b2 | <|skeleton|>
class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self) -> int:
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w: List[int]):
""":type w: List[int]"""
self.prefix_sums = []
prefix_sum = 0
for weight in w:
prefix_sum += weight
self.prefix_sums.append(prefix_sum)
self.total_sum = prefix_sum
def pickIndex(self) -> int:
... | the_stack_v2_python_sparse | 528.random-pick-with-weight.py | Joecth/leetcode_3rd_vscode | train | 0 | |
d5cacbf48d08affed6a6fb7e4d4c55059bd4b274 | [
"self.num = num\nfor i, x in enumerate(events):\n if 'addC' in x.Event:\n for y in range(i + 1, i + PLAYER_COUNT):\n events[y].Event = dict()\nbidRows = filter(lambda x: 'bid' in x.Event, events)\nplayRows = filter(lambda x: 'playC' in x.Event, events)\nscoreRow = filter(lambda x: 'sco' in x.Ev... | <|body_start_0|>
self.num = num
for i, x in enumerate(events):
if 'addC' in x.Event:
for y in range(i + 1, i + PLAYER_COUNT):
events[y].Event = dict()
bidRows = filter(lambda x: 'bid' in x.Event, events)
playRows = filter(lambda x: 'playC' ... | Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner. tricks (list): Each element is... | Hand | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hand:
"""Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner... | stack_v2_sparse_classes_36k_train_003152 | 5,091 | permissive | [
{
"docstring": "Process events and store hand data. Args: num (int): Hand number events (list): List of events for this hand.",
"name": "__init__",
"signature": "def __init__(self, num, events)"
},
{
"docstring": "Set the bids attribute for the Hand. The 'actvP' in the final bid is the bid winne... | 4 | stack_v2_sparse_classes_30k_train_013946 | Implement the Python class `Hand` described below.
Class description:
Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dea... | Implement the Python class `Hand` described below.
Class description:
Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dea... | f8b9e8c073f555ff827fa7887153e82b263a8aab | <|skeleton|>
class Hand:
"""Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hand:
"""Helper class for parsing game logs. Attributes: num (int): The hand number within the game. trump (int): The trump for the hand. bids (dict): With the keys: - values (list): Bid amounts in pNum order (list index == pNum). - dealer (int): pNum of dealer. - winner (int): pNum of bid winner. tricks (lis... | the_stack_v2_python_sparse | db/parseLog.py | JackieChiles/Cinch | train | 2 |
80646d2c2036115c8bfaafaa8b73704303b86707 | [
"m, n = (len(matrix), len(matrix[0]))\nfor i in xrange(m / 2):\n tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]\n tmp2 = matrix[n - 1 - i][i:n - i]\n tmp2.reverse()\n tmp3 = [e[i] for e in matrix[i:n - i]]\n tmp3.reverse()\n tmp4 = matrix[i][i:n - i]\n for j in xrange(i, n - i):\n matrix... | <|body_start_0|>
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m / 2):
tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]
tmp2 = matrix[n - 1 - i][i:n - i]
tmp2.reverse()
tmp3 = [e[i] for e in matrix[i:n - i]]
tmp3.reverse()
tmp4... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k_train_003153 | 3,108 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
"name": "rotate",
"signature": "def rotate(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.",
... | 3 | stack_v2_sparse_classes_30k_train_009361 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix): :type matrix: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate(self, matrix): :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead.
- def rotate2(self, matrix): :type matrix: List[List[... | 4aa3a3a0da8b911e140446352debb9b567b6d78b | <|skeleton|>
class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
<|body_0|>
def rotate2(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate(self, matrix):
""":type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead."""
m, n = (len(matrix), len(matrix[0]))
for i in xrange(m / 2):
tmp1 = [e[n - 1 - i] for e in matrix[i:n - i]]
tmp2 = matrix... | the_stack_v2_python_sparse | rotate_image_48.py | adiggo/leetcode_py | train | 0 | |
77a79fa5b8ca9fd5a91768ddd050387930391c92 | [
"args = pagination_arguments.parse_args(request)\npage = args.get('page', 1)\nper_page = args.get('per_page', 10)\nleave_query = Leave.query\nleave_page = leave_query.paginate(page, per_page, error_out=False)\nreturn leave_page",
"data = request.json\nuser_id = data.get('user_id')\nstart_date = datetime.strptime(... | <|body_start_0|>
args = pagination_arguments.parse_args(request)
page = args.get('page', 1)
per_page = args.get('per_page', 10)
leave_query = Leave.query
leave_page = leave_query.paginate(page, per_page, error_out=False)
return leave_page
<|end_body_0|>
<|body_start_1|>
... | Manipulations with leave. | LeaveCollection | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeaveCollection:
"""Manipulations with leave."""
def get(self):
"""List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter."""
<|body_0|>
def post(self):
"""Registers a new leave application."""
<|body_... | stack_v2_sparse_classes_36k_train_003154 | 3,389 | no_license | [
{
"docstring": "List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Registers a new leave application.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020260 | Implement the Python class `LeaveCollection` described below.
Class description:
Manipulations with leave.
Method signatures and docstrings:
- def get(self): List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter.
- def post(self): Registers a new leave applicatio... | Implement the Python class `LeaveCollection` described below.
Class description:
Manipulations with leave.
Method signatures and docstrings:
- def get(self): List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter.
- def post(self): Registers a new leave applicatio... | 7d5737fc7dd008acb67d935d76f5238f5cdcfda8 | <|skeleton|>
class LeaveCollection:
"""Manipulations with leave."""
def get(self):
"""List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter."""
<|body_0|>
def post(self):
"""Registers a new leave application."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeaveCollection:
"""Manipulations with leave."""
def get(self):
"""List of leave. Returns a list of leave applications starting from ``page`` limited by ``per_page`` parameter."""
args = pagination_arguments.parse_args(request)
page = args.get('page', 1)
per_page = args.ge... | the_stack_v2_python_sparse | app/modules/leave/resources.py | CockyAmoeba/flask-restplus-leave-demo | train | 1 |
4eaaebf28a36f60b66505dff1d65f39ca9acdf17 | [
"if not isPluginRegistryLoaded() or not isInMainThread():\n return\nif canAppAccessDatabase():\n self.update_trackable_status()\n self.reset_part_pricing_flags()",
"from .models import BomItem\ntry:\n items = BomItem.objects.filter(part__trackable=False, sub_part__trackable=True)\n for item in item... | <|body_start_0|>
if not isPluginRegistryLoaded() or not isInMainThread():
return
if canAppAccessDatabase():
self.update_trackable_status()
self.reset_part_pricing_flags()
<|end_body_0|>
<|body_start_1|>
from .models import BomItem
try:
ite... | Config class for the 'part' app | PartConfig | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PartConfig:
"""Config class for the 'part' app"""
def ready(self):
"""This function is called whenever the Part app is loaded."""
<|body_0|>
def update_trackable_status(self):
"""Check for any instances where a trackable part is used in the BOM for a non-trackabl... | stack_v2_sparse_classes_36k_train_003155 | 2,253 | permissive | [
{
"docstring": "This function is called whenever the Part app is loaded.",
"name": "ready",
"signature": "def ready(self)"
},
{
"docstring": "Check for any instances where a trackable part is used in the BOM for a non-trackable part. In such a case, force the top-level part to be trackable too."... | 3 | null | Implement the Python class `PartConfig` described below.
Class description:
Config class for the 'part' app
Method signatures and docstrings:
- def ready(self): This function is called whenever the Part app is loaded.
- def update_trackable_status(self): Check for any instances where a trackable part is used in the B... | Implement the Python class `PartConfig` described below.
Class description:
Config class for the 'part' app
Method signatures and docstrings:
- def ready(self): This function is called whenever the Part app is loaded.
- def update_trackable_status(self): Check for any instances where a trackable part is used in the B... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class PartConfig:
"""Config class for the 'part' app"""
def ready(self):
"""This function is called whenever the Part app is loaded."""
<|body_0|>
def update_trackable_status(self):
"""Check for any instances where a trackable part is used in the BOM for a non-trackabl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PartConfig:
"""Config class for the 'part' app"""
def ready(self):
"""This function is called whenever the Part app is loaded."""
if not isPluginRegistryLoaded() or not isInMainThread():
return
if canAppAccessDatabase():
self.update_trackable_status()
... | the_stack_v2_python_sparse | InvenTree/part/apps.py | inventree/InvenTree | train | 3,077 |
4eb21ed0c6aad1db27383874aca9fe9dac922f70 | [
"schedule = parts.LinearSchedule(begin_t=5, decay_steps=7, begin_value=1.0, end_value=0.3)\nfor step in range(20):\n val = schedule(step)\n if step <= 5:\n self.assertEqual(1.0, val)\n elif step >= 12:\n self.assertEqual(0.3, val)\n else:\n self.assertAlmostEqual(1.0 - (step - 5) / ... | <|body_start_0|>
schedule = parts.LinearSchedule(begin_t=5, decay_steps=7, begin_value=1.0, end_value=0.3)
for step in range(20):
val = schedule(step)
if step <= 5:
self.assertEqual(1.0, val)
elif step >= 12:
self.assertEqual(0.3, val)
... | LinearScheduleTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearScheduleTest:
def test_descent(self):
"""Checks basic linear decay schedule."""
<|body_0|>
def test_ascent(self):
"""Checks basic linear ascent schedule."""
<|body_1|>
def test_constant(self):
"""Checks constant schedule."""
<|body_... | stack_v2_sparse_classes_36k_train_003156 | 10,408 | permissive | [
{
"docstring": "Checks basic linear decay schedule.",
"name": "test_descent",
"signature": "def test_descent(self)"
},
{
"docstring": "Checks basic linear ascent schedule.",
"name": "test_ascent",
"signature": "def test_ascent(self)"
},
{
"docstring": "Checks constant schedule.",... | 4 | stack_v2_sparse_classes_30k_test_001141 | Implement the Python class `LinearScheduleTest` described below.
Class description:
Implement the LinearScheduleTest class.
Method signatures and docstrings:
- def test_descent(self): Checks basic linear decay schedule.
- def test_ascent(self): Checks basic linear ascent schedule.
- def test_constant(self): Checks co... | Implement the Python class `LinearScheduleTest` described below.
Class description:
Implement the LinearScheduleTest class.
Method signatures and docstrings:
- def test_descent(self): Checks basic linear decay schedule.
- def test_ascent(self): Checks basic linear ascent schedule.
- def test_constant(self): Checks co... | f011d683529d8d23b017a95194ebbb41a4962fe8 | <|skeleton|>
class LinearScheduleTest:
def test_descent(self):
"""Checks basic linear decay schedule."""
<|body_0|>
def test_ascent(self):
"""Checks basic linear ascent schedule."""
<|body_1|>
def test_constant(self):
"""Checks constant schedule."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LinearScheduleTest:
def test_descent(self):
"""Checks basic linear decay schedule."""
schedule = parts.LinearSchedule(begin_t=5, decay_steps=7, begin_value=1.0, end_value=0.3)
for step in range(20):
val = schedule(step)
if step <= 5:
self.assertE... | the_stack_v2_python_sparse | dqn_zoo/parts_test.py | jinghanY/dqn_zoo | train | 0 | |
43d4b7b7ffb85ed309077166842d47c14b6fdbad | [
"sess = super().create_session(user_id)\nif sess is None:\n return None\nUserSession(user_id=user_id, session_id=sess).save()\nreturn sess",
"if session_id is None:\n return None\nsession_dictionary = None\nif session_id not in SessionAuth.user_id_by_session_id.keys():\n sessData = UserSession.search({'s... | <|body_start_0|>
sess = super().create_session(user_id)
if sess is None:
return None
UserSession(user_id=user_id, session_id=sess).save()
return sess
<|end_body_0|>
<|body_start_1|>
if session_id is None:
return None
session_dictionary = None
... | The session auth class with expiration | SessionDBAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionDBAuth:
"""The session auth class with expiration"""
def create_session(self, user_id=None):
"""create a new session for a user overloaded"""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""get the user id for a session overloaded"""
... | stack_v2_sparse_classes_36k_train_003157 | 2,111 | no_license | [
{
"docstring": "create a new session for a user overloaded",
"name": "create_session",
"signature": "def create_session(self, user_id=None)"
},
{
"docstring": "get the user id for a session overloaded",
"name": "user_id_for_session_id",
"signature": "def user_id_for_session_id(self, sess... | 3 | stack_v2_sparse_classes_30k_train_004733 | Implement the Python class `SessionDBAuth` described below.
Class description:
The session auth class with expiration
Method signatures and docstrings:
- def create_session(self, user_id=None): create a new session for a user overloaded
- def user_id_for_session_id(self, session_id=None): get the user id for a sessio... | Implement the Python class `SessionDBAuth` described below.
Class description:
The session auth class with expiration
Method signatures and docstrings:
- def create_session(self, user_id=None): create a new session for a user overloaded
- def user_id_for_session_id(self, session_id=None): get the user id for a sessio... | 231a975bbaa60233e5e5260d91c968e865bb85a7 | <|skeleton|>
class SessionDBAuth:
"""The session auth class with expiration"""
def create_session(self, user_id=None):
"""create a new session for a user overloaded"""
<|body_0|>
def user_id_for_session_id(self, session_id=None):
"""get the user id for a session overloaded"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionDBAuth:
"""The session auth class with expiration"""
def create_session(self, user_id=None):
"""create a new session for a user overloaded"""
sess = super().create_session(user_id)
if sess is None:
return None
UserSession(user_id=user_id, session_id=sess... | the_stack_v2_python_sparse | 0x07-Session_authentication/api/v1/auth/session_db_auth.py | maybe-william/holbertonschool-web_back_end | train | 0 |
a8daab6463f2cf3d68bec7af90919ab8bc9dfd8c | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the MutateJobService. Service to manage mutate jobs. | MutateJobServiceServicer | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MutateJobServiceServicer:
"""Proto file describing the MutateJobService. Service to manage mutate jobs."""
def CreateMutateJob(self, request, context):
"""Creates a mutate job."""
<|body_0|>
def GetMutateJob(self, request, context):
"""Returns the mutate job."""
... | stack_v2_sparse_classes_36k_train_003158 | 6,874 | permissive | [
{
"docstring": "Creates a mutate job.",
"name": "CreateMutateJob",
"signature": "def CreateMutateJob(self, request, context)"
},
{
"docstring": "Returns the mutate job.",
"name": "GetMutateJob",
"signature": "def GetMutateJob(self, request, context)"
},
{
"docstring": "Returns th... | 5 | null | Implement the Python class `MutateJobServiceServicer` described below.
Class description:
Proto file describing the MutateJobService. Service to manage mutate jobs.
Method signatures and docstrings:
- def CreateMutateJob(self, request, context): Creates a mutate job.
- def GetMutateJob(self, request, context): Return... | Implement the Python class `MutateJobServiceServicer` described below.
Class description:
Proto file describing the MutateJobService. Service to manage mutate jobs.
Method signatures and docstrings:
- def CreateMutateJob(self, request, context): Creates a mutate job.
- def GetMutateJob(self, request, context): Return... | 0fc8a7dbf31d9e8e2a4364df93bec5f6b7edd50a | <|skeleton|>
class MutateJobServiceServicer:
"""Proto file describing the MutateJobService. Service to manage mutate jobs."""
def CreateMutateJob(self, request, context):
"""Creates a mutate job."""
<|body_0|>
def GetMutateJob(self, request, context):
"""Returns the mutate job."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MutateJobServiceServicer:
"""Proto file describing the MutateJobService. Service to manage mutate jobs."""
def CreateMutateJob(self, request, context):
"""Creates a mutate job."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | google/ads/google_ads/v1/proto/services/mutate_job_service_pb2_grpc.py | juanmacugat/google-ads-python | train | 1 |
f3cd108c4ee31b5498859b931cd6bc67e4d4b418 | [
"assert isinstance(p1, Point), 'p1=%r is not a point' % p1\nassert isinstance(p2, Point), 'p2=%r is not a point' % p2\nself.p1 = p1\nself.p2 = p2\nself.x_min = min(p1.x, p2.x)\nself.y_min = min(p1.y, p2.x)\nself.x_max = max(p1.x, p2.x)\nself.y_max = max(p1.y, p2.x)",
"assert isinstance(p, Point), 'p=%r is not a p... | <|body_start_0|>
assert isinstance(p1, Point), 'p1=%r is not a point' % p1
assert isinstance(p2, Point), 'p2=%r is not a point' % p2
self.p1 = p1
self.p2 = p2
self.x_min = min(p1.x, p2.x)
self.y_min = min(p1.y, p2.x)
self.x_max = max(p1.x, p2.x)
self.y_max... | A rectangle identified by two points. | Rectangle | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
<|body_0|>
def get_outcode(self, p):
"""Get the outcode for a point p. The values are (left, right, b... | stack_v2_sparse_classes_36k_train_003159 | 5,195 | permissive | [
{
"docstring": "Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point",
"name": "__init__",
"signature": "def __init__(self, p1, p2)"
},
{
"docstring": "Get the outcode for a point p. The values are (left, right, bottom, top). Parameters ---------- p : Point Returns ------- li... | 3 | stack_v2_sparse_classes_30k_train_016890 | Implement the Python class `Rectangle` described below.
Class description:
A rectangle identified by two points.
Method signatures and docstrings:
- def __init__(self, p1, p2): Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point
- def get_outcode(self, p): Get the outcode for a point p. The value... | Implement the Python class `Rectangle` described below.
Class description:
A rectangle identified by two points.
Method signatures and docstrings:
- def __init__(self, p1, p2): Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point
- def get_outcode(self, p): Get the outcode for a point p. The value... | 1c20f57185e6324aa840ccff98e69764b4213131 | <|skeleton|>
class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
<|body_0|>
def get_outcode(self, p):
"""Get the outcode for a point p. The values are (left, right, b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rectangle:
"""A rectangle identified by two points."""
def __init__(self, p1, p2):
"""Constructor for a rectangle. Parameters ---------- p1 : Point p2 : Point"""
assert isinstance(p1, Point), 'p1=%r is not a point' % p1
assert isinstance(p2, Point), 'p2=%r is not a point' % p2
... | the_stack_v2_python_sparse | alpha-clipping/main.py | PepSalehi/algorithms | train | 0 |
3a08ffd697eafdb2bef5e92107b2fa0cc2702de9 | [
"inf = int(1000000000.0)\nminprice = inf\nmaxprofit = 0\nfor price in prices:\n maxprofit = max(price - minprice, maxprofit)\n minprice = min(price, minprice)\nreturn maxprofit",
"if len(prices) < 2:\n return 0\ndp = [[0 for _ in range(2)] for _ in range(len(prices))]\ndp[0][0] = 0\ndp[0][1] = -prices[0]... | <|body_start_0|>
inf = int(1000000000.0)
minprice = inf
maxprofit = 0
for price in prices:
maxprofit = max(price - minprice, maxprofit)
minprice = min(price, minprice)
return maxprofit
<|end_body_0|>
<|body_start_1|>
if len(prices) < 2:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""动态规划写法: 定义动态方程为dp[i][j] i -> 第i天, j 持股状态 定义j 为 0、1两种状态,0未持股,1持股: 0 状态转移: 前一天未持股,当前天未持股 前一天持股,当... | stack_v2_sparse_classes_36k_train_003160 | 2,777 | no_license | [
{
"docstring": "暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:",
"name": "maxProfit",
"signature": "def maxProfit(self, prices: List[int]) -> int"
},
{
"docstring": "动态规划写法: 定义动态方程为dp[i][j] i -> 第i天, j 持股状态 定义j 为 0、1两种状态,0未持股,1持股: 0 状态转移: 前一天未持股,当前天未持股 前一天持股,当前天未持股 dp[i][0] = max(dp[i - 1][0], ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:
- def maxProfit1(self, prices: List[int]) -> int: 动态规划写法: 定义动态方程为dp[i][j] i -> 第i天,... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit(self, prices: List[int]) -> int: 暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:
- def maxProfit1(self, prices: List[int]) -> int: 动态规划写法: 定义动态方程为dp[i][j] i -> 第i天,... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:"""
<|body_0|>
def maxProfit1(self, prices: List[int]) -> int:
"""动态规划写法: 定义动态方程为dp[i][j] i -> 第i天, j 持股状态 定义j 为 0、1两种状态,0未持股,1持股: 0 状态转移: 前一天未持股,当前天未持股 前一天持股,当... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""暴力法,时间复杂度O(N),空间复杂度O(1) :param prices: :return:"""
inf = int(1000000000.0)
minprice = inf
maxprofit = 0
for price in prices:
maxprofit = max(price - minprice, maxprofit)
minprice = min(p... | the_stack_v2_python_sparse | Interview_preparation/tencent/MaxProfit.py | yinhuax/leet_code | train | 0 | |
b44ccdcceb1696548fb38c2b22c31d8728641474 | [
"main_root = os.environ['MAIN_ROOT']\ndict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')\nhmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8')\nuser_dict_path = os.path.join(main_root, 'tools/cppjieba/dict/user.dict.utf8')\nidf_path = os.path.join(main_root, 'tools/cppjie... | <|body_start_0|>
main_root = os.environ['MAIN_ROOT']
dict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')
hmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8')
user_dict_path = os.path.join(main_root, 'tools/cppjieba/dict/user.dict.utf8')
... | jieba op test | JiebaOpsTest | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
<|body_0|>
def build_op_no_file(self, sentence):
"""build graph"""
<|body_1|>
def test_jieba_cut_op_use_file(self):
"""test jieba"""
<|body_2|>... | stack_v2_sparse_classes_36k_train_003161 | 5,875 | permissive | [
{
"docstring": "build graph",
"name": "build_op_use_file",
"signature": "def build_op_use_file(self, sentence)"
},
{
"docstring": "build graph",
"name": "build_op_no_file",
"signature": "def build_op_no_file(self, sentence)"
},
{
"docstring": "test jieba",
"name": "test_jieba... | 4 | stack_v2_sparse_classes_30k_train_015159 | Implement the Python class `JiebaOpsTest` described below.
Class description:
jieba op test
Method signatures and docstrings:
- def build_op_use_file(self, sentence): build graph
- def build_op_no_file(self, sentence): build graph
- def test_jieba_cut_op_use_file(self): test jieba
- def test_jieba_cut_op_no_file(self... | Implement the Python class `JiebaOpsTest` described below.
Class description:
jieba op test
Method signatures and docstrings:
- def build_op_use_file(self, sentence): build graph
- def build_op_no_file(self, sentence): build graph
- def test_jieba_cut_op_use_file(self): test jieba
- def test_jieba_cut_op_no_file(self... | 7eb4e3be578a680737616efff6858d280595ff48 | <|skeleton|>
class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
<|body_0|>
def build_op_no_file(self, sentence):
"""build graph"""
<|body_1|>
def test_jieba_cut_op_use_file(self):
"""test jieba"""
<|body_2|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JiebaOpsTest:
"""jieba op test"""
def build_op_use_file(self, sentence):
"""build graph"""
main_root = os.environ['MAIN_ROOT']
dict_path = os.path.join(main_root, 'tools/cppjieba/dict/jieba.dict.utf8')
hmm_path = os.path.join(main_root, 'tools/cppjieba/dict/hmm_model.utf8'... | the_stack_v2_python_sparse | delta/layers/ops/kernels/jieba_op_test.py | luffywalf/delta | train | 1 |
52199d5344bb74983cb53ee0493b9ae79490b3d4 | [
"username = request.user.get_username()\nserializer = ViewSerializer(username=username, repo_base=repo_base)\nview_info = serializer.describe_view(repo_name, view, detail=False)\nreturn Response(view_info, status=status.HTTP_200_OK)",
"username = request.user.get_username()\nserializer = ViewSerializer(username=u... | <|body_start_0|>
username = request.user.get_username()
serializer = ViewSerializer(username=username, repo_base=repo_base)
view_info = serializer.describe_view(repo_name, view, detail=False)
return Response(view_info, status=status.HTTP_200_OK)
<|end_body_0|>
<|body_start_1|>
u... | View | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
def get(self, request, repo_base, repo_name, view, format=None):
"""See the schema of a single view This endpoint does not throw an error if the table does not exist."""
<|body_0|>
def delete(self, request, repo_base, repo_name, view, format=None):
"""Delete a ... | stack_v2_sparse_classes_36k_train_003162 | 31,465 | permissive | [
{
"docstring": "See the schema of a single view This endpoint does not throw an error if the table does not exist.",
"name": "get",
"signature": "def get(self, request, repo_base, repo_name, view, format=None)"
},
{
"docstring": "Delete a single view",
"name": "delete",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_011040 | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, view, format=None): See the schema of a single view This endpoint does not throw an error if the table does not exist.
- def delete(self, req... | Implement the Python class `View` described below.
Class description:
Implement the View class.
Method signatures and docstrings:
- def get(self, request, repo_base, repo_name, view, format=None): See the schema of a single view This endpoint does not throw an error if the table does not exist.
- def delete(self, req... | f066b472c2b66cc3b868bbe433aed2d4557aea32 | <|skeleton|>
class View:
def get(self, request, repo_base, repo_name, view, format=None):
"""See the schema of a single view This endpoint does not throw an error if the table does not exist."""
<|body_0|>
def delete(self, request, repo_base, repo_name, view, format=None):
"""Delete a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
def get(self, request, repo_base, repo_name, view, format=None):
"""See the schema of a single view This endpoint does not throw an error if the table does not exist."""
username = request.user.get_username()
serializer = ViewSerializer(username=username, repo_base=repo_base)
... | the_stack_v2_python_sparse | src/api/views.py | datahuborg/datahub | train | 199 | |
1b536b4f65c18d468203f4d32a60e627cae99435 | [
"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... | Service to manage customer-manager links. | CustomerManagerLinkServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
<|body_0|>
def MutateCustomerManagerLink(self, request, context):
... | stack_v2_sparse_classes_36k_train_003163 | 5,031 | permissive | [
{
"docstring": "Returns the requested CustomerManagerLink in full detail.",
"name": "GetCustomerManagerLink",
"signature": "def GetCustomerManagerLink(self, request, context)"
},
{
"docstring": "Creates or updates customer manager links. Operation statuses are returned.",
"name": "MutateCust... | 3 | null | Implement the Python class `CustomerManagerLinkServiceServicer` described below.
Class description:
Service to manage customer-manager links.
Method signatures and docstrings:
- def GetCustomerManagerLink(self, request, context): Returns the requested CustomerManagerLink in full detail.
- def MutateCustomerManagerLin... | Implement the Python class `CustomerManagerLinkServiceServicer` described below.
Class description:
Service to manage customer-manager links.
Method signatures and docstrings:
- def GetCustomerManagerLink(self, request, context): Returns the requested CustomerManagerLink in full detail.
- def MutateCustomerManagerLin... | a5b6cede64f4d9912ae6ad26927a54e40448c9fe | <|skeleton|>
class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
<|body_0|>
def MutateCustomerManagerLink(self, request, context):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomerManagerLinkServiceServicer:
"""Service to manage customer-manager links."""
def GetCustomerManagerLink(self, request, context):
"""Returns the requested CustomerManagerLink in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not i... | the_stack_v2_python_sparse | google/ads/google_ads/v3/proto/services/customer_manager_link_service_pb2_grpc.py | fiboknacky/google-ads-python | train | 0 |
2a92cbc25f23e6c067314cdb56f8f6d78bbc9805 | [
"Factory.subscribe('Hugo', _Dummy0)\nFactory.subscribe('Paco', _Dummy1)\nFactory.subscribe('Luis', _Dummy2)\nself.assertTrue(type(Factory.incept('Hugo')) == _Dummy0)\nself.assertTrue(type(Factory.incept('Paco')) == _Dummy1)\nself.assertTrue(type(Factory.incept('Luis')) == _Dummy2)\nself.assertFalse(type(Factory.inc... | <|body_start_0|>
Factory.subscribe('Hugo', _Dummy0)
Factory.subscribe('Paco', _Dummy1)
Factory.subscribe('Luis', _Dummy2)
self.assertTrue(type(Factory.incept('Hugo')) == _Dummy0)
self.assertTrue(type(Factory.incept('Paco')) == _Dummy1)
self.assertTrue(type(Factory.incept(... | TestFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestFactory:
def test_correct_type(self):
"""Ensures that the right instance type has been fetched from factory"""
<|body_0|>
def test_tuple_as_index(self):
"""Warranties that any hashable object features a usage as an slot index"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_003164 | 2,420 | no_license | [
{
"docstring": "Ensures that the right instance type has been fetched from factory",
"name": "test_correct_type",
"signature": "def test_correct_type(self)"
},
{
"docstring": "Warranties that any hashable object features a usage as an slot index",
"name": "test_tuple_as_index",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_009694 | Implement the Python class `TestFactory` described below.
Class description:
Implement the TestFactory class.
Method signatures and docstrings:
- def test_correct_type(self): Ensures that the right instance type has been fetched from factory
- def test_tuple_as_index(self): Warranties that any hashable object feature... | Implement the Python class `TestFactory` described below.
Class description:
Implement the TestFactory class.
Method signatures and docstrings:
- def test_correct_type(self): Ensures that the right instance type has been fetched from factory
- def test_tuple_as_index(self): Warranties that any hashable object feature... | 527231a4a2747ffc87ed86299cc02b8361d49c9c | <|skeleton|>
class TestFactory:
def test_correct_type(self):
"""Ensures that the right instance type has been fetched from factory"""
<|body_0|>
def test_tuple_as_index(self):
"""Warranties that any hashable object features a usage as an slot index"""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestFactory:
def test_correct_type(self):
"""Ensures that the right instance type has been fetched from factory"""
Factory.subscribe('Hugo', _Dummy0)
Factory.subscribe('Paco', _Dummy1)
Factory.subscribe('Luis', _Dummy2)
self.assertTrue(type(Factory.incept('Hugo')) == _D... | the_stack_v2_python_sparse | obras/service/quality/test_dal_afactory.py | pianodaemon/SJO | train | 0 | |
39017c91fcb49dc9a62c590010bfd0dd887e318e | [
"super(ProxyNCALoss, self).__init__()\nself.num_proxies = num_proxies\nself.embedding_dim = embedding_dim\nself.PROXIES = torch.nn.Parameter(torch.randn(num_proxies, self.embedding_dim) / 8)\nself.all_classes = torch.arange(num_proxies)",
"batch = 3 * torch.nn.functional.normalize(batch, dim=1)\nPROXIES = 3 * tor... | <|body_start_0|>
super(ProxyNCALoss, self).__init__()
self.num_proxies = num_proxies
self.embedding_dim = embedding_dim
self.PROXIES = torch.nn.Parameter(torch.randn(num_proxies, self.embedding_dim) / 8)
self.all_classes = torch.arange(num_proxies)
<|end_body_0|>
<|body_start_1|... | ProxyNCALoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProxyNCALoss:
def __init__(self, num_proxies, embedding_dim):
"""Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of proxies to use to estimate data groups. Usually set to number of classes. embedding_dim: int, Required t... | stack_v2_sparse_classes_36k_train_003165 | 29,027 | no_license | [
{
"docstring": "Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of proxies to use to estimate data groups. Usually set to number of classes. embedding_dim: int, Required to generate initial proxies which are the same size as the actual data emb... | 2 | stack_v2_sparse_classes_30k_train_020971 | Implement the Python class `ProxyNCALoss` described below.
Class description:
Implement the ProxyNCALoss class.
Method signatures and docstrings:
- def __init__(self, num_proxies, embedding_dim): Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of pro... | Implement the Python class `ProxyNCALoss` described below.
Class description:
Implement the ProxyNCALoss class.
Method signatures and docstrings:
- def __init__(self, num_proxies, embedding_dim): Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of pro... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ProxyNCALoss:
def __init__(self, num_proxies, embedding_dim):
"""Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of proxies to use to estimate data groups. Usually set to number of classes. embedding_dim: int, Required t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProxyNCALoss:
def __init__(self, num_proxies, embedding_dim):
"""Basic ProxyNCA Loss as proposed in 'No Fuss Distance Metric Learning using Proxies'. Args: num_proxies: int, number of proxies to use to estimate data groups. Usually set to number of classes. embedding_dim: int, Required to generate ini... | the_stack_v2_python_sparse | generated/test_Confusezius_Deep_Metric_Learning_Baselines.py | jansel/pytorch-jit-paritybench | train | 35 | |
695cee99cf12c7c750bdd02cbb215e58afb2e2f2 | [
"super().__init__()\nself.conv1 = conv1x1(inplanes, planes, n_dim=n_dim)\nself.bn1 = NormNdTorch(norm_layer, n_dim, planes)\nself.conv2 = conv3x3(planes, planes, stride, n_dim=n_dim)\nself.bn2 = NormNdTorch(norm_layer, n_dim, planes)\nself.conv3 = conv1x1(planes, planes * self.expansion, n_dim=n_dim)\nself.bn3 = No... | <|body_start_0|>
super().__init__()
self.conv1 = conv1x1(inplanes, planes, n_dim=n_dim)
self.bn1 = NormNdTorch(norm_layer, n_dim, planes)
self.conv2 = conv3x3(planes, planes, stride, n_dim=n_dim)
self.bn2 = NormNdTorch(norm_layer, n_dim, planes)
self.conv3 = conv1x1(plane... | SEBottleneckTorch | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SEBottleneckTorch:
def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16):
"""Squeeze and Excitation Bottleneck ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stri... | stack_v2_sparse_classes_36k_train_003166 | 8,979 | permissive | [
{
"docstring": "Squeeze and Excitation Bottleneck ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : int or tuple stride of first convolution downsample : nn.Module downsampling in residual path norm_layer : str type of normalisation ... | 2 | stack_v2_sparse_classes_30k_train_019984 | Implement the Python class `SEBottleneckTorch` described below.
Class description:
Implement the SEBottleneckTorch class.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): Squeeze and Excitation Bottleneck ResNet block Param... | Implement the Python class `SEBottleneckTorch` described below.
Class description:
Implement the SEBottleneckTorch class.
Method signatures and docstrings:
- def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16): Squeeze and Excitation Bottleneck ResNet block Param... | d944aa67d319bd63a2add5cb89e8308413943de6 | <|skeleton|>
class SEBottleneckTorch:
def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16):
"""Squeeze and Excitation Bottleneck ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SEBottleneckTorch:
def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer='Batch', n_dim=2, reduction=16):
"""Squeeze and Excitation Bottleneck ResNet block Parameters ---------- inplanes : int number of input channels planes : int number of intermediate channels stride : int or tu... | the_stack_v2_python_sparse | deliravision/torch/models/backbones/seblocks.py | delira-dev/vision_torch | train | 5 | |
5005814530be9ba2733a4cdea4499a2a09ee6907 | [
"self.options = options\nself.queue = Queue()\nsuper(Executer, self).__init__()",
"if self.options.jail_options[ControllerConstants.IS_JAILED]:\n self.options.logger.info('Executing script in chroot jail')\n os.chroot(self.options.jail_options[ControllerConstants.JAIL_DIR])\n os.chdir('/')\n os.setgid... | <|body_start_0|>
self.options = options
self.queue = Queue()
super(Executer, self).__init__()
<|end_body_0|>
<|body_start_1|>
if self.options.jail_options[ControllerConstants.IS_JAILED]:
self.options.logger.info('Executing script in chroot jail')
os.chroot(self.o... | Class for running a Python scripts. | Executer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Executer:
"""Class for running a Python scripts."""
def __init__(self, options):
"""Constructor."""
<|body_0|>
def run(self):
"""Function to run specified command in subprocess."""
<|body_1|>
def run_parent(self):
"""Function to run specified... | stack_v2_sparse_classes_36k_train_003167 | 7,287 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, options)"
},
{
"docstring": "Function to run specified command in subprocess.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Function to run specified command in parent process."... | 3 | stack_v2_sparse_classes_30k_train_007381 | Implement the Python class `Executer` described below.
Class description:
Class for running a Python scripts.
Method signatures and docstrings:
- def __init__(self, options): Constructor.
- def run(self): Function to run specified command in subprocess.
- def run_parent(self): Function to run specified command in par... | Implement the Python class `Executer` described below.
Class description:
Class for running a Python scripts.
Method signatures and docstrings:
- def __init__(self, options): Constructor.
- def run(self): Function to run specified command in subprocess.
- def run_parent(self): Function to run specified command in par... | 4648e48f4e290e5a1e5558acaf05431982acb81a | <|skeleton|>
class Executer:
"""Class for running a Python scripts."""
def __init__(self, options):
"""Constructor."""
<|body_0|>
def run(self):
"""Function to run specified command in subprocess."""
<|body_1|>
def run_parent(self):
"""Function to run specified... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Executer:
"""Class for running a Python scripts."""
def __init__(self, options):
"""Constructor."""
self.options = options
self.queue = Queue()
super(Executer, self).__init__()
def run(self):
"""Function to run specified command in subprocess."""
if se... | the_stack_v2_python_sparse | activities_python/actions/action_run_script.py | mikhail-rozhkov/cicso_lab | train | 0 |
e7c5b32e6c0b91e533bf934d84a897e199f16e0c | [
"self.shutdown()\nif self.state != PMAppType.HALTED:\n time.sleep(2)\n os.kill(self.processid, signal.SIGTERM)",
"stopcommand = os.path.join(pylabs.q.dirs.baseDir, 'control', self.name, 'stop.')\nif pylabs.q.platform.isUnix():\n stopcommand += 'py'\nelif pylabs.q.platform.isWindows():\n stopcommand +=... | <|body_start_0|>
self.shutdown()
if self.state != PMAppType.HALTED:
time.sleep(2)
os.kill(self.processid, signal.SIGTERM)
<|end_body_0|>
<|body_start_1|>
stopcommand = os.path.join(pylabs.q.dirs.baseDir, 'control', self.name, 'stop.')
if pylabs.q.platform.isUnix(... | PMApp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
<|body_0|>
def shutdown(self):
"""Attempts to stop ... | stack_v2_sparse_classes_36k_train_003168 | 3,345 | no_license | [
{
"docstring": "Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way.",
"name": "kill",
"signature": "def kill(self)"
},
{
"docstring": "Attempts to stop a pylabs ... | 3 | stack_v2_sparse_classes_30k_train_003069 | Implement the Python class `PMApp` described below.
Class description:
Implement the PMApp class.
Method signatures and docstrings:
- def kill(self): Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is ki... | Implement the Python class `PMApp` described below.
Class description:
Implement the PMApp class.
Method signatures and docstrings:
- def kill(self): Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is ki... | 53d349fa6bee0ccead29afd6676979b44c109a61 | <|skeleton|>
class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
<|body_0|>
def shutdown(self):
"""Attempts to stop ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PMApp:
def kill(self):
"""Attempts to stop a pylabs application gracefully Attempts to stop a pylabs application in a nice way, waits for two seconds. If the attempt fails, the application is killed the hard way."""
self.shutdown()
if self.state != PMAppType.HALTED:
time.sl... | the_stack_v2_python_sparse | core/apps/App.py | racktivity/ext-pylabs-core | train | 0 | |
cf3b386e69a352230fec7e5af27d9b4262f68c72 | [
"self.shape_predictor_path = shape_predictor_path\nself.predictor = dlib.shape_predictor(self.shape_predictor_path)\nself.detector = dlib.get_frontal_face_detector()\nself.face_aligner = FaceAligner(self.predictor, desiredFaceWidth=256)",
"rectangles = self.detector(image, 1)\nif len(rectangles) == 0:\n logger... | <|body_start_0|>
self.shape_predictor_path = shape_predictor_path
self.predictor = dlib.shape_predictor(self.shape_predictor_path)
self.detector = dlib.get_frontal_face_detector()
self.face_aligner = FaceAligner(self.predictor, desiredFaceWidth=256)
<|end_body_0|>
<|body_start_1|>
... | The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image. | FaceDetector | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceDetector:
"""The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image."""
def __init__(self, shape_predictor_path):
"""Initialise Face Detector Manager. :param shape_predictor_path (s... | stack_v2_sparse_classes_36k_train_003169 | 4,580 | permissive | [
{
"docstring": "Initialise Face Detector Manager. :param shape_predictor_path (str): Describes the path to the Shape Predictor trained data.",
"name": "__init__",
"signature": "def __init__(self, shape_predictor_path)"
},
{
"docstring": "This function detects the face in the image passed. By mak... | 4 | stack_v2_sparse_classes_30k_train_012076 | Implement the Python class `FaceDetector` described below.
Class description:
The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image.
Method signatures and docstrings:
- def __init__(self, shape_predictor_path): Initial... | Implement the Python class `FaceDetector` described below.
Class description:
The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image.
Method signatures and docstrings:
- def __init__(self, shape_predictor_path): Initial... | d62917262080f09d7c9e7262f507e2c1482d7c56 | <|skeleton|>
class FaceDetector:
"""The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image."""
def __init__(self, shape_predictor_path):
"""Initialise Face Detector Manager. :param shape_predictor_path (s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaceDetector:
"""The FaceDetector class is responsible for: 1. Detecting the face. 2. Extracting a face from an image. 3. Applying blurring on a detected face in an image."""
def __init__(self, shape_predictor_path):
"""Initialise Face Detector Manager. :param shape_predictor_path (str): Describe... | the_stack_v2_python_sparse | src/main/python/hutts_verification/image_preprocessing/face_manager.py | javaTheHutts/Java-the-Hutts | train | 2 |
1da40abcc7caf561ac2a64892193e910f6916ceb | [
"hl = md5()\nhl.update(msg.encode('utf-8'))\nreturn hl.hexdigest()",
"sh = sha1()\nsh.update(msg.encode('utf-8'))\nreturn sh.hexdigest()",
"sh = SHA256.new()\nsh.update(msg.encode('utf-8'))\nreturn sh.hexdigest()",
"de = DES.new(key, DES.MODE_ECB)\nmss = msg + (8 - len(msg) % 8) * '='\ntext = de.encrypt(mss.e... | <|body_start_0|>
hl = md5()
hl.update(msg.encode('utf-8'))
return hl.hexdigest()
<|end_body_0|>
<|body_start_1|>
sh = sha1()
sh.update(msg.encode('utf-8'))
return sh.hexdigest()
<|end_body_1|>
<|body_start_2|>
sh = SHA256.new()
sh.update(msg.encode('utf-... | MyHash | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyHash:
def my_md5(self, msg):
"""md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
<|body_0|>
def my_sha1(self, msg):
"""sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
<|body_1|>
def my_sha256(self, msg):
"""sha256 算法加密 :param msg: 需加密的字符串 :retu... | stack_v2_sparse_classes_36k_train_003170 | 2,376 | no_license | [
{
"docstring": "md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符",
"name": "my_md5",
"signature": "def my_md5(self, msg)"
},
{
"docstring": "sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符",
"name": "my_sha1",
"signature": "def my_sha1(self, msg)"
},
{
"docstring": "sha256 算法加密 :param ... | 6 | stack_v2_sparse_classes_30k_test_000132 | Implement the Python class `MyHash` described below.
Class description:
Implement the MyHash class.
Method signatures and docstrings:
- def my_md5(self, msg): md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符
- def my_sha1(self, msg): sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符
- def my_sha256(self, msg): sha256 算法加密 :p... | Implement the Python class `MyHash` described below.
Class description:
Implement the MyHash class.
Method signatures and docstrings:
- def my_md5(self, msg): md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符
- def my_sha1(self, msg): sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符
- def my_sha256(self, msg): sha256 算法加密 :p... | 8dd873977444818d0515d51d6552db3e0c318bb2 | <|skeleton|>
class MyHash:
def my_md5(self, msg):
"""md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
<|body_0|>
def my_sha1(self, msg):
"""sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
<|body_1|>
def my_sha256(self, msg):
"""sha256 算法加密 :param msg: 需加密的字符串 :retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyHash:
def my_md5(self, msg):
"""md5 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
hl = md5()
hl.update(msg.encode('utf-8'))
return hl.hexdigest()
def my_sha1(self, msg):
"""sha1 算法加密 :param msg: 需加密的字符串 :return: 加密后的字符"""
sh = sha1()
sh.update(msg.e... | the_stack_v2_python_sparse | Common/Hash.py | chenanming/API_Auto_Test | train | 0 | |
344ec2bed37c4f8b21332c7078f4da2649f2c825 | [
"super(ConvGRU, self).__init__()\nself.input_size = input_size\nif type(hidden_sizes) != list:\n self.hidden_sizes = [hidden_sizes] * n_layers\nelse:\n assert len(hidden_sizes) == n_layers, '`hidden_sizes` must have the same length as n_layers'\n self.hidden_sizes = hidden_sizes\nif type(kernel_sizes) != l... | <|body_start_0|>
super(ConvGRU, self).__init__()
self.input_size = input_size
if type(hidden_sizes) != list:
self.hidden_sizes = [hidden_sizes] * n_layers
else:
assert len(hidden_sizes) == n_layers, '`hidden_sizes` must have the same length as n_layers'
... | ConvGRU | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : intege... | stack_v2_sparse_classes_36k_train_003171 | 4,783 | permissive | [
{
"docstring": "Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : integer or list. depth dimensions of hidden state. if integer, the same hidden size is used for ... | 2 | stack_v2_sparse_classes_30k_train_018219 | Implement the Python class `ConvGRU` described below.
Class description:
Implement the ConvGRU class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers): Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Par... | Implement the Python class `ConvGRU` described below.
Class description:
Implement the ConvGRU class.
Method signatures and docstrings:
- def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers): Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Par... | 3efa944031e65d4a9fc6dee27381e73e446bb16d | <|skeleton|>
class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : intege... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvGRU:
def __init__(self, input_size, hidden_sizes, kernel_sizes, n_layers):
"""Generates a multi-layer convolutional GRU. Preserves spatial dimensions across cells, only altering depth. Parameters ---------- input_size : integer. depth dimension of input tensors. hidden_sizes : integer or list. dep... | the_stack_v2_python_sparse | gen_models/convgru.py | KamyarGh/rl_swiss | train | 61 | |
8d8c10531fad5f016f77fbd84fee07e3127c644b | [
"params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}\nparams.update(kwargs)\nreturn self.api._get('emails/get_or_create', params=params)",
"params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}\nparams.update(kwargs)\nreturn self.api._get('emails/disable', params=params)"
] | <|body_start_0|>
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params.update(kwargs)
return self.api._get('emails/get_or_create', params=params)
<|end_body_0|>
<|body_start_1|>
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params... | EmailsManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
<|body_0|>
def disable(self, obj_type, obj_id, **kwargs):
"""Disable email to an object."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
para... | stack_v2_sparse_classes_36k_train_003172 | 668 | permissive | [
{
"docstring": "Get or create email to an object.",
"name": "get_or_create",
"signature": "def get_or_create(self, obj_type, obj_id, **kwargs)"
},
{
"docstring": "Disable email to an object.",
"name": "disable",
"signature": "def disable(self, obj_type, obj_id, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000820 | Implement the Python class `EmailsManager` described below.
Class description:
Implement the EmailsManager class.
Method signatures and docstrings:
- def get_or_create(self, obj_type, obj_id, **kwargs): Get or create email to an object.
- def disable(self, obj_type, obj_id, **kwargs): Disable email to an object. | Implement the Python class `EmailsManager` described below.
Class description:
Implement the EmailsManager class.
Method signatures and docstrings:
- def get_or_create(self, obj_type, obj_id, **kwargs): Get or create email to an object.
- def disable(self, obj_type, obj_id, **kwargs): Disable email to an object.
<|s... | 7b85de81619146d3d54fececda068010ae73775b | <|skeleton|>
class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
<|body_0|>
def disable(self, obj_type, obj_id, **kwargs):
"""Disable email to an object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailsManager:
def get_or_create(self, obj_type, obj_id, **kwargs):
"""Get or create email to an object."""
params = {'token': self.token, 'obj_type': obj_type, 'obj_id': obj_id}
params.update(kwargs)
return self.api._get('emails/get_or_create', params=params)
def disable(... | the_stack_v2_python_sparse | todoist/managers/emails.py | Doist/todoist-python | train | 627 | |
5a888214d751de293e46fee6c50986420e97b6ab | [
"query = 'SELECT details, UNIX_TIMESTAMP(timestamp)\\n FROM api_audit_entry\\n FORCE INDEX (api_audit_entry_by_username_timestamp)\\n {WHERE_PLACEHOLDER}\\n ORDER BY timestamp ASC\\n '\nconditions = []\nvalues = []\nwhere = ''\nif username is not None:\n conditions.append('username... | <|body_start_0|>
query = 'SELECT details, UNIX_TIMESTAMP(timestamp)\n FROM api_audit_entry\n FORCE INDEX (api_audit_entry_by_username_timestamp)\n {WHERE_PLACEHOLDER}\n ORDER BY timestamp ASC\n '
conditions = []
values = []
where = ''
if username is... | MySQLDB mixin for event handling. | MySQLDBEventMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MySQLDBEventMixin:
"""MySQLDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None):
"""Returns audit entries stored in the database."""
<|body_0|>
def CountAPIAuditEntries... | stack_v2_sparse_classes_36k_train_003173 | 4,374 | permissive | [
{
"docstring": "Returns audit entries stored in the database.",
"name": "ReadAPIAuditEntries",
"signature": "def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None)"
},
{
"docstring": "Returns audit entry counts grouped by user ... | 3 | stack_v2_sparse_classes_30k_train_008473 | Implement the Python class `MySQLDBEventMixin` described below.
Class description:
MySQLDB mixin for event handling.
Method signatures and docstrings:
- def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): Returns audit entries stored in the data... | Implement the Python class `MySQLDBEventMixin` described below.
Class description:
MySQLDB mixin for event handling.
Method signatures and docstrings:
- def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): Returns audit entries stored in the data... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class MySQLDBEventMixin:
"""MySQLDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None):
"""Returns audit entries stored in the database."""
<|body_0|>
def CountAPIAuditEntries... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MySQLDBEventMixin:
"""MySQLDB mixin for event handling."""
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None):
"""Returns audit entries stored in the database."""
query = 'SELECT details, UNIX_TIMESTAMP(timestamp)\n ... | the_stack_v2_python_sparse | grr/server/grr_response_server/databases/mysql_events.py | google/grr | train | 4,683 |
0e492246018ba3af8b2c25e69a7a1a58b3c2bfca | [
"text = reply_to = None\nchannel = immp.Channel(discord, message.channel.id)\nuser = DiscordUser.from_user(discord, message.author)\nattachments = []\nif message.content:\n text = DiscordRichText.from_message(discord, message)\nif message.reference and (not message.flags.is_crossposted):\n receipt = immp.Rece... | <|body_start_0|>
text = reply_to = None
channel = immp.Channel(discord, message.channel.id)
user = DiscordUser.from_user(discord, message.author)
attachments = []
if message.content:
text = DiscordRichText.from_message(discord, message)
if message.reference an... | Message originating from Discord. | DiscordMessage | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiscordMessage:
"""Message originating from Discord."""
async def from_message(cls, discord, message, edited=False, deleted=False):
"""Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): Related plug instance that provides the event. message (di... | stack_v2_sparse_classes_36k_train_003174 | 31,741 | permissive | [
{
"docstring": "Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): Related plug instance that provides the event. message (discord.Message): Discord message object received from a channel. edited (bool): Whether this message comes from an edit event. deleted (bool): Wheth... | 2 | stack_v2_sparse_classes_30k_train_004630 | Implement the Python class `DiscordMessage` described below.
Class description:
Message originating from Discord.
Method signatures and docstrings:
- async def from_message(cls, discord, message, edited=False, deleted=False): Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): R... | Implement the Python class `DiscordMessage` described below.
Class description:
Message originating from Discord.
Method signatures and docstrings:
- async def from_message(cls, discord, message, edited=False, deleted=False): Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): R... | a7045a8fd4d2e8090fc84e3581f766492ae7f2da | <|skeleton|>
class DiscordMessage:
"""Message originating from Discord."""
async def from_message(cls, discord, message, edited=False, deleted=False):
"""Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): Related plug instance that provides the event. message (di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiscordMessage:
"""Message originating from Discord."""
async def from_message(cls, discord, message, edited=False, deleted=False):
"""Convert a :class:`discord.Message` into a :class:`.Message`. Args: discord (.DiscordPlug): Related plug instance that provides the event. message (discord.Message... | the_stack_v2_python_sparse | immp/plug/discord.py | Terrance/IMMP | train | 12 |
c903894bfabf054e87f326f812ce1d4e31f96b79 | [
"s, stack = ('', deque([root]))\nif root:\n while stack:\n node = stack.popleft()\n if node:\n s += str(node.val) + ','\n stack.append(node.left)\n stack.append(node.right)\n else:\n s += ' ,'\nreturn s[:-1]",
"x = deque(data.split(','))\nv = x.p... | <|body_start_0|>
s, stack = ('', deque([root]))
if root:
while stack:
node = stack.popleft()
if node:
s += str(node.val) + ','
stack.append(node.left)
stack.append(node.right)
else:
... | check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work. | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
"""check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your... | stack_v2_sparse_classes_36k_train_003175 | 1,453 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> T... | Implement the Python class `Codec` described below.
Class description:
check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> T... | 6043134736452a6f4704b62857d0aed2e9571164 | <|skeleton|>
class Codec:
"""check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
"""check out listToTreeNode in @/src/config/treenode.py, which is exactly how deserialize work."""
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
s, stack = ('', deque([root]))
if root:
while stack:
node = st... | the_stack_v2_python_sparse | src/0200-0299/0297.serialize.deserialize.bt.py | gyang274/leetcode | train | 1 |
d45662f4dd4be5a127e11579b8d510877b610a82 | [
"self.step_vector = step\nself.step_time = step_time\nself.ref_timer = None",
"u = np.zeros(shape=dim)\nj = 0\nfor i in range(len(t)):\n if t[i] % self.step_time == 0 and t[i] != 0 and (j + 1 != len(self.step_vector)):\n j += 1\n u[i, :] = self.step_vector[j]\nreturn u"
] | <|body_start_0|>
self.step_vector = step
self.step_time = step_time
self.ref_timer = None
<|end_body_0|>
<|body_start_1|>
u = np.zeros(shape=dim)
j = 0
for i in range(len(t)):
if t[i] % self.step_time == 0 and t[i] != 0 and (j + 1 != len(self.step_vector)):
... | Step | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Step:
def __init__(self, step_time, step=None):
"""Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change"""
<|body_0|>
def out(self, t: any, dim=(None, None)) -> any:
"""Generate a step signal se... | stack_v2_sparse_classes_36k_train_003176 | 8,036 | no_license | [
{
"docstring": "Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change",
"name": "__init__",
"signature": "def __init__(self, step_time, step=None)"
},
{
"docstring": "Generate a step signal sequence Args: dim: Dimension tupl... | 2 | stack_v2_sparse_classes_30k_train_021074 | Implement the Python class `Step` described below.
Class description:
Implement the Step class.
Method signatures and docstrings:
- def __init__(self, step_time, step=None): Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change
- def out(self, t:... | Implement the Python class `Step` described below.
Class description:
Implement the Step class.
Method signatures and docstrings:
- def __init__(self, step_time, step=None): Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change
- def out(self, t:... | cf548475295f25407ba968546c2fc85c26f9343c | <|skeleton|>
class Step:
def __init__(self, step_time, step=None):
"""Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change"""
<|body_0|>
def out(self, t: any, dim=(None, None)) -> any:
"""Generate a step signal se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Step:
def __init__(self, step_time, step=None):
"""Settings for a step sequence Args: step (list): List containing all desired step vales step_time: Time to perform step change"""
self.step_vector = step
self.step_time = step_time
self.ref_timer = None
def out(self, t: any... | the_stack_v2_python_sparse | SourceCode/simulation/signal.py | martin-bachorik/Master-Thesis-Project | train | 0 | |
3bf7035b7a82015b146e64c37e79bf4ba225f90c | [
"self.document_id = document_id\nself.account_id = account_id\nself.title = title\nself.description = description\nself.last_updated = APIHelper.RFC3339DateTime(last_updated) if last_updated else None\nself.deadline = APIHelper.RFC3339DateTime(deadline) if deadline else None\nself.signed_date = APIHelper.RFC3339Dat... | <|body_start_0|>
self.document_id = document_id
self.account_id = account_id
self.title = title
self.description = description
self.last_updated = APIHelper.RFC3339DateTime(last_updated) if last_updated else None
self.deadline = APIHelper.RFC3339DateTime(deadline) if dead... | Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (string): Document description last_updated (datetime): When was the document last upda... | DocumentSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DocumentSummary:
"""Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (string): Document description last_updated ... | stack_v2_sparse_classes_36k_train_003177 | 6,958 | permissive | [
{
"docstring": "Constructor for the DocumentSummary class",
"name": "__init__",
"signature": "def __init__(self, document_id=None, account_id=None, title=None, description=None, last_updated=None, deadline=None, signed_date=None, status=None, external_id=None, document_signatures=None, required_signatur... | 2 | stack_v2_sparse_classes_30k_train_003679 | Implement the Python class `DocumentSummary` described below.
Class description:
Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (stri... | Implement the Python class `DocumentSummary` described below.
Class description:
Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (stri... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class DocumentSummary:
"""Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (string): Document description last_updated ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DocumentSummary:
"""Implementation of the 'DocumentSummary' model. A summary containing core information about a document Attributes: document_id (uuid|string): Document id account_id (uuid|string): Account id title (string): Document title description (string): Document description last_updated (datetime): W... | the_stack_v2_python_sparse | idfy_rest_client/models/document_summary.py | dealflowteam/Idfy | train | 0 |
21b5ca12c811872e34248dc43f74403446b30991 | [
"date_by_year = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}\nyear, month, date = [int(x) for x in date.split('-')]\ndates = 0\nif self.is_leap(year):\n date_by_year[2] += 1\nfor key in range(1, month):\n dates += date_by_year[key]\nreturn dates + date",
"if year %... | <|body_start_0|>
date_by_year = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
year, month, date = [int(x) for x in date.split('-')]
dates = 0
if self.is_leap(year):
date_by_year[2] += 1
for key in range(1, month):
... | Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date ... | stack_v2_sparse_classes_36k_train_003178 | 1,914 | no_license | [
{
"docstring": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. Example 1: Input: date = \"2019-01-09\" Output: 9 Explanation: Given date is the 9th day of the year in 2019. Example 2: Input: date = \"2019-02-10\" Output: 41 Example 3: Input... | 2 | stack_v2_sparse_classes_30k_train_000289 | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year.
Method signatures and docstrings:
- def dayOfYear(self, date): Gi... | Implement the Python class `Solution` described below.
Class description:
Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year.
Method signatures and docstrings:
- def dayOfYear(self, date): Gi... | 01fe893ba2e37c9bda79e3081c556698f0b6d2f0 | <|skeleton|>
class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Day of the Year. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Day of the Year."""
def dayOfYear(self, date):
"""Given a string date representing a Gregorian calendar date formatted as ... | the_stack_v2_python_sparse | LeetCode/1154_day_of_the_year.py | KKosukeee/CodingQuestions | train | 1 |
f8e6dfc8b1bd33e4d06fc93442962e3e5e69e8be | [
"super().solve(X, y, coef, cf, cf_prime, eta, max_iter, store_coefs)\ncoef_prev = coef.copy()\nfor i in range(max_iter):\n coef_prev = coef\n eta_ = self._update_learning_rate(i, max_iter)\n coef = self._gradient_descent_step(X, y, coef, cf_prime, eta_)\n if self.momentum != 0:\n coef += coef_pre... | <|body_start_0|>
super().solve(X, y, coef, cf, cf_prime, eta, max_iter, store_coefs)
coef_prev = coef.copy()
for i in range(max_iter):
coef_prev = coef
eta_ = self._update_learning_rate(i, max_iter)
coef = self._gradient_descent_step(X, y, coef, cf_prime, eta_... | Class tailored to logistic regression. | GradientDescent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientDescent:
"""Class tailored to logistic regression."""
def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None):
"""Gradient descent solver."""
<|body_0|>
def _gradient_descent_step(X, y, coef, cf_prime... | stack_v2_sparse_classes_36k_train_003179 | 12,672 | permissive | [
{
"docstring": "Gradient descent solver.",
"name": "solve",
"signature": "def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None)"
},
{
"docstring": "Performs a single gradient descent step.",
"name": "_gradient_descent_step",
... | 2 | stack_v2_sparse_classes_30k_train_016899 | Implement the Python class `GradientDescent` described below.
Class description:
Class tailored to logistic regression.
Method signatures and docstrings:
- def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None): Gradient descent solver.
- def _gradient_d... | Implement the Python class `GradientDescent` described below.
Class description:
Class tailored to logistic regression.
Method signatures and docstrings:
- def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None): Gradient descent solver.
- def _gradient_d... | 3cf617399f99026cbcd79f8153d3196ebd86c7cd | <|skeleton|>
class GradientDescent:
"""Class tailored to logistic regression."""
def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None):
"""Gradient descent solver."""
<|body_0|>
def _gradient_descent_step(X, y, coef, cf_prime... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradientDescent:
"""Class tailored to logistic regression."""
def solve(self, X, y, coef, cf, cf_prime, eta=1.0, max_iter=1000, store_coefs=False, tol=1e-15, alpha=1.0, scale=None):
"""Gradient descent solver."""
super().solve(X, y, coef, cf, cf_prime, eta, max_iter, store_coefs)
... | the_stack_v2_python_sparse | src/lib/utils/optimize.py | hmvege/FYSSTK4155-Project2 | train | 0 |
fe7f2b35ab01db879a17ab2e79d5f35fcebc5ee0 | [
"self.keep_transcription_text = keep_transcription_text\nself.train_mode = not keep_transcription_text\nself.stride_ms = stride_ms\nself.window_ms = window_ms\nself.feat_dim = feat_dim\nself.loader = LoadInputsAndTargets()\nself._local_data = TarLocalData(tar2info={}, tar2object={})\nself.augmentation = Augmentatio... | <|body_start_0|>
self.keep_transcription_text = keep_transcription_text
self.train_mode = not keep_transcription_text
self.stride_ms = stride_ms
self.window_ms = window_ms
self.feat_dim = feat_dim
self.loader = LoadInputsAndTargets()
self._local_data = TarLocalDat... | SpeechCollatorBase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeechCollatorBase:
def __init__(self, aug_file, mean_std_filepath, vocab_filepath, spm_model_prefix, random_seed=0, unit_type='char', spectrum_type='linear', feat_dim=0, delta_delta=False, stride_ms=10.0, window_ms=20.0, n_fft=None, max_freq=None, target_sample_rate=16000, use_dB_normalization=... | stack_v2_sparse_classes_36k_train_003180 | 13,764 | permissive | [
{
"docstring": "SpeechCollator Collator Args: unit_type(str): token unit type, e.g. char, word, spm vocab_filepath (str): vocab file path. mean_std_filepath (str): mean and std file path, which suffix is *.npy spm_model_prefix (str): spm model prefix, need if `unit_type` is spm. augmentation_config (str, option... | 3 | null | Implement the Python class `SpeechCollatorBase` described below.
Class description:
Implement the SpeechCollatorBase class.
Method signatures and docstrings:
- def __init__(self, aug_file, mean_std_filepath, vocab_filepath, spm_model_prefix, random_seed=0, unit_type='char', spectrum_type='linear', feat_dim=0, delta_d... | Implement the Python class `SpeechCollatorBase` described below.
Class description:
Implement the SpeechCollatorBase class.
Method signatures and docstrings:
- def __init__(self, aug_file, mean_std_filepath, vocab_filepath, spm_model_prefix, random_seed=0, unit_type='char', spectrum_type='linear', feat_dim=0, delta_d... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class SpeechCollatorBase:
def __init__(self, aug_file, mean_std_filepath, vocab_filepath, spm_model_prefix, random_seed=0, unit_type='char', spectrum_type='linear', feat_dim=0, delta_delta=False, stride_ms=10.0, window_ms=20.0, n_fft=None, max_freq=None, target_sample_rate=16000, use_dB_normalization=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpeechCollatorBase:
def __init__(self, aug_file, mean_std_filepath, vocab_filepath, spm_model_prefix, random_seed=0, unit_type='char', spectrum_type='linear', feat_dim=0, delta_delta=False, stride_ms=10.0, window_ms=20.0, n_fft=None, max_freq=None, target_sample_rate=16000, use_dB_normalization=True, target_d... | the_stack_v2_python_sparse | paddlespeech/s2t/io/collator.py | anniyanvr/DeepSpeech-1 | train | 0 | |
327c271a1e6e32587d0e66bc1c8ab8ebfa9a49a3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.deviceEnrollmentLimitConfiguration'.casefol... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | The Base Class of Device Enrollment Configuration | DeviceEnrollmentConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceEnrollmentConfiguration:
"""The Base Class of Device Enrollment Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceEnrollmentConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: par... | stack_v2_sparse_classes_36k_train_003181 | 6,436 | 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: DeviceEnrollmentConfiguration",
"name": "create_from_discriminator_value",
"signature": "def create_from_dis... | 3 | stack_v2_sparse_classes_30k_train_009794 | Implement the Python class `DeviceEnrollmentConfiguration` described below.
Class description:
The Base Class of Device Enrollment Configuration
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceEnrollmentConfiguration: Creates a new instance of the... | Implement the Python class `DeviceEnrollmentConfiguration` described below.
Class description:
The Base Class of Device Enrollment Configuration
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceEnrollmentConfiguration: Creates a new instance of the... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceEnrollmentConfiguration:
"""The Base Class of Device Enrollment Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceEnrollmentConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeviceEnrollmentConfiguration:
"""The Base Class of Device Enrollment Configuration"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceEnrollmentConfiguration:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The ... | the_stack_v2_python_sparse | msgraph/generated/models/device_enrollment_configuration.py | microsoftgraph/msgraph-sdk-python | train | 135 |
311fd6ae560e67365300344f56e6f7c6b238c27a | [
"self.matrix = matrix\nself.preSumMatrix = []\nfor i in range(len(matrix)):\n cur = 0\n self.preSumMatrix.append([])\n for j in range(len(matrix[0])):\n cur += matrix[i][j]\n self.preSumMatrix[i].append(cur)",
"diff = val - self.matrix[row][col]\nfor i in range(col, len(self.preSumMatrix[0]... | <|body_start_0|>
self.matrix = matrix
self.preSumMatrix = []
for i in range(len(matrix)):
cur = 0
self.preSumMatrix.append([])
for j in range(len(matrix[0])):
cur += matrix[i][j]
self.preSumMatrix[i].append(cur)
<|end_body_0|>
... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k_train_003182 | 5,380 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row: int :type col: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, row, col, val)"
},
{
"docstring": ":type r... | 3 | stack_v2_sparse_classes_30k_train_014667 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def update(self, row, col, val): :type row: int :type col: int :type val: int :rtype: void
- def sumRegion(self, row... | fd310ec0a989e003242f1840230aaac150f006f0 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def update(self, row, col, val):
""":type row: int :type col: int :type val: int :rtype: void"""
<|body_1|>
def sumRegion(self, row1, col1, row2, col2):
""":typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.matrix = matrix
self.preSumMatrix = []
for i in range(len(matrix)):
cur = 0
self.preSumMatrix.append([])
for j in range(len(matrix[0])):
cur += ma... | the_stack_v2_python_sparse | 好咧,最后还是要搞google/hard/RangeSumQuery2DMutable308.py | jing1988a/python_fb | train | 0 | |
a95a35263fd31f4056e253abe6f0b511d0bf784d | [
"self.ec2_mock = MagicMock()\nself.ec2_mock.run_instances.return_value = {'Instances': [{'InstanceId': '1', 'PrivateIpAddress': '1.1.1.1', 'PublicIpAddress': '2.1.1.1', 'State': {'Name': 'pending'}}]}\nself.ec2_mock.describe_instances.return_value = {'Reservations': [{'Instances': [{'InstanceId': '1', 'PrivateIpAdd... | <|body_start_0|>
self.ec2_mock = MagicMock()
self.ec2_mock.run_instances.return_value = {'Instances': [{'InstanceId': '1', 'PrivateIpAddress': '1.1.1.1', 'PublicIpAddress': '2.1.1.1', 'State': {'Name': 'pending'}}]}
self.ec2_mock.describe_instances.return_value = {'Reservations': [{'Instances': ... | Test suite for class EC2Adapter. | EC2AdapterTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EC2AdapterTestCase:
"""Test suite for class EC2Adapter."""
def setUp(self) -> None:
"""Create an instance."""
<|body_0|>
def test_create_instances(self) -> None:
"""Create and start an instance."""
<|body_1|>
def test_list_instances(self) -> None:
... | stack_v2_sparse_classes_36k_train_003183 | 5,205 | permissive | [
{
"docstring": "Create an instance.",
"name": "setUp",
"signature": "def setUp(self) -> None"
},
{
"docstring": "Create and start an instance.",
"name": "test_create_instances",
"signature": "def test_create_instances(self) -> None"
},
{
"docstring": "List all instances.",
"n... | 4 | stack_v2_sparse_classes_30k_val_000264 | Implement the Python class `EC2AdapterTestCase` described below.
Class description:
Test suite for class EC2Adapter.
Method signatures and docstrings:
- def setUp(self) -> None: Create an instance.
- def test_create_instances(self) -> None: Create and start an instance.
- def test_list_instances(self) -> None: List a... | Implement the Python class `EC2AdapterTestCase` described below.
Class description:
Test suite for class EC2Adapter.
Method signatures and docstrings:
- def setUp(self) -> None: Create an instance.
- def test_create_instances(self) -> None: Create and start an instance.
- def test_list_instances(self) -> None: List a... | 55be690535e5f3feb33c888c3e4a586b7bdbf489 | <|skeleton|>
class EC2AdapterTestCase:
"""Test suite for class EC2Adapter."""
def setUp(self) -> None:
"""Create an instance."""
<|body_0|>
def test_create_instances(self) -> None:
"""Create and start an instance."""
<|body_1|>
def test_list_instances(self) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EC2AdapterTestCase:
"""Test suite for class EC2Adapter."""
def setUp(self) -> None:
"""Create an instance."""
self.ec2_mock = MagicMock()
self.ec2_mock.run_instances.return_value = {'Instances': [{'InstanceId': '1', 'PrivateIpAddress': '1.1.1.1', 'PublicIpAddress': '2.1.1.1', 'Sta... | the_stack_v2_python_sparse | src/py/flwr_experimental/ops/compute/ec2_adapter_test.py | adap/flower | train | 2,999 |
182ad5a6dad70c78408cd5188cff78eae39306c5 | [
"provider_names = build.ListBuildProviderNames()\nbuild_channel_providers = []\nfor name in provider_names:\n cls = build.GetBuildProviderClass(name)\n assert cls\n option_defs = cls().GetOptionDefs()\n build_channel_providers.append(mtt_messages.BuildChannelProvider(name=name, option_defs=mtt_messages.... | <|body_start_0|>
provider_names = build.ListBuildProviderNames()
build_channel_providers = []
for name in provider_names:
cls = build.GetBuildProviderClass(name)
assert cls
option_defs = cls().GetOptionDefs()
build_channel_providers.append(mtt_mess... | A handler for Build Channel Provider API. | BuildChannelProviderApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildChannelProviderApi:
"""A handler for Build Channel Provider API."""
def List(self, request):
"""Lists registered build channel providers."""
<|body_0|>
def Get(self, request):
"""Fetches a build channel provider. Parameters: build_channel_provider_id: Build ... | stack_v2_sparse_classes_36k_train_003184 | 2,871 | permissive | [
{
"docstring": "Lists registered build channel providers.",
"name": "List",
"signature": "def List(self, request)"
},
{
"docstring": "Fetches a build channel provider. Parameters: build_channel_provider_id: Build channel provider ID",
"name": "Get",
"signature": "def Get(self, request)"
... | 2 | stack_v2_sparse_classes_30k_train_007088 | Implement the Python class `BuildChannelProviderApi` described below.
Class description:
A handler for Build Channel Provider API.
Method signatures and docstrings:
- def List(self, request): Lists registered build channel providers.
- def Get(self, request): Fetches a build channel provider. Parameters: build_channe... | Implement the Python class `BuildChannelProviderApi` described below.
Class description:
A handler for Build Channel Provider API.
Method signatures and docstrings:
- def List(self, request): Lists registered build channel providers.
- def Get(self, request): Fetches a build channel provider. Parameters: build_channe... | 5e10bed02089e4cf29ae4d9d67e127f77e8fb3c9 | <|skeleton|>
class BuildChannelProviderApi:
"""A handler for Build Channel Provider API."""
def List(self, request):
"""Lists registered build channel providers."""
<|body_0|>
def Get(self, request):
"""Fetches a build channel provider. Parameters: build_channel_provider_id: Build ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildChannelProviderApi:
"""A handler for Build Channel Provider API."""
def List(self, request):
"""Lists registered build channel providers."""
provider_names = build.ListBuildProviderNames()
build_channel_providers = []
for name in provider_names:
cls = buil... | the_stack_v2_python_sparse | multitest_transport/api/build_channel_provider_api.py | maksonlee/multitest_transport | train | 0 |
878935b47df44f09108fff3720df4c511f22bc33 | [
"if nums:\n self.nums = [nums[0]]\n for i in range(1, len(nums)):\n self.nums.append(self.nums[-1] + nums[i])",
"if i == 0:\n return self.nums[j]\nreturn self.nums[j] - self.nums[i - 1]"
] | <|body_start_0|>
if nums:
self.nums = [nums[0]]
for i in range(1, len(nums)):
self.nums.append(self.nums[-1] + nums[i])
<|end_body_0|>
<|body_start_1|>
if i == 0:
return self.nums[j]
return self.nums[j] - self.nums[i - 1]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_003185 | 1,087 | no_license | [
{
"docstring": "initialize your data structure here. :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": "sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, ... | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): initialize your data structure here. :type nums: List[int]
- def sumRange(self, i, j): sum of elements nums[i..j], inclusive. :type i: int :type j: int ... | 2df1a58aa9474f2ecec2ee7c45ebf12466181391 | <|skeleton|>
class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
"""sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
"""initialize your data structure here. :type nums: List[int]"""
if nums:
self.nums = [nums[0]]
for i in range(1, len(nums)):
self.nums.append(self.nums[-1] + nums[i])
def sumRange(self, i, j):
"""sum of e... | the_stack_v2_python_sparse | RangeSumQuery-Immutable.py | zjuzpz/Algorithms | train | 2 | |
e1880ad05e6eb8e04a90d77deebb111cd5ce871c | [
"self.ago_string = listing.get('config_specified_ago_string')\nself.city = listing.get('city')\nself.cluster_expansion_url = listing.get('cluster_expansion_url')\nself.company = listing.get('company_name')\nself.description = listing.get('description_clip') if listing.get('description_clip') else ''\nself.descripti... | <|body_start_0|>
self.ago_string = listing.get('config_specified_ago_string')
self.city = listing.get('city')
self.cluster_expansion_url = listing.get('cluster_expansion_url')
self.company = listing.get('company_name')
self.description = listing.get('description_clip') if listing... | Job object to store job information. | Job | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Job:
"""Job object to store job information."""
def __init__(self, listing, bridge_search_query):
"""Initialize a Job object."""
<|body_0|>
def is_new(self):
"""Returns true if job is less than a specified number of days old."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_003186 | 5,331 | no_license | [
{
"docstring": "Initialize a Job object.",
"name": "__init__",
"signature": "def __init__(self, listing, bridge_search_query)"
},
{
"docstring": "Returns true if job is less than a specified number of days old.",
"name": "is_new",
"signature": "def is_new(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007728 | Implement the Python class `Job` described below.
Class description:
Job object to store job information.
Method signatures and docstrings:
- def __init__(self, listing, bridge_search_query): Initialize a Job object.
- def is_new(self): Returns true if job is less than a specified number of days old. | Implement the Python class `Job` described below.
Class description:
Job object to store job information.
Method signatures and docstrings:
- def __init__(self, listing, bridge_search_query): Initialize a Job object.
- def is_new(self): Returns true if job is less than a specified number of days old.
<|skeleton|>
cl... | da3073eec6d676dfe0164502b80d2a1c75e89575 | <|skeleton|>
class Job:
"""Job object to store job information."""
def __init__(self, listing, bridge_search_query):
"""Initialize a Job object."""
<|body_0|>
def is_new(self):
"""Returns true if job is less than a specified number of days old."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Job:
"""Job object to store job information."""
def __init__(self, listing, bridge_search_query):
"""Initialize a Job object."""
self.ago_string = listing.get('config_specified_ago_string')
self.city = listing.get('city')
self.cluster_expansion_url = listing.get('cluster_e... | the_stack_v2_python_sparse | web-serpng/code/serpng/jobs/services/search/job.py | alyago/django-web | train | 0 |
866dd1740d6a646ef55b652414c5f369a030f1e1 | [
"try:\n prod = [var.ui.editNomeProd, var.ui.editPrezoProd, var.ui.editStockProd]\n newprod = []\n for i in prod:\n newprod.append(i.text())\n if newprod[0] == '' or newprod[1] == '' or newprod[2] == '':\n print('Faltan datos')\n else:\n print(newprod)\n conexion.Conexion.a... | <|body_start_0|>
try:
prod = [var.ui.editNomeProd, var.ui.editPrezoProd, var.ui.editStockProd]
newprod = []
for i in prod:
newprod.append(i.text())
if newprod[0] == '' or newprod[1] == '' or newprod[2] == '':
print('Faltan datos')
... | Eventos de la clase Productos | Productos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Productos:
"""Eventos de la clase Productos"""
def altaProd():
"""Módulo que recoge los datos del formulario de productos para darlo de alta :return: None"""
<|body_0|>
def cargarProd():
"""Módulo que carga en el formulario los datos del producto seleccionado :re... | stack_v2_sparse_classes_36k_train_003187 | 3,095 | no_license | [
{
"docstring": "Módulo que recoge los datos del formulario de productos para darlo de alta :return: None",
"name": "altaProd",
"signature": "def altaProd()"
},
{
"docstring": "Módulo que carga en el formulario los datos del producto seleccionado :return: None",
"name": "cargarProd",
"sig... | 5 | stack_v2_sparse_classes_30k_train_016751 | Implement the Python class `Productos` described below.
Class description:
Eventos de la clase Productos
Method signatures and docstrings:
- def altaProd(): Módulo que recoge los datos del formulario de productos para darlo de alta :return: None
- def cargarProd(): Módulo que carga en el formulario los datos del prod... | Implement the Python class `Productos` described below.
Class description:
Eventos de la clase Productos
Method signatures and docstrings:
- def altaProd(): Módulo que recoge los datos del formulario de productos para darlo de alta :return: None
- def cargarProd(): Módulo que carga en el formulario los datos del prod... | 9ea06b6fde86da8ac45f0e6775758556f8a61bc5 | <|skeleton|>
class Productos:
"""Eventos de la clase Productos"""
def altaProd():
"""Módulo que recoge los datos del formulario de productos para darlo de alta :return: None"""
<|body_0|>
def cargarProd():
"""Módulo que carga en el formulario los datos del producto seleccionado :re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Productos:
"""Eventos de la clase Productos"""
def altaProd():
"""Módulo que recoge los datos del formulario de productos para darlo de alta :return: None"""
try:
prod = [var.ui.editNomeProd, var.ui.editPrezoProd, var.ui.editStockProd]
newprod = []
for ... | the_stack_v2_python_sparse | products.py | RubenBL0/BLANCOLAGE | train | 0 |
5bb9a7f1263ffef188ec3f11fdfe4db167ef6d24 | [
"if self.__isInValid(authorization_header) or not authorization_header.startswith('Basic '):\n return None\nreturn authorization_header.split(' ')[1].lstrip()",
"if self.__isInValid(base64_authorization_header):\n return None\ntry:\n return base64.b64decode(base64_authorization_header).decode('utf-8')\ne... | <|body_start_0|>
if self.__isInValid(authorization_header) or not authorization_header.startswith('Basic '):
return None
return authorization_header.split(' ')[1].lstrip()
<|end_body_0|>
<|body_start_1|>
if self.__isInValid(base64_authorization_header):
return None
... | Basic Auth class. | BasicAuth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuth:
"""Basic Auth class."""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Extract_base64_authorization_header."""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header: str) -> str:
"""Dec... | stack_v2_sparse_classes_36k_train_003188 | 2,780 | permissive | [
{
"docstring": "Extract_base64_authorization_header.",
"name": "extract_base64_authorization_header",
"signature": "def extract_base64_authorization_header(self, authorization_header: str) -> str"
},
{
"docstring": "Decode_base64_authorization_header.",
"name": "decode_base64_authorization_h... | 6 | stack_v2_sparse_classes_30k_train_007990 | Implement the Python class `BasicAuth` described below.
Class description:
Basic Auth class.
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Extract_base64_authorization_header.
- def decode_base64_authorization_header(self, base64_authorization_hea... | Implement the Python class `BasicAuth` described below.
Class description:
Basic Auth class.
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Extract_base64_authorization_header.
- def decode_base64_authorization_header(self, base64_authorization_hea... | eb514784772352b8e4873d1f648726815ab69592 | <|skeleton|>
class BasicAuth:
"""Basic Auth class."""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Extract_base64_authorization_header."""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_header: str) -> str:
"""Dec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicAuth:
"""Basic Auth class."""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Extract_base64_authorization_header."""
if self.__isInValid(authorization_header) or not authorization_header.startswith('Basic '):
return None
return... | the_stack_v2_python_sparse | 0x06-Basic_authentication/api/v1/auth/basic_auth.py | JoseAVallejo12/holbertonschool-web_back_end | train | 0 |
fab08cbf93e02acf724570c8f3ce07e38a696abf | [
"rev_total = self.tempo * self.count\nrev_total += review.tempo\nself.count += 1\nself.score = rev_total / self.count\nself.save()",
"reviews = Review.objects.filger(song=self.song).filter(quality=self.tempo)\ncount = len(reviews)\nagg = sum"
] | <|body_start_0|>
rev_total = self.tempo * self.count
rev_total += review.tempo
self.count += 1
self.score = rev_total / self.count
self.save()
<|end_body_0|>
<|body_start_1|>
reviews = Review.objects.filger(song=self.song).filter(quality=self.tempo)
count = len(r... | ReviewAvg | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and count with a new quality review"""
<|body_0|>
def reset_avg(self):
"""Totally resets the average by looking at all available scores for a quality"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_003189 | 1,308 | no_license | [
{
"docstring": "Adjust the score and count with a new quality review",
"name": "add_review",
"signature": "def add_review(self, review)"
},
{
"docstring": "Totally resets the average by looking at all available scores for a quality",
"name": "reset_avg",
"signature": "def reset_avg(self)... | 2 | stack_v2_sparse_classes_30k_test_000748 | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and count with a new quality review
- def reset_avg(self): Totally resets the average by looking at all available scores for a qu... | Implement the Python class `ReviewAvg` described below.
Class description:
Implement the ReviewAvg class.
Method signatures and docstrings:
- def add_review(self, review): Adjust the score and count with a new quality review
- def reset_avg(self): Totally resets the average by looking at all available scores for a qu... | 36e08862d1bbcc9a4b535d948199e569ecbdd115 | <|skeleton|>
class ReviewAvg:
def add_review(self, review):
"""Adjust the score and count with a new quality review"""
<|body_0|>
def reset_avg(self):
"""Totally resets the average by looking at all available scores for a quality"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReviewAvg:
def add_review(self, review):
"""Adjust the score and count with a new quality review"""
rev_total = self.tempo * self.count
rev_total += review.tempo
self.count += 1
self.score = rev_total / self.count
self.save()
def reset_avg(self):
""... | the_stack_v2_python_sparse | Assignments/Brea/Capstone/capstone/models2.py | PdxCodeGuild/class_mudpuppy | train | 5 | |
8d281c9677935eb83a7de1afe43c5ee04c9d01ae | [
"self.abs_tol = abs_tol\nself.rel_tol = rel_tol\nself.n_max = n_max\nself.alpha = alpha\nself.inflate = inflate\nself.stage = 'sigma'\nself.data = MeanVarData(len(true_measure), n_init)\nallowed_distribs = ['IIDStdUniform', 'IIDStdGaussian']\nsuper().__init__(discrete_distrib, allowed_distribs)",
"if self.stage =... | <|body_start_0|>
self.abs_tol = abs_tol
self.rel_tol = rel_tol
self.n_max = n_max
self.alpha = alpha
self.inflate = inflate
self.stage = 'sigma'
self.data = MeanVarData(len(true_measure), n_init)
allowed_distribs = ['IIDStdUniform', 'IIDStdGaussian']
... | Stopping criterion based on the Central Limit Theorem (CLT) | CLT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution i... | stack_v2_sparse_classes_36k_train_003190 | 3,558 | no_license | [
{
"docstring": "Args: discrete_distrib true_measure: an instance of DiscreteDistribution inflate: inflation factor when estimating variance alpha: significance level for confidence interval abs_tol: absolute error tolerance rel_tol: relative error tolerance n_max: maximum number of samples",
"name": "__init... | 2 | stack_v2_sparse_classes_30k_train_016929 | Implement the Python class `CLT` described below.
Class description:
Stopping criterion based on the Central Limit Theorem (CLT)
Method signatures and docstrings:
- def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0): Args: discrete_di... | Implement the Python class `CLT` described below.
Class description:
Stopping criterion based on the Central Limit Theorem (CLT)
Method signatures and docstrings:
- def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0): Args: discrete_di... | 9f37eb67f74c4b1a4ccfb5547a2b284cb5897d37 | <|skeleton|>
class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLT:
"""Stopping criterion based on the Central Limit Theorem (CLT)"""
def __init__(self, discrete_distrib, true_measure, inflate=1.2, alpha=0.01, abs_tol=0.01, rel_tol=0, n_init=1024, n_max=10000000000.0):
"""Args: discrete_distrib true_measure: an instance of DiscreteDistribution inflate: infla... | the_stack_v2_python_sparse | python_prototype/qmcpy/stopping_criterion/clt.py | jagadeesr/QMCSoftware | train | 0 |
13850e96a9dca01a7b1133a1a6d8e227a050f276 | [
"pre_sum = list(accumulate(nums))\npre_sum.insert(0, 0)\nn = len(nums)\ncnt = 0\nfor left in range(0, n):\n for r in range(left, n):\n if pre_sum[r + 1] - pre_sum[left] == k:\n cnt += 1\nreturn cnt",
"d = {0: 1}\npre_sum = 0\ncount = 0\nfor i in range(len(nums)):\n pre_sum += nums[i]\n ... | <|body_start_0|>
pre_sum = list(accumulate(nums))
pre_sum.insert(0, 0)
n = len(nums)
cnt = 0
for left in range(0, n):
for r in range(left, n):
if pre_sum[r + 1] - pre_sum[left] == k:
cnt += 1
return cnt
<|end_body_0|>
<|bod... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""简单前缀和解决, 超时"""
<|body_0|>
def subarraySum2(self, nums: List[int], k: int) -> int:
"""借助哈希表保存累加和sumsum及出现的次数。若累加和sum-ksum−k在哈希表中存在,则说明存在连续序列使得和为kk。则之前的累加和中,sum-ksum−k出现的次数即为有多少种子序列使得累加和为sum-ksum−k"""
... | stack_v2_sparse_classes_36k_train_003191 | 1,736 | no_license | [
{
"docstring": "简单前缀和解决, 超时",
"name": "subarraySum",
"signature": "def subarraySum(self, nums: List[int], k: int) -> int"
},
{
"docstring": "借助哈希表保存累加和sumsum及出现的次数。若累加和sum-ksum−k在哈希表中存在,则说明存在连续序列使得和为kk。则之前的累加和中,sum-ksum−k出现的次数即为有多少种子序列使得累加和为sum-ksum−k",
"name": "subarraySum2",
"signature... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 简单前缀和解决, 超时
- def subarraySum2(self, nums: List[int], k: int) -> int: 借助哈希表保存累加和sumsum及出现的次数。若累加和sum-ksum−k在哈希表中存在,则说明存在连续序... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums: List[int], k: int) -> int: 简单前缀和解决, 超时
- def subarraySum2(self, nums: List[int], k: int) -> int: 借助哈希表保存累加和sumsum及出现的次数。若累加和sum-ksum−k在哈希表中存在,则说明存在连续序... | 5ba3465ba9c85955eac188e1e3793a981de712e7 | <|skeleton|>
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""简单前缀和解决, 超时"""
<|body_0|>
def subarraySum2(self, nums: List[int], k: int) -> int:
"""借助哈希表保存累加和sumsum及出现的次数。若累加和sum-ksum−k在哈希表中存在,则说明存在连续序列使得和为kk。则之前的累加和中,sum-ksum−k出现的次数即为有多少种子序列使得累加和为sum-ksum−k"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""简单前缀和解决, 超时"""
pre_sum = list(accumulate(nums))
pre_sum.insert(0, 0)
n = len(nums)
cnt = 0
for left in range(0, n):
for r in range(left, n):
if pre_sum[r + 1] - pre_s... | the_stack_v2_python_sparse | 前缀和/560_和为k的子数组.py | SilvesSun/learn-algorithm-in-python | train | 0 | |
fe6183ae51829d4cd615e3be642be74de34b7af6 | [
"super().__init__(**kwargs)\nself.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs)\nself.set_logger()\nprint(self.model.summary())\nif self.data is not None:\n print('Training set size: %d; Validation set size: %d' % (self.get_training_data_size(), self.get_validation_data_size()))",... | <|body_start_0|>
super().__init__(**kwargs)
self.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs)
self.set_logger()
print(self.model.summary())
if self.data is not None:
print('Training set size: %d; Validation set size: %d' % (self.get_tr... | A basic convolutional neural network model. | KerasCNN | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KerasCNN:
"""A basic convolutional neural network model."""
def __init__(self, **kwargs):
"""Initializer Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def build_model(self, input_shape, num_classes, conv_kernel_size=(4, 4), conv_strides=(2, ... | stack_v2_sparse_classes_36k_train_003192 | 3,114 | permissive | [
{
"docstring": "Initializer Args: **kwargs: Additional parameters to pass to the function",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Define the model architecture. Args: input_shape (numpy.ndarray): The shape of the data num_classes (int): The number of ... | 2 | null | Implement the Python class `KerasCNN` described below.
Class description:
A basic convolutional neural network model.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializer Args: **kwargs: Additional parameters to pass to the function
- def build_model(self, input_shape, num_classes, conv_kerne... | Implement the Python class `KerasCNN` described below.
Class description:
A basic convolutional neural network model.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializer Args: **kwargs: Additional parameters to pass to the function
- def build_model(self, input_shape, num_classes, conv_kerne... | d8e2d22dfccfb8488f70f1fb5593d4e6ee1eca1f | <|skeleton|>
class KerasCNN:
"""A basic convolutional neural network model."""
def __init__(self, **kwargs):
"""Initializer Args: **kwargs: Additional parameters to pass to the function"""
<|body_0|>
def build_model(self, input_shape, num_classes, conv_kernel_size=(4, 4), conv_strides=(2, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KerasCNN:
"""A basic convolutional neural network model."""
def __init__(self, **kwargs):
"""Initializer Args: **kwargs: Additional parameters to pass to the function"""
super().__init__(**kwargs)
self.model = self.build_model(self.feature_shape, self.data.num_classes, **kwargs)
... | the_stack_v2_python_sparse | openfl/models/tensorflow/keras_cnn/keras_cnn.py | sbakas/OpenFederatedLearning-1 | train | 0 |
ad2cf5ed5bf84c172cb0aa1eaac2f3cd983f6298 | [
"super().__init__()\nself.input_size = input_size\nself.d_model = d_model\nif input_size != d_model:\n self.proj = nn.Linear(input_size, d_model)\nlayer = TransformerSRUDecoderLayer(d_model, nhead, dim_feedforward, dropout, sru_dropout)\nself.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers... | <|body_start_0|>
super().__init__()
self.input_size = input_size
self.d_model = d_model
if input_size != d_model:
self.proj = nn.Linear(input_size, d_model)
layer = TransformerSRUDecoderLayer(d_model, nhead, dim_feedforward, dropout, sru_dropout)
self.layers =... | A TransformerSRUDecoderwith an SRU replacing the FFN. | TransformerSRUDecoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerSRUDecoder:
"""A TransformerSRUDecoderwith an SRU replacing the FFN."""
def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
... | stack_v2_sparse_classes_36k_train_003193 | 23,050 | permissive | [
{
"docstring": "Initialize the TransformerEncoder. Parameters --------- input_size : int The embedding dimension of the model. If different from d_model, a linear projection layer is added. d_model : int the number of expected features in encoder/decoder inputs. Default ``512``. nhead : int, optional the number... | 3 | null | Implement the Python class `TransformerSRUDecoder` described below.
Class description:
A TransformerSRUDecoderwith an SRU replacing the FFN.
Method signatures and docstrings:
- def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1, sru... | Implement the Python class `TransformerSRUDecoder` described below.
Class description:
A TransformerSRUDecoderwith an SRU replacing the FFN.
Method signatures and docstrings:
- def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1, sru... | 0dc2f5b2b286694defe8abf450fe5be9ae12c097 | <|skeleton|>
class TransformerSRUDecoder:
"""A TransformerSRUDecoderwith an SRU replacing the FFN."""
def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerSRUDecoder:
"""A TransformerSRUDecoderwith an SRU replacing the FFN."""
def __init__(self, input_size: int=512, d_model: int=512, nhead: int=8, num_layers: int=6, dim_feedforward: int=2048, dropout: float=0.1, sru_dropout: Optional[float]=None, **kwargs: Dict[str, Any]) -> None:
"""Ini... | the_stack_v2_python_sparse | flambe/nn/transformer_sru.py | cle-ros/flambe | train | 1 |
c25f83960b5144701a24e29c7e13ae6c7f48d2d7 | [
"self.fig = plt.figure()\nsuper().__init__(self.fig)\ngs = gridspec.GridSpec(4, 1)\nself.ax_main = self.fig.add_subplot(gs[:3, 0])\nself.ax_resid = self.fig.add_subplot(gs[3:4, 0], sharex=self.ax_main)\nif specfit is not None:\n self.plot(specfit)\nself.ax_main.set_xlim(specfit.xlim)\nself.ax_main.set_ylim(specf... | <|body_start_0|>
self.fig = plt.figure()
super().__init__(self.fig)
gs = gridspec.GridSpec(4, 1)
self.ax_main = self.fig.add_subplot(gs[:3, 0])
self.ax_resid = self.fig.add_subplot(gs[3:4, 0], sharex=self.ax_main)
if specfit is not None:
self.plot(specfit)
... | A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot ax_resid (matplotlib.axes.Axis): Axis for the residual plot | SpecFitCanvas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecFitCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot ax_resid (matplotli... | stack_v2_sparse_classes_36k_train_003194 | 1,992 | permissive | [
{
"docstring": "Initilization method for the SpecFitCanvas :param (SpecFit) specfit: SpecFit object, which holds information on the astronomical spectrum and its fit.",
"name": "__init__",
"signature": "def __init__(self, specfit=None)"
},
{
"docstring": "Plot the spectrum and the models :param ... | 2 | stack_v2_sparse_classes_30k_train_012421 | Implement the Python class `SpecFitCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis):... | Implement the Python class `SpecFitCanvas` described below.
Class description:
A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis):... | a71c24f07a13546e662271349b1e83b31ac1720e | <|skeleton|>
class SpecFitCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot ax_resid (matplotli... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpecFitCanvas:
"""A FigureCanvas for plotting an astronomical spectrum from a SpecFit object. This class provides the plotting routine for the SpecFitGui. Attributes: fig (matplotlib.figure.Figure): Figure object for the plot. ax_main (matplotlib.axes.Axis): Axis for main plot ax_resid (matplotlib.axes.Axis):... | the_stack_v2_python_sparse | sculptor/specfitcanvas.py | jtschindler/sculptor | train | 9 |
de20d56dd39418f7b07b9e7d620b134a74a26383 | [
"plan = self.raw.get('plan')\n\ndef find_tid(p):\n if 'task' in p:\n task = p.get('task')\n if task.get('name') == task_name:\n return p.get('id')\n for k, v in p.items():\n if isinstance(v, dict):\n task_id = find_tid(v)\n if task_id:\n ret... | <|body_start_0|>
plan = self.raw.get('plan')
def find_tid(p):
if 'task' in p:
task = p.get('task')
if task.get('name') == task_name:
return p.get('id')
for k, v in p.items():
if isinstance(v, dict):
... | BuildPlan | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BuildPlan:
def task_id(self, task_name: str):
"""determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is returned. If no task with the given name is found, `None` is returned."""
<|body_0|>
de... | stack_v2_sparse_classes_36k_train_003195 | 15,599 | permissive | [
{
"docstring": "determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is returned. If no task with the given name is found, `None` is returned.",
"name": "task_id",
"signature": "def task_id(self, task_name: str)"
},
{... | 2 | stack_v2_sparse_classes_30k_train_010478 | Implement the Python class `BuildPlan` described below.
Class description:
Implement the BuildPlan class.
Method signatures and docstrings:
- def task_id(self, task_name: str): determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is re... | Implement the Python class `BuildPlan` described below.
Class description:
Implement the BuildPlan class.
Method signatures and docstrings:
- def task_id(self, task_name: str): determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is re... | b043a1285b67c585fc357c80678765fae47ea506 | <|skeleton|>
class BuildPlan:
def task_id(self, task_name: str):
"""determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is returned. If no task with the given name is found, `None` is returned."""
<|body_0|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BuildPlan:
def task_id(self, task_name: str):
"""determines the task-id for the given task_name If the task_name is not unique, the task-id for the first-found task with the given name is returned. If no task with the given name is found, `None` is returned."""
plan = self.raw.get('plan')
... | the_stack_v2_python_sparse | concourse/client/model.py | gardener/cc-utils | train | 21 | |
2615f7084d90dc4b463a651644c519be9b214dd8 | [
"if p.val < root.val and q.val < root.val:\n return self.lowestCommonAncestor(root.left, p, q)\nelif p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right, p, q)\nelse:\n return root",
"node = root\nwhile True:\n if p.val < node.val and q.val < node.val:\n node = ... | <|body_start_0|>
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
<|end_body_0|>
<|body_start_1|>
... | 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 lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""... | stack_v2_sparse_classes_36k_train_003196 | 1,256 | 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... | 2 | stack_v2_sparse_classes_30k_train_011456 | 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 lowestCommonAncestor(self, root, p, q): :type root: Tr... | 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 lowestCommonAncestor(self, root, p, q): :type root: Tr... | 6582b0f138a19f9d4a005eda298ecb1488eb0d2e | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
... | the_stack_v2_python_sparse | Tree/235.py | ShangruZhong/leetcode | train | 0 | |
17ee9697dfe9c096ff84dd3ead78987cd8504cd5 | [
"api_datas = self.call_api(search_items, 'adaptation', 'detail', None, extra_param=extra_param)\nproduct = [AdaptationDetail(api_data) for api_data in api_datas]\nif csv:\n csv_format.to_csv(product, 'adaptation', 'detail', output_dir=output_dir)\nlogging.info('Adaptation Detail Data Ready.')\nreturn product",
... | <|body_start_0|>
api_datas = self.call_api(search_items, 'adaptation', 'detail', None, extra_param=extra_param)
product = [AdaptationDetail(api_data) for api_data in api_datas]
if csv:
csv_format.to_csv(product, 'adaptation', 'detail', output_dir=output_dir)
logging.info('Ada... | This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Summary for the given list of IDs | Adaptation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Adaptation:
"""This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Summary for the given list of IDs"""
... | stack_v2_sparse_classes_36k_train_003197 | 5,519 | permissive | [
{
"docstring": "Retrieves adaptation detail product data from the First Street Foundation API given a list of search_items and returns a list of Adaptation Detail objects. Args: search_items (list/file): A First Street Foundation IDs, lat/lng pair, address, or a file of First Street Foundation IDs csv (bool): T... | 3 | stack_v2_sparse_classes_30k_val_000669 | Implement the Python class `Adaptation` described below.
Class description:
This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Sum... | Implement the Python class `Adaptation` described below.
Class description:
This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Sum... | f6bcd43bf76fd9ee893482bcc17614f9ed01d0c5 | <|skeleton|>
class Adaptation:
"""This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Summary for the given list of IDs"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Adaptation:
"""This class receives a list of search_items and handles the creation of a adaptation product from the request. Methods: get_detail: Retrieves a list of Adaptation Details for the given list of IDs get_summary: Retrieves a list of Adaptation Summary for the given list of IDs"""
def get_detai... | the_stack_v2_python_sparse | firststreet/api/adaptation.py | rht/fsf_api_access_python | train | 0 |
e59a8db10ff05797345353182cb7d141482091ec | [
"self.model = model\nself.feature_names = feature_names\nself.feature_types = feature_types",
"if name is None:\n name = gen_name_from_class(self)\ny = clean_dimensions(y, 'y')\nif y.ndim != 1:\n raise ValueError('y must be 1 dimensional')\nX, n_samples = preclean_X(X, self.feature_names, self.feature_types... | <|body_start_0|>
self.model = model
self.feature_names = feature_names
self.feature_types = feature_types
<|end_body_0|>
<|body_start_1|>
if name is None:
name = gen_name_from_class(self)
y = clean_dimensions(y, 'y')
if y.ndim != 1:
raise ValueErr... | Produces ROC curves. | ROC | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ROC:
"""Produces ROC curves."""
def __init__(self, model, feature_names=None, feature_types=None):
"""Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) feature_names: List of feature names. feature_types... | stack_v2_sparse_classes_36k_train_003198 | 10,362 | permissive | [
{
"docstring": "Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) feature_names: List of feature names. feature_types: List of feature types.",
"name": "__init__",
"signature": "def __init__(self, model, feature_names=None,... | 2 | stack_v2_sparse_classes_30k_train_013590 | Implement the Python class `ROC` described below.
Class description:
Produces ROC curves.
Method signatures and docstrings:
- def __init__(self, model, feature_names=None, feature_types=None): Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regres... | Implement the Python class `ROC` described below.
Class description:
Produces ROC curves.
Method signatures and docstrings:
- def __init__(self, model, feature_names=None, feature_types=None): Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regres... | e6f38ea195aecbbd9d28c7183a83c65ada16e1ae | <|skeleton|>
class ROC:
"""Produces ROC curves."""
def __init__(self, model, feature_names=None, feature_types=None):
"""Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) feature_names: List of feature names. feature_types... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ROC:
"""Produces ROC curves."""
def __init__(self, model, feature_names=None, feature_types=None):
"""Initializes class. Args: model: model or prediction function of model (predict_proba for classification or predict for regression) feature_names: List of feature names. feature_types: List of fea... | the_stack_v2_python_sparse | python/interpret-core/interpret/perf/_curve.py | interpretml/interpret | train | 3,731 |
3134e6970696b9b73462d784ec878b3f89a9352b | [
"if not value:\n return u''\nseparator = getattr(self.widget, 'separator', ',')\nreturn separator.join((unicode(v) for v in value))",
"if not value:\n return self.field.missing_value\nseparator = getattr(self.widget, 'separator', ',')\nreturn tuple([v for v in value.split(separator)])"
] | <|body_start_0|>
if not value:
return u''
separator = getattr(self.widget, 'separator', ',')
return separator.join((unicode(v) for v in value))
<|end_body_0|>
<|body_start_1|>
if not value:
return self.field.missing_value
separator = getattr(self.widget, ... | Data converter for ICollection. | TagsSelectWidgetConverter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TagsSelectWidgetConverter:
"""Data converter for ICollection."""
def toWidgetValue(self, value):
"""Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using separator defined on widget :rtype: string"""
<|b... | stack_v2_sparse_classes_36k_train_003199 | 4,276 | no_license | [
{
"docstring": "Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using separator defined on widget :rtype: string",
"name": "toWidgetValue",
"signature": "def toWidgetValue(self, value)"
},
{
"docstring": "Converts from widg... | 2 | null | Implement the Python class `TagsSelectWidgetConverter` described below.
Class description:
Data converter for ICollection.
Method signatures and docstrings:
- def toWidgetValue(self, value): Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using ... | Implement the Python class `TagsSelectWidgetConverter` described below.
Class description:
Data converter for ICollection.
Method signatures and docstrings:
- def toWidgetValue(self, value): Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using ... | d0b1c0db3ae4b355ab9d694b8392b73b65036d1e | <|skeleton|>
class TagsSelectWidgetConverter:
"""Data converter for ICollection."""
def toWidgetValue(self, value):
"""Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using separator defined on widget :rtype: string"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TagsSelectWidgetConverter:
"""Data converter for ICollection."""
def toWidgetValue(self, value):
"""Converts from field value to widget. :param value: Field value. :type value: list |tuple | set :returns: Items separated using separator defined on widget :rtype: string"""
if not value:
... | the_stack_v2_python_sparse | genweb/core/widgets/select2_tags_widget.py | UPCnet/genweb.core | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.