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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d87574e09b5d6209a73863ef4e1280e6ea6dd87c | [
"self.size = size\nself.sum = 0\nself.window = [0] * size\nself.index = -1",
"self.index += 1\nself.window[self.index % self.size] = val\nself.sum = sum(self.window)\nreturn self.sum / min(self.index + 1, self.size)"
] | <|body_start_0|>
self.size = size
self.sum = 0
self.window = [0] * size
self.index = -1
<|end_body_0|>
<|body_start_1|>
self.index += 1
self.window[self.index % self.size] = val
self.sum = sum(self.window)
return self.sum / min(self.index + 1, self.size)
... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.sum = 0... | stack_v2_sparse_classes_36k_train_002100 | 2,826 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | 2ffe01713a12090848ed9b75457bf9ee156db84b | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.sum = 0
self.window = [0] * size
self.index = -1
def next(self, val):
""":type val: int :rtype: float"""
self.index += 1
... | the_stack_v2_python_sparse | array/Q346_movingAverage.py | liangming168/leetcode | train | 0 | |
77a9a8ae36b5a9f452fa6accaf680ac54f150a01 | [
"stk = []\nret = 0\nfor s in S:\n if s == '(':\n stk.append(0)\n else:\n cur = stk.pop()\n score = max(2 * cur, 1)\n if stk:\n stk[-1] += score\n else:\n ret += score\nreturn ret",
"ret = 0\ncur_stk = []\nfor s in S:\n if s == '(':\n cur_stk... | <|body_start_0|>
stk = []
ret = 0
for s in S:
if s == '(':
stk.append(0)
else:
cur = stk.pop()
score = max(2 * cur, 1)
if stk:
stk[-1] += score
else:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
<|body_0|>
def scoreOfParentheses_error(self, S: str) -> int:
"""stk"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_002101 | 1,710 | no_license | [
{
"docstring": "stk Every position in the string has a depth - some number of matching parentheses surrounding it",
"name": "scoreOfParentheses",
"signature": "def scoreOfParentheses(self, S: str) -> int"
},
{
"docstring": "stk",
"name": "scoreOfParentheses_error",
"signature": "def scor... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: stk Every position in the string has a depth - some number of matching parentheses surrounding it
- def scoreOfParentheses_error(self... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def scoreOfParentheses(self, S: str) -> int: stk Every position in the string has a depth - some number of matching parentheses surrounding it
- def scoreOfParentheses_error(self... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
<|body_0|>
def scoreOfParentheses_error(self, S: str) -> int:
"""stk"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def scoreOfParentheses(self, S: str) -> int:
"""stk Every position in the string has a depth - some number of matching parentheses surrounding it"""
stk = []
ret = 0
for s in S:
if s == '(':
stk.append(0)
else:
c... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetCode/856 Score of Parentheses.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
3d2d662a5833683bf33b03b3f4c3de98f34b2fde | [
"super(ShowCommand, self).__init__()\nself.device_name = device_name\nself.default_res_mes = '>'",
"self._clear_command()\nself._append_add_command('console columns 200')\nself._append_add_command('show config')\nself._append_add_command('console columns 80')\nGlobalModule.EM_LOGGER.debug('show command = %s' % (s... | <|body_start_0|>
super(ShowCommand, self).__init__()
self.device_name = device_name
self.default_res_mes = '>'
<|end_body_0|>
<|body_start_1|>
self._clear_command()
self._append_add_command('console columns 200')
self._append_add_command('show config')
self._appe... | Part class for setting NVR driver show-command | ShowCommand | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShowCommand:
"""Part class for setting NVR driver show-command"""
def __init__(self, device_name=None):
"""Constructor"""
<|body_0|>
def output_add_command(self):
"""Added Command line is output."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s... | stack_v2_sparse_classes_36k_train_002102 | 1,138 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, device_name=None)"
},
{
"docstring": "Added Command line is output.",
"name": "output_add_command",
"signature": "def output_add_command(self)"
}
] | 2 | null | Implement the Python class `ShowCommand` described below.
Class description:
Part class for setting NVR driver show-command
Method signatures and docstrings:
- def __init__(self, device_name=None): Constructor
- def output_add_command(self): Added Command line is output. | Implement the Python class `ShowCommand` described below.
Class description:
Part class for setting NVR driver show-command
Method signatures and docstrings:
- def __init__(self, device_name=None): Constructor
- def output_add_command(self): Added Command line is output.
<|skeleton|>
class ShowCommand:
"""Part c... | e550d1b5ec9419f1fb3eb6e058ce46b57c92ee2f | <|skeleton|>
class ShowCommand:
"""Part class for setting NVR driver show-command"""
def __init__(self, device_name=None):
"""Constructor"""
<|body_0|>
def output_add_command(self):
"""Added Command line is output."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShowCommand:
"""Part class for setting NVR driver show-command"""
def __init__(self, device_name=None):
"""Constructor"""
super(ShowCommand, self).__init__()
self.device_name = device_name
self.default_res_mes = '>'
def output_add_command(self):
"""Added Comma... | the_stack_v2_python_sparse | lib/SeparateDriver/NVRDriverParts/ShowCommand.py | lixiaochun/element-manager | train | 0 |
595956846bced4080fb1935dc1c756a0c6c2d89c | [
"if multi_label:\n self.model = OneVsRestClassifier(model)\nelse:\n self.model = model\nself.num_classes = num_classes\nself.multi_label = multi_label",
"check_training_data(train_set, None, weights=weights)\nif self.multi_label and weights is not None:\n raise ValueError('Sample weights are not supporte... | <|body_start_0|>
if multi_label:
self.model = OneVsRestClassifier(model)
else:
self.model = model
self.num_classes = num_classes
self.multi_label = multi_label
<|end_body_0|>
<|body_start_1|>
check_training_data(train_set, None, weights=weights)
i... | An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data. | SklearnClassifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnClassifier:
"""An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data."""
def __init__(self, model, num_classes, multi_label=False):
"""Parameters ----... | stack_v2_sparse_classes_36k_train_002103 | 7,350 | permissive | [
{
"docstring": "Parameters ---------- model : sklearn.base.BaseEstimator A scikit-learn estimator that implements `fit` and `predict_proba`. num_classes : int Number of classes which are to be trained and predicted. multi_label : bool, default=False If `False`, the classes are mutually exclusive, i.e. the predi... | 4 | null | Implement the Python class `SklearnClassifier` described below.
Class description:
An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data.
Method signatures and docstrings:
- def __init__(self... | Implement the Python class `SklearnClassifier` described below.
Class description:
An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data.
Method signatures and docstrings:
- def __init__(self... | 2bb16b7413f85f3b933887c7054db45b5652d3a2 | <|skeleton|>
class SklearnClassifier:
"""An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data."""
def __init__(self, model, num_classes, multi_label=False):
"""Parameters ----... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SklearnClassifier:
"""An adapter for using scikit-learn estimators. Notes ----- The multi-label settings currently assumes that the underlying classifer returns a sparse matrix if trained on sparse data."""
def __init__(self, model, num_classes, multi_label=False):
"""Parameters ---------- model ... | the_stack_v2_python_sparse | small_text/classifiers/classification.py | webis-de/small-text | train | 476 |
8beacd2fb4a27ad3059c9f1f90d9b70d29d8b605 | [
"if data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\n self.lambtha = float(lambtha)\nelse:\n if not isinstance(data, list):\n raise TypeError('data must be a list')\n if len(data) < 2:\n raise ValueError('data must contain multiple values')\n ... | <|body_start_0|>
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
self.lambtha = float(lambtha)
else:
if not isinstance(data, list):
raise TypeError('data must be a list')
if len(data) <... | Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time frame Raises: ValueError: If lambtha is not positive value TypeError: If ... | Poisson | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poisson:
"""Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time frame Raises: ValueError: If lambtha i... | stack_v2_sparse_classes_36k_train_002104 | 2,401 | no_license | [
{
"docstring": "Initializer",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates the value of PMF for a given number of ``successes`` Args: k (int): Is the number of successes Returns: float|0: The PMF value for k, 0 if k is out of range",... | 4 | stack_v2_sparse_classes_30k_train_013738 | Implement the Python class `Poisson` described below.
Class description:
Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time... | Implement the Python class `Poisson` described below.
Class description:
Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time... | 2ddae38cc25d914488451b8c30e1234f1fa55ebe | <|skeleton|>
class Poisson:
"""Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time frame Raises: ValueError: If lambtha i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poisson:
"""Poisson class represent the poisson distribution Note: If data is not given we use the given lambtha. Attributes: data (list): List of the data to be used to estimate the distribution lambtha (float): Expected number of occurences in a given time frame Raises: ValueError: If lambtha is not positiv... | the_stack_v2_python_sparse | math/0x03-probability/poisson.py | KoeusIss/holbertonschool-machine_learning | train | 0 |
b8a46ae822d846ec966db46130381b4f180f0f92 | [
"nodes = []\n\ndef preorder(node):\n if not node:\n nodes.append('null')\n else:\n nodes.append(str(node.val))\n preorder(node.left)\n preorder(node.right)\npreorder(root)\nreturn ','.join(nodes)",
"node_list = deque(data.split(','))\n\ndef rebuild():\n if not node_list:\n ... | <|body_start_0|>
nodes = []
def preorder(node):
if not node:
nodes.append('null')
else:
nodes.append(str(node.val))
preorder(node.left)
preorder(node.right)
preorder(root)
return ','.join(nodes)
<|en... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_002105 | 2,048 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
nodes = []
def preorder(node):
if not node:
nodes.append('null')
else:
nodes.append(str(node.val))
preord... | the_stack_v2_python_sparse | python_1_to_1000/297_Serialize_and_Deserialize_Binary_Tree.py | jakehoare/leetcode | train | 58 | |
1d9e97d9551137e600416e0d8f55e802b234d908 | [
"self.noun_to_adj = {}\nfor noun in noun_list:\n self.noun_to_adj[noun] = []\nself.tokenizer = TreebankWordTokenizer()\nself.bert_model = Bert()\nself.adj_tags = ['JJ', 'JJR', 'JJS']\nself.noun_tags = ['NN', 'NNS', 'NNP', 'NNPS']\nself.noun_list = noun_list\nself.adj_list = adj_list",
"for sent in sentences:\n... | <|body_start_0|>
self.noun_to_adj = {}
for noun in noun_list:
self.noun_to_adj[noun] = []
self.tokenizer = TreebankWordTokenizer()
self.bert_model = Bert()
self.adj_tags = ['JJ', 'JJR', 'JJS']
self.noun_tags = ['NN', 'NNS', 'NNP', 'NNPS']
self.noun_lis... | Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : List of nouns that we are working on. adj... | NounToAdjGen | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : L... | stack_v2_sparse_classes_36k_train_002106 | 4,308 | permissive | [
{
"docstring": "Initializing noun to adjective dictionary.",
"name": "__init__",
"signature": "def __init__(self, noun_list, adj_list)"
},
{
"docstring": "Add adjectives for nouns by perturbing sentence to noun_to_adj. Args: sentences : The list of sentences for which to look up for nouns and ad... | 4 | stack_v2_sparse_classes_30k_train_013300 | Implement the Python class `NounToAdjGen` described below.
Class description:
Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags... | Implement the Python class `NounToAdjGen` described below.
Class description:
Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags... | 8029927bfd45d378dd920c9b27f2ca0d06063fa5 | <|skeleton|>
class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NounToAdjGen:
"""Add adjectives for nouns in dictionary noun_to_adj. Attributes: noun_to_adj : Noun to adjective dictionary. tokenizer : An instance of nltk's tokenizer. bert_model : An instance of class bert. adj_tags : Tags of adjectives in nltk. noun_tags : Tags of nouns in nltk. noun_list : List of nouns ... | the_stack_v2_python_sparse | generate_noun_to_adj_list/noun_to_adj_gen.py | googleinterns/contextual-adjectives | train | 1 |
5c79c54386411207cfef6f34ce542db22f47cd5f | [
"self.m1 = defaultdict(list)\nself.m2 = {}\nself.nextid = 0",
"present = val in self.m1\nself.m1[val].append(self.nextid)\nself.m2[self.nextid] = val\nself.nextid += 1\nreturn not present",
"if val in self.m1:\n nid = self.m1[val].pop()\n if len(self.m1[val]) == 0:\n self.m1.pop(val)\n self.m2.p... | <|body_start_0|>
self.m1 = defaultdict(list)
self.m2 = {}
self.nextid = 0
<|end_body_0|>
<|body_start_1|>
present = val in self.m1
self.m1[val].append(self.nextid)
self.m2[self.nextid] = val
self.nextid += 1
return not present
<|end_body_1|>
<|body_start... | RandomizedSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_002107 | 3,207 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool",
"name": "insert",
"signature": ... | 4 | stack_v2_sparse_classes_30k_train_014884 | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | Implement the Python class `RandomizedSet` described below.
Class description:
Implement the RandomizedSet class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def insert(self, val): Inserts a value to the set. Returns true if the set did not already contain the specif... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type val: int :rtype: bool"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomizedSet:
def __init__(self):
"""Initialize your data structure here."""
self.m1 = defaultdict(list)
self.m2 = {}
self.nextid = 0
def insert(self, val):
"""Inserts a value to the set. Returns true if the set did not already contain the specified element. :type... | the_stack_v2_python_sparse | I/InsertDeleteGetRandomO1-Duplicatesallowed.py | bssrdf/pyleet | train | 2 | |
f601e61c67125e91b6a982437643c105556066f5 | [
"left = 0\nright = len(s) - 1\nwhile left < right:\n while left < right and (not s[left].isalnum()):\n left += 1\n while left < right and (not s[right].isalnum()):\n right -= 1\n if s[left].isalpha():\n if s[left].upper() != s[right].upper():\n return False\n elif s[left]... | <|body_start_0|>
left = 0
right = len(s) - 1
while left < right:
while left < right and (not s[left].isalnum()):
left += 1
while left < right and (not s[right].isalnum()):
right -= 1
if s[left].isalpha():
if s[le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, s: str) -> bool:
"""func: 双指针法 param {*} return {*}"""
<|body_0|>
def isPalindrome2(self, s: str) -> bool:
"""func: python处理字符串的方法 param {*} return {*}"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
left = 0
... | stack_v2_sparse_classes_36k_train_002108 | 1,761 | no_license | [
{
"docstring": "func: 双指针法 param {*} return {*}",
"name": "isPalindrome",
"signature": "def isPalindrome(self, s: str) -> bool"
},
{
"docstring": "func: python处理字符串的方法 param {*} return {*}",
"name": "isPalindrome2",
"signature": "def isPalindrome2(self, s: str) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s: str) -> bool: func: 双指针法 param {*} return {*}
- def isPalindrome2(self, s: str) -> bool: func: python处理字符串的方法 param {*} return {*} | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, s: str) -> bool: func: 双指针法 param {*} return {*}
- def isPalindrome2(self, s: str) -> bool: func: python处理字符串的方法 param {*} return {*}
<|skeleton|>
class S... | 62c9dc7f04d6f4122274e82427901af55af113f9 | <|skeleton|>
class Solution:
def isPalindrome(self, s: str) -> bool:
"""func: 双指针法 param {*} return {*}"""
<|body_0|>
def isPalindrome2(self, s: str) -> bool:
"""func: python处理字符串的方法 param {*} return {*}"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, s: str) -> bool:
"""func: 双指针法 param {*} return {*}"""
left = 0
right = len(s) - 1
while left < right:
while left < right and (not s[left].isalnum()):
left += 1
while left < right and (not s[right].isalnum... | the_stack_v2_python_sparse | 双指针/125.py | CodingProgrammer/Algorithm | train | 0 | |
fa0a45728d4897049d8e930031dcf0035b6966a7 | [
"w = len(matrix)\nif w == 0:\n return\nl = len(matrix[0])\nif l == 0:\n return\nlst = []\ntmp = [matrix[0][0]]\nfor i in range(1, l):\n tmp.append(tmp[i - 1] + matrix[0][i])\nlst.append(tmp)\nfor i in range(1, w):\n tmp = [matrix[i][0] + lst[i - 1][0]]\n for j in range(1, l):\n tmp.append(matr... | <|body_start_0|>
w = len(matrix)
if w == 0:
return
l = len(matrix[0])
if l == 0:
return
lst = []
tmp = [matrix[0][0]]
for i in range(1, l):
tmp.append(tmp[i - 1] + matrix[0][i])
lst.append(tmp)
for i in range(1, ... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_002109 | 1,310 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_010753 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 93cbb01487a61e37159e8bdd4bf40f623e131c19 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
w = len(matrix)
if w == 0:
return
l = len(matrix[0])
if l == 0:
return
lst = []
tmp = [matrix[0][0]]
for i in range(1, l):
tmp.append(t... | the_stack_v2_python_sparse | Leetcode_medium/dynamicprogramming/304.py | HenryBalthier/Python-Learning | train | 0 | |
41635d714f783bf5c868ad5ddc8d19d47470621d | [
"self.function_name = function_name\nself._patterns = reg_token_patterns\nself._arg_index = arg_index",
"reports: list[RegisterUsageReport] = []\nfor cursor in _walk_callsites(cursor, self.function_name):\n args_tokens: list[list[str]] = []\n arg: clang.cindex.Cursor\n for i, arg in enumerate(cursor.get_... | <|body_start_0|>
self.function_name = function_name
self._patterns = reg_token_patterns
self._arg_index = arg_index
<|end_body_0|>
<|body_start_1|>
reports: list[RegisterUsageReport] = []
for cursor in _walk_callsites(cursor, self.function_name):
args_tokens: list[li... | CallSiteAnalyzer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CallSiteAnalyzer:
def __init__(self, function_name: str, arg_index: int, reg_token_patterns: list[RegisterTokenPattern]):
"""Create a call-site analyzer for a given function. Token semantics: The list of tokens patterns is intended to be complete. If we ever hit a call site for the given... | stack_v2_sparse_classes_36k_train_002110 | 10,612 | permissive | [
{
"docstring": "Create a call-site analyzer for a given function. Token semantics: The list of tokens patterns is intended to be complete. If we ever hit a call site for the given function that does not match any of the token patterns, we will raise an exception. None values in a token pattern are interpreted a... | 2 | null | Implement the Python class `CallSiteAnalyzer` described below.
Class description:
Implement the CallSiteAnalyzer class.
Method signatures and docstrings:
- def __init__(self, function_name: str, arg_index: int, reg_token_patterns: list[RegisterTokenPattern]): Create a call-site analyzer for a given function. Token se... | Implement the Python class `CallSiteAnalyzer` described below.
Class description:
Implement the CallSiteAnalyzer class.
Method signatures and docstrings:
- def __init__(self, function_name: str, arg_index: int, reg_token_patterns: list[RegisterTokenPattern]): Create a call-site analyzer for a given function. Token se... | 51f6017b8425b14d5a4aa9abace8fe5a25ef08c8 | <|skeleton|>
class CallSiteAnalyzer:
def __init__(self, function_name: str, arg_index: int, reg_token_patterns: list[RegisterTokenPattern]):
"""Create a call-site analyzer for a given function. Token semantics: The list of tokens patterns is intended to be complete. If we ever hit a call site for the given... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CallSiteAnalyzer:
def __init__(self, function_name: str, arg_index: int, reg_token_patterns: list[RegisterTokenPattern]):
"""Create a call-site analyzer for a given function. Token semantics: The list of tokens patterns is intended to be complete. If we ever hit a call site for the given function that... | the_stack_v2_python_sparse | util/py/packages/lib/register_usage_report.py | lowRISC/opentitan | train | 2,077 | |
8b4393f08adbc912e4d9679e95e940343eda7c60 | [
"r = Element('a:r')\nSubElement(r, 'a:t')\ntry:\n self.endParaRPr.addprevious(r)\nexcept AttributeError:\n self.append(r)\nreturn r",
"children = self.getchildren()\nfor child in children:\n if child.tag == qn('a:r'):\n self.remove(child)\nreturn self",
"if not hasattr(self, 'pPr'):\n pPr = E... | <|body_start_0|>
r = Element('a:r')
SubElement(r, 'a:t')
try:
self.endParaRPr.addprevious(r)
except AttributeError:
self.append(r)
return r
<|end_body_0|>
<|body_start_1|>
children = self.getchildren()
for child in children:
if... | <a:p> custom element class | CT_TextParagraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_TextParagraph:
"""<a:p> custom element class"""
def add_r(self):
"""Return a newly appended <a:r> element."""
<|body_0|>
def remove_child_r_elms(self):
"""Return self after removing all <a:r> child elements."""
<|body_1|>
def get_or_add_pPr(self):... | stack_v2_sparse_classes_36k_train_002111 | 17,817 | permissive | [
{
"docstring": "Return a newly appended <a:r> element.",
"name": "add_r",
"signature": "def add_r(self)"
},
{
"docstring": "Return self after removing all <a:r> child elements.",
"name": "remove_child_r_elms",
"signature": "def remove_child_r_elms(self)"
},
{
"docstring": "Return... | 3 | stack_v2_sparse_classes_30k_train_002354 | Implement the Python class `CT_TextParagraph` described below.
Class description:
<a:p> custom element class
Method signatures and docstrings:
- def add_r(self): Return a newly appended <a:r> element.
- def remove_child_r_elms(self): Return self after removing all <a:r> child elements.
- def get_or_add_pPr(self): Ret... | Implement the Python class `CT_TextParagraph` described below.
Class description:
<a:p> custom element class
Method signatures and docstrings:
- def add_r(self): Return a newly appended <a:r> element.
- def remove_child_r_elms(self): Return self after removing all <a:r> child elements.
- def get_or_add_pPr(self): Ret... | 808f2475639f3d1471879ef2dacd151cfe8b89d3 | <|skeleton|>
class CT_TextParagraph:
"""<a:p> custom element class"""
def add_r(self):
"""Return a newly appended <a:r> element."""
<|body_0|>
def remove_child_r_elms(self):
"""Return self after removing all <a:r> child elements."""
<|body_1|>
def get_or_add_pPr(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_TextParagraph:
"""<a:p> custom element class"""
def add_r(self):
"""Return a newly appended <a:r> element."""
r = Element('a:r')
SubElement(r, 'a:t')
try:
self.endParaRPr.addprevious(r)
except AttributeError:
self.append(r)
return... | the_stack_v2_python_sparse | pptx/oxml/text.py | amisa/python-pptx | train | 0 |
ef763c30a3c3420033842057c41c3176f5da2c48 | [
"longest = ''\npalindromes = set()\nfor i in range(len(s)):\n for j in range(len(s) - 1, i - 1, -1):\n if j - i >= len(longest):\n is_palindrome = self.isPalindrome(s, i, j, palindromes)\n if is_palindrome:\n palindromes.add((i, j))\n if len(s[i:j + 1]) ... | <|body_start_0|>
longest = ''
palindromes = set()
for i in range(len(s)):
for j in range(len(s) - 1, i - 1, -1):
if j - i >= len(longest):
is_palindrome = self.isPalindrome(s, i, j, palindromes)
if is_palindrome:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str"""
<|body_0|>
def isPalindrome(self, s, left, right, palindromes):
""":param s: :param left: :param right: :param palindromes... | stack_v2_sparse_classes_36k_train_002112 | 1,431 | no_license | [
{
"docstring": "Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":param s: :param left: :param right: :param palindromes: :return:",
"name": "isPali... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str
- def isPalindrome(self, s, left, right, palindro... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str
- def isPalindrome(self, s, left, right, palindro... | f38a289a65cca1806341c01e4525eb2727336fe4 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
"""Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str"""
<|body_0|>
def isPalindrome(self, s, left, right, palindromes):
""":param s: :param left: :param right: :param palindromes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
"""Find the longest palindromic substring occurring in the string provided :type s: str :rtype: str"""
longest = ''
palindromes = set()
for i in range(len(s)):
for j in range(len(s) - 1, i - 1, -1):
if j - i ... | the_stack_v2_python_sparse | Medium/5-longest-palidromic-substring.py | NjengaSaruni/LeetCode-Python-Solutions | train | 0 | |
305572fe9bd59dbccba654884516e2bf5b0421d3 | [
"super().__init__()\nself.hypo_parameters = dict(hypo_module.meta_named_parameters())\nself.representation_dim = 0\nself.rank = rank\nself.names = []\nself.nets = nn.ModuleList()\nself.param_shapes = []\nfor name, param in self.hypo_parameters.items():\n self.names.append(name)\n self.param_shapes.append(para... | <|body_start_0|>
super().__init__()
self.hypo_parameters = dict(hypo_module.meta_named_parameters())
self.representation_dim = 0
self.rank = rank
self.names = []
self.nets = nn.ModuleList()
self.param_shapes = []
for name, param in self.hypo_parameters.ite... | LowRankHyperNetwork | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LowRankHyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False, rank=10, nonlinearity='relu'):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidd... | stack_v2_sparse_classes_36k_train_002113 | 7,605 | no_license | [
{
"docstring": "Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: Number of hidden units in hypernetwork hypo_module: MetaModule. The module whose parameters are predicted.",
"name": "__init__",
"signature": "def __in... | 2 | stack_v2_sparse_classes_30k_train_014530 | Implement the Python class `LowRankHyperNetwork` described below.
Class description:
Implement the LowRankHyperNetwork class.
Method signatures and docstrings:
- def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False, rank=10, nonlinearity='relu'): Args: hyper_in_f... | Implement the Python class `LowRankHyperNetwork` described below.
Class description:
Implement the LowRankHyperNetwork class.
Method signatures and docstrings:
- def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False, rank=10, nonlinearity='relu'): Args: hyper_in_f... | 1c2ba87c6b2cf89f14ea43ec14b179579cbc9220 | <|skeleton|>
class LowRankHyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False, rank=10, nonlinearity='relu'):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidd... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LowRankHyperNetwork:
def __init__(self, hyper_in_features, hyper_hidden_layers, hyper_hidden_features, hypo_module, linear=False, rank=10, nonlinearity='relu'):
"""Args: hyper_in_features: In features of hypernetwork hyper_hidden_layers: Number of hidden layers in hypernetwork hyper_hidden_features: N... | the_stack_v2_python_sparse | colf/supplementary_colf/code/hyperlayers.py | cameronosmith/cameronosmith.github.io | train | 0 | |
9fb96ac46b5c682c1a3bbee8dbfd2f4b3c1272c9 | [
"f = self.cleaned_data['avatar_upload']\nif f.size > self.MAX_FILE_SIZE:\n raise ValidationError(_('The file is too large.'))\ncontent_type = f.content_type.split('/')[0]\nif content_type != 'image':\n raise ValidationError(_('Only images are supported.'))\nreturn f",
"storage = DefaultStorage()\nusername =... | <|body_start_0|>
f = self.cleaned_data['avatar_upload']
if f.size > self.MAX_FILE_SIZE:
raise ValidationError(_('The file is too large.'))
content_type = f.content_type.split('/')[0]
if content_type != 'image':
raise ValidationError(_('Only images are supported.')... | The FileUploadService configuration form. | FileUploadServiceForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileUploadServiceForm:
"""The FileUploadService configuration form."""
def clean_file(self):
"""Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is valid. Raises: django.core.exceptions.ValidationError: Rai... | stack_v2_sparse_classes_36k_train_002114 | 6,132 | no_license | [
{
"docstring": "Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is valid. Raises: django.core.exceptions.ValidationError: Raised if the file is too large or the incorrect MIME type.",
"name": "clean_file",
"signature": "def c... | 2 | null | Implement the Python class `FileUploadServiceForm` described below.
Class description:
The FileUploadService configuration form.
Method signatures and docstrings:
- def clean_file(self): Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is v... | Implement the Python class `FileUploadServiceForm` described below.
Class description:
The FileUploadService configuration form.
Method signatures and docstrings:
- def clean_file(self): Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is v... | 99ea69d80a3a393b0da4da3152ef26e808dd8487 | <|skeleton|>
class FileUploadServiceForm:
"""The FileUploadService configuration form."""
def clean_file(self):
"""Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is valid. Raises: django.core.exceptions.ValidationError: Rai... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileUploadServiceForm:
"""The FileUploadService configuration form."""
def clean_file(self):
"""Ensure the uploaded file is an image of an appropriate size. Returns: django.core.files.UploadedFile: The uploaded file, if it is valid. Raises: django.core.exceptions.ValidationError: Raised if the fi... | the_stack_v2_python_sparse | djblets/avatars/services/file_upload.py | chipx86/djblets | train | 2 |
c59926268f36b0129108b2d05a7c3f0c710c1cf8 | [
"joint_world = np.asarray(joint_world)\nR = np.asarray(camera_intrinsic['R'])\nT = np.asarray(camera_intrinsic['T'])\njoint_num = len(joint_world)\njoint_cam = np.dot(R, (joint_world - T).T).T\nreturn joint_cam",
"joint_world = np.asarray(joint_world)\nR = np.asarray(camera_intrinsic['R'])\nT = np.asarray(camera_... | <|body_start_0|>
joint_world = np.asarray(joint_world)
R = np.asarray(camera_intrinsic['R'])
T = np.asarray(camera_intrinsic['T'])
joint_num = len(joint_world)
joint_cam = np.dot(R, (joint_world - T).T).T
return joint_cam
<|end_body_0|>
<|body_start_1|>
joint_wor... | CameraTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CameraTools:
def convert_wc_to_cc(joint_world):
"""世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:"""
<|body_0|>
def convert_cc_to_wc(joint_world):
"""相机坐标系 -> 世界坐标系: inv(R) * pt +T joint_cam = np.dot(inv(R), joint_world.T)+T :retu... | stack_v2_sparse_classes_36k_train_002115 | 6,618 | no_license | [
{
"docstring": "世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:",
"name": "convert_wc_to_cc",
"signature": "def convert_wc_to_cc(joint_world)"
},
{
"docstring": "相机坐标系 -> 世界坐标系: inv(R) * pt +T joint_cam = np.dot(inv(R), joint_world.T)+T :return:",
"name": ... | 4 | null | Implement the Python class `CameraTools` described below.
Class description:
Implement the CameraTools class.
Method signatures and docstrings:
- def convert_wc_to_cc(joint_world): 世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:
- def convert_cc_to_wc(joint_world): 相机坐标系 -> 世界坐标系: ... | Implement the Python class `CameraTools` described below.
Class description:
Implement the CameraTools class.
Method signatures and docstrings:
- def convert_wc_to_cc(joint_world): 世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:
- def convert_cc_to_wc(joint_world): 相机坐标系 -> 世界坐标系: ... | 513d3e57f4e0fce72ca4ecd1f30be2d261ee9260 | <|skeleton|>
class CameraTools:
def convert_wc_to_cc(joint_world):
"""世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:"""
<|body_0|>
def convert_cc_to_wc(joint_world):
"""相机坐标系 -> 世界坐标系: inv(R) * pt +T joint_cam = np.dot(inv(R), joint_world.T)+T :retu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CameraTools:
def convert_wc_to_cc(joint_world):
"""世界坐标系 -> 相机坐标系: R * (pt - T): joint_cam = np.dot(R, (joint_world - T).T).T :return:"""
joint_world = np.asarray(joint_world)
R = np.asarray(camera_intrinsic['R'])
T = np.asarray(camera_intrinsic['T'])
joint_num = len(jo... | the_stack_v2_python_sparse | python/opencv/img_tr.py | juechen-zzz/learngit | train | 8 | |
921dcd021a8caaf231e1c03cc513c97845c439ac | [
"users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}\nusers2 = {'2': 'Sam', '6': 'Kate'}\nusers.update(users2)\nkey = '2'\nprint(TestDict.test7_dict_update.__doc__)\nassert users.get(key) == 'Sam'\nprint('test7_dict_update passed')",
"users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}\nkey = '5'\nuser = users.pop(key, 'No... | <|body_start_0|>
users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}
users2 = {'2': 'Sam', '6': 'Kate'}
users.update(users2)
key = '2'
print(TestDict.test7_dict_update.__doc__)
assert users.get(key) == 'Sam'
print('test7_dict_update passed')
<|end_body_0|>
<|body_star... | TestDict | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
<|body_0|>
def test8_dict_pop(self):
"""Тест 'test8_dict_pop' проверяет удаление элементе из словаря"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002116 | 928 | no_license | [
{
"docstring": "Тест 'test7_dict_update' проверяет объединение двух словарей",
"name": "test7_dict_update",
"signature": "def test7_dict_update(self)"
},
{
"docstring": "Тест 'test8_dict_pop' проверяет удаление элементе из словаря",
"name": "test8_dict_pop",
"signature": "def test8_dict_... | 2 | stack_v2_sparse_classes_30k_train_010526 | Implement the Python class `TestDict` described below.
Class description:
Implement the TestDict class.
Method signatures and docstrings:
- def test7_dict_update(self): Тест 'test7_dict_update' проверяет объединение двух словарей
- def test8_dict_pop(self): Тест 'test8_dict_pop' проверяет удаление элементе из словаря | Implement the Python class `TestDict` described below.
Class description:
Implement the TestDict class.
Method signatures and docstrings:
- def test7_dict_update(self): Тест 'test7_dict_update' проверяет объединение двух словарей
- def test8_dict_pop(self): Тест 'test8_dict_pop' проверяет удаление элементе из словаря... | 49fd8e5b4da76b1ab9c21e34ce89d0082bed5e56 | <|skeleton|>
class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
<|body_0|>
def test8_dict_pop(self):
"""Тест 'test8_dict_pop' проверяет удаление элементе из словаря"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDict:
def test7_dict_update(self):
"""Тест 'test7_dict_update' проверяет объединение двух словарей"""
users = {'1': 'Tom', '3': 'Bob', '5': 'Alice'}
users2 = {'2': 'Sam', '6': 'Kate'}
users.update(users2)
key = '2'
print(TestDict.test7_dict_update.__doc__)
... | the_stack_v2_python_sparse | Homework_1_3/test_dict.py | Kyanty/qa_automation | train | 0 | |
0f62933246114deed5623f7496d381796a012ae7 | [
"super().__init__(parent)\nself.other_sources = other_sources\nself.item = None\nself.name = None\nself.source = None\nbutton = tkinter.Button(self, text='Open file...', command=self.on_select_file)\nbutton.pack(fill='both', expand=True)\nif self.other_sources:\n tkinter.Label(self, text='Other Sources:').pack(f... | <|body_start_0|>
super().__init__(parent)
self.other_sources = other_sources
self.item = None
self.name = None
self.source = None
button = tkinter.Button(self, text='Open file...', command=self.on_select_file)
button.pack(fill='both', expand=True)
if self.... | tkSourceSelect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
<|body_0|>
def on_select_file(self):
"""TODO: add docstring"""
<|body_1|>
def on_select_other(self, item):
"""TODO: add docstring"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k_train_002117 | 5,415 | no_license | [
{
"docstring": "TODO: add docstring",
"name": "__init__",
"signature": "def __init__(self, parent, other_sources=None)"
},
{
"docstring": "TODO: add docstring",
"name": "on_select_file",
"signature": "def on_select_file(self)"
},
{
"docstring": "TODO: add docstring",
"name": ... | 3 | stack_v2_sparse_classes_30k_train_012199 | Implement the Python class `tkSourceSelect` described below.
Class description:
Implement the tkSourceSelect class.
Method signatures and docstrings:
- def __init__(self, parent, other_sources=None): TODO: add docstring
- def on_select_file(self): TODO: add docstring
- def on_select_other(self, item): TODO: add docst... | Implement the Python class `tkSourceSelect` described below.
Class description:
Implement the tkSourceSelect class.
Method signatures and docstrings:
- def __init__(self, parent, other_sources=None): TODO: add docstring
- def on_select_file(self): TODO: add docstring
- def on_select_other(self, item): TODO: add docst... | 237cb3c74ff193557addcf5bb43af4b87cb8df4e | <|skeleton|>
class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
<|body_0|>
def on_select_file(self):
"""TODO: add docstring"""
<|body_1|>
def on_select_other(self, item):
"""TODO: add docstring"""
<|body_2|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class tkSourceSelect:
def __init__(self, parent, other_sources=None):
"""TODO: add docstring"""
super().__init__(parent)
self.other_sources = other_sources
self.item = None
self.name = None
self.source = None
button = tkinter.Button(self, text='Open file...', ... | the_stack_v2_python_sparse | test03/tkCamera.py | ss820938ss/pythonProject | train | 0 | |
a64070b7ffb6e15f16acce48aca79358f52a620b | [
"super(STFTLoss, self).__init__()\nself.fft_size = fft_size\nself.shift_size = shift_size\nself.win_length = win_length\nself.register_buffer('window', getattr(torch, window)(win_length))\nself.spectral_convergenge_loss = SpectralConvergengeLoss()\nself.log_stft_magnitude_loss = LogSTFTMagnitudeLoss()",
"x_mag = ... | <|body_start_0|>
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = win_length
self.register_buffer('window', getattr(torch, window)(win_length))
self.spectral_convergenge_loss = SpectralConvergengeLoss()
self.... | STFT loss module. | STFTLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal ... | stack_v2_sparse_classes_36k_train_002118 | 24,374 | no_license | [
{
"docstring": "Initialize STFT loss module.",
"name": "__init__",
"signature": "def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window')"
},
{
"docstring": "Calculate forward propagation. Args: x (Tensor): Predicted signal (B, T). y (Tensor): Groundtruth signal (B... | 2 | null | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tenso... | Implement the Python class `STFTLoss` described below.
Class description:
STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'): Initialize STFT loss module.
- def forward(self, x, y): Calculate forward propagation. Args: x (Tenso... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
<|body_0|>
def forward(self, x, y):
"""Calculate forward propagation. Args: x (Tensor): Predicted signal ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class STFTLoss:
"""STFT loss module."""
def __init__(self, fft_size=1024, shift_size=120, win_length=600, window='hann_window'):
"""Initialize STFT loss module."""
super(STFTLoss, self).__init__()
self.fft_size = fft_size
self.shift_size = shift_size
self.win_length = wi... | the_stack_v2_python_sparse | generated/test_facebookresearch_denoiser.py | jansel/pytorch-jit-paritybench | train | 35 |
9256abf33dcfba01e675007370f9744a7c164adf | [
"if d is None and t is None:\n return None\njoint = t.copy() if t else {}\njoint.update(d)\nif 'ML_half_mosaicity_deg' in joint:\n assert 'ML_domain_size_ang' in joint\n if joint['ML_half_mosaicity_deg'] is None or joint['ML_domain_size_ang'] is None:\n assert joint['ML_half_mosaicity_deg'] is None ... | <|body_start_0|>
if d is None and t is None:
return None
joint = t.copy() if t else {}
joint.update(d)
if 'ML_half_mosaicity_deg' in joint:
assert 'ML_domain_size_ang' in joint
if joint['ML_half_mosaicity_deg'] is None or joint['ML_domain_size_ang'] is... | CrystalFactory | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrystalFactory:
def from_dict(d, t=None):
"""Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model"""
<|body_0|>
def from_mosflm_matrix(mosflm_A_matrix, unit_cell=None, wavelength=None, sp... | stack_v2_sparse_classes_36k_train_002119 | 4,636 | permissive | [
{
"docstring": "Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model",
"name": "from_dict",
"signature": "def from_dict(d, t=None)"
},
{
"docstring": "Create a crystal_model from a Mosflm A matrix (a*, b*, c*... | 2 | null | Implement the Python class `CrystalFactory` described below.
Class description:
Implement the CrystalFactory class.
Method signatures and docstrings:
- def from_dict(d, t=None): Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model... | Implement the Python class `CrystalFactory` described below.
Class description:
Implement the CrystalFactory class.
Method signatures and docstrings:
- def from_dict(d, t=None): Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model... | 2fc8ffadbf67d0611e2d7affcf50d0f23abfc16f | <|skeleton|>
class CrystalFactory:
def from_dict(d, t=None):
"""Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model"""
<|body_0|>
def from_mosflm_matrix(mosflm_A_matrix, unit_cell=None, wavelength=None, sp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrystalFactory:
def from_dict(d, t=None):
"""Convert the dictionary to a crystal model Params: d The dictionary of parameters t The template dictionary to use Returns: The crystal model"""
if d is None and t is None:
return None
joint = t.copy() if t else {}
joint.u... | the_stack_v2_python_sparse | src/dxtbx/model/crystal.py | cctbx/dxtbx | train | 2 | |
a8d8c7208b0fd396c80c17305899a36b656a75c1 | [
"self.encoding = encoding\nself.flush = flush\nself.ofile = ofile",
"for ostring in ostrings:\n if isinstance(ostring, unicode):\n ostring = ostring.encode(self.encoding)\n (print >> self.ofile, ostring)\nprint >> self.ofile\nif self.flush:\n self.ofile.flush()"
] | <|body_start_0|>
self.encoding = encoding
self.flush = flush
self.ofile = ofile
<|end_body_0|>
<|body_start_1|>
for ostring in ostrings:
if isinstance(ostring, unicode):
ostring = ostring.encode(self.encoding)
(print >> self.ofile, ostring)
... | Class for outputing strings in appropriate encoding. | AltFileOutput | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AltFileOutput:
"""Class for outputing strings in appropriate encoding."""
def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False):
"""Create an instance of AltFileOutput."""
<|body_0|>
def fprint(self, *ostrings):
"""Encode ostrings and print... | stack_v2_sparse_classes_36k_train_002120 | 6,891 | permissive | [
{
"docstring": "Create an instance of AltFileOutput.",
"name": "__init__",
"signature": "def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False)"
},
{
"docstring": "Encode ostrings and print them, flushing the output if necessary. If you don't want to redirect fprint's outpu... | 2 | stack_v2_sparse_classes_30k_train_015330 | Implement the Python class `AltFileOutput` described below.
Class description:
Class for outputing strings in appropriate encoding.
Method signatures and docstrings:
- def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False): Create an instance of AltFileOutput.
- def fprint(self, *ostrings): Enco... | Implement the Python class `AltFileOutput` described below.
Class description:
Class for outputing strings in appropriate encoding.
Method signatures and docstrings:
- def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False): Create an instance of AltFileOutput.
- def fprint(self, *ostrings): Enco... | ac645fb41260b86491b17fbc50e5ea3300dc28b7 | <|skeleton|>
class AltFileOutput:
"""Class for outputing strings in appropriate encoding."""
def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False):
"""Create an instance of AltFileOutput."""
<|body_0|>
def fprint(self, *ostrings):
"""Encode ostrings and print... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AltFileOutput:
"""Class for outputing strings in appropriate encoding."""
def __init__(self, encoding=DEFAULT_LANG, ofile=DEFAULT_OUTPUT, flush=False):
"""Create an instance of AltFileOutput."""
self.encoding = encoding
self.flush = flush
self.ofile = ofile
def fprint... | the_stack_v2_python_sparse | scripts/lib/python/alt_fio.py | WladimirSidorenko/TextNormalization | train | 1 |
5e3f5de9d49a6684c121640e1ba4e59ff841e59f | [
"Parametre.__init__(self, 'voir', 'view')\nself.schema = ''\nself.aide_courte = 'visualise les options du joueur'\nself.aide_longue = \"Cette commande permet de voir l'état actuel des options que vous pouvez éditer avec la commande %options%. Elle donne aussi un aperçu des valeurs disponibles.\"",
"langue = perso... | <|body_start_0|>
Parametre.__init__(self, 'voir', 'view')
self.schema = ''
self.aide_courte = 'visualise les options du joueur'
self.aide_longue = "Cette commande permet de voir l'état actuel des options que vous pouvez éditer avec la commande %options%. Elle donne aussi un aperçu des va... | Commande 'options voir'. | PrmVoir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVoir:
"""Commande 'options voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametre.__ini... | stack_v2_sparse_classes_36k_train_002121 | 3,294 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002349 | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'options voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'options voir'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmVoir:
"""Commande 'options voir'.... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVoir:
"""Commande 'options voir'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmVoir:
"""Commande 'options voir'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'voir', 'view')
self.schema = ''
self.aide_courte = 'visualise les options du joueur'
self.aide_longue = "Cette commande permet de voir l'état actue... | the_stack_v2_python_sparse | src/primaires/joueur/commandes/options/voir.py | vincent-lg/tsunami | train | 5 |
efa97d371bfd44da5e8a603f5e56499f7c0fd67d | [
"filtered = [x for x in self if addr in x.ucqm]\nblocks = sorted(filtered, key=lambda x: x.ucqm[addr]['mov_rssi'], reverse=True)\nreturn ResourcePool(blocks)",
"blocks = []\nfor block in self.__iter__():\n if block.channel == channel:\n blocks.append(block)\nreturn ResourcePool(blocks)",
"blocks = []\... | <|body_start_0|>
filtered = [x for x in self if addr in x.ucqm]
blocks = sorted(filtered, key=lambda x: x.ucqm[addr]['mov_rssi'], reverse=True)
return ResourcePool(blocks)
<|end_body_0|>
<|body_start_1|>
blocks = []
for block in self.__iter__():
if block.channel == c... | Resource pool. This extends the list in order to add a few filtering and sorting methods | ResourcePool | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourcePool:
"""Resource pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rssi(self, addr):
"""Return list sorted by rssi for the specific address."""
<|body_0|>
def filter_by_channel(self, channel):
"""Return list s... | stack_v2_sparse_classes_36k_train_002122 | 7,116 | permissive | [
{
"docstring": "Return list sorted by rssi for the specific address.",
"name": "sort_by_rssi",
"signature": "def sort_by_rssi(self, addr)"
},
{
"docstring": "Return list sorted filtered by channel.",
"name": "filter_by_channel",
"signature": "def filter_by_channel(self, channel)"
},
... | 5 | stack_v2_sparse_classes_30k_train_003607 | Implement the Python class `ResourcePool` described below.
Class description:
Resource pool. This extends the list in order to add a few filtering and sorting methods
Method signatures and docstrings:
- def sort_by_rssi(self, addr): Return list sorted by rssi for the specific address.
- def filter_by_channel(self, ch... | Implement the Python class `ResourcePool` described below.
Class description:
Resource pool. This extends the list in order to add a few filtering and sorting methods
Method signatures and docstrings:
- def sort_by_rssi(self, addr): Return list sorted by rssi for the specific address.
- def filter_by_channel(self, ch... | ad81b04937ff1db82ea2a4e8218422ca3437401c | <|skeleton|>
class ResourcePool:
"""Resource pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rssi(self, addr):
"""Return list sorted by rssi for the specific address."""
<|body_0|>
def filter_by_channel(self, channel):
"""Return list s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourcePool:
"""Resource pool. This extends the list in order to add a few filtering and sorting methods"""
def sort_by_rssi(self, addr):
"""Return list sorted by rssi for the specific address."""
filtered = [x for x in self if addr in x.ucqm]
blocks = sorted(filtered, key=lambda... | the_stack_v2_python_sparse | empower/managers/ranmanager/lvapp/resourcepool.py | 5g-empower/empower-runtime | train | 55 |
edb589c887326d71458744ffd2c6edb1de53bbfa | [
"self.max_items = 100\nself.count = 0\nself.values = ['' for i in range(self.max_items)]\nself.priorities = [float('-inf') for i in range(self.max_items)]",
"self.values[self.count] = value\nself.priorities[self.count] = priority\nself.count += 1\nindex = self.count - 1\nwhile index != 0:\n parent = (index - 1... | <|body_start_0|>
self.max_items = 100
self.count = 0
self.values = ['' for i in range(self.max_items)]
self.priorities = [float('-inf') for i in range(self.max_items)]
<|end_body_0|>
<|body_start_1|>
self.values[self.count] = value
self.priorities[self.count] = priority
... | PriorityQueue | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriorityQueue:
def __init__(self, capacity):
"""Make arrays to hold the priority queue."""
<|body_0|>
def push(self, value, priority):
"""Add the item to the priority queue."""
<|body_1|>
def pop(self):
"""Remove the highest priority item from th... | stack_v2_sparse_classes_36k_train_002123 | 6,317 | permissive | [
{
"docstring": "Make arrays to hold the priority queue.",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": "Add the item to the priority queue.",
"name": "push",
"signature": "def push(self, value, priority)"
},
{
"docstring": "Remove the highest ... | 3 | null | Implement the Python class `PriorityQueue` described below.
Class description:
Implement the PriorityQueue class.
Method signatures and docstrings:
- def __init__(self, capacity): Make arrays to hold the priority queue.
- def push(self, value, priority): Add the item to the priority queue.
- def pop(self): Remove the... | Implement the Python class `PriorityQueue` described below.
Class description:
Implement the PriorityQueue class.
Method signatures and docstrings:
- def __init__(self, capacity): Make arrays to hold the priority queue.
- def push(self, value, priority): Add the item to the priority queue.
- def pop(self): Remove the... | 9ffefcf5418488c43a57797904ecfee9c3e4f84b | <|skeleton|>
class PriorityQueue:
def __init__(self, capacity):
"""Make arrays to hold the priority queue."""
<|body_0|>
def push(self, value, priority):
"""Add the item to the priority queue."""
<|body_1|>
def pop(self):
"""Remove the highest priority item from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriorityQueue:
def __init__(self, capacity):
"""Make arrays to hold the priority queue."""
self.max_items = 100
self.count = 0
self.values = ['' for i in range(self.max_items)]
self.priorities = [float('-inf') for i in range(self.max_items)]
def push(self, value, p... | the_stack_v2_python_sparse | algs2e_python/Chapter 06/python/priority_queue.py | bqmoreland/EASwift | train | 0 | |
aa5692655000bf7b66f3ee480f02260c5d6c5b33 | [
"self.capacity = capacity\nself.hash = {}\nself.head, self.tail = (LinkNode(None, None), LinkNode(None, None))\nself.head.next, self.tail.prev = (self.tail, self.head)",
"if key not in self.hash:\n return -1\ngetNode = self.hash[key]\ngetNode.prev.next, getNode.next.prev = (getNode.next, getNode.prev)\ngetNode... | <|body_start_0|>
self.capacity = capacity
self.hash = {}
self.head, self.tail = (LinkNode(None, None), LinkNode(None, None))
self.head.next, self.tail.prev = (self.tail, self.head)
<|end_body_0|>
<|body_start_1|>
if key not in self.hash:
return -1
getNode = s... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k_train_002124 | 1,508 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_017588 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 762162a53a1032b627f83f00a9ef6a55b53f023a | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.capacity = capacity
self.hash = {}
self.head, self.tail = (LinkNode(None, None), LinkNode(None, None))
self.head.next, self.tail.prev = (self.tail, self.head)
def get(self, key):
""":typ... | the_stack_v2_python_sparse | 146_LRU_Cache.py | luchen29/Algorithm-Practice | train | 0 | |
89b289f1e77d348df3b4507a6d7584e26d1b9294 | [
"flag = Flag()\nassert not flag\n\ndef trigger_flag(after):\n yield env.timeout(after)\n yield flag.set()\nenv.process(trigger_flag(5))\nyield flag\nassert env.now == 5",
"assert env.now == 0\n\nasync def ping_pong(value):\n return value\nresult = (yield ping_pong(3))\nassert result == 3\nassert env.now ... | <|body_start_0|>
flag = Flag()
assert not flag
def trigger_flag(after):
yield env.timeout(after)
yield flag.set()
env.process(trigger_flag(5))
yield flag
assert env.now == 5
<|end_body_0|>
<|body_start_1|>
assert env.now == 0
asy... | TestUsim2Simpy | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
<|body_0|>
def test_coroutine(self, env):
"""Can yield-as-await coroutines"""
<|body_1|>
def test_time(self, env):
"""Can yield-as-await time expressions"""
<|body_... | stack_v2_sparse_classes_36k_train_002125 | 2,166 | permissive | [
{
"docstring": "Can trigger and set flags",
"name": "test_flag",
"signature": "def test_flag(self, env)"
},
{
"docstring": "Can yield-as-await coroutines",
"name": "test_coroutine",
"signature": "def test_coroutine(self, env)"
},
{
"docstring": "Can yield-as-await time expression... | 6 | stack_v2_sparse_classes_30k_train_008699 | Implement the Python class `TestUsim2Simpy` described below.
Class description:
Implement the TestUsim2Simpy class.
Method signatures and docstrings:
- def test_flag(self, env): Can trigger and set flags
- def test_coroutine(self, env): Can yield-as-await coroutines
- def test_time(self, env): Can yield-as-await time... | Implement the Python class `TestUsim2Simpy` described below.
Class description:
Implement the TestUsim2Simpy class.
Method signatures and docstrings:
- def test_flag(self, env): Can trigger and set flags
- def test_coroutine(self, env): Can yield-as-await coroutines
- def test_time(self, env): Can yield-as-await time... | 28615825fbe23140bbf9efe63fb18410f9453441 | <|skeleton|>
class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
<|body_0|>
def test_coroutine(self, env):
"""Can yield-as-await coroutines"""
<|body_1|>
def test_time(self, env):
"""Can yield-as-await time expressions"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestUsim2Simpy:
def test_flag(self, env):
"""Can trigger and set flags"""
flag = Flag()
assert not flag
def trigger_flag(after):
yield env.timeout(after)
yield flag.set()
env.process(trigger_flag(5))
yield flag
assert env.now == ... | the_stack_v2_python_sparse | usim_pytest/test_usimpy/test_compatibility.py | MaineKuehn/usim | train | 18 | |
1c16d3d49b11542b93f0fd51b35f008385499165 | [
"try:\n self.teaClassPractice = dict()\n self.sqlhandler = None\n self.teaId = self.get_argument('teaId')\n print(self.teaId)\n if self.getTeaClass():\n self.write(self.teaClassPractice)\n self.finish()\n else:\n raise RuntimeError\nexcept Exception:\n self.write('error')\n... | <|body_start_0|>
try:
self.teaClassPractice = dict()
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
print(self.teaId)
if self.getTeaClass():
self.write(self.teaClassPractice)
self.finish()
els... | TeaGetClassListRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
<|body_0|>
def getTeaClass(self):
"""返回老师的习题列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.teaClassPractice = dict()
self.sqlhandler = None
... | stack_v2_sparse_classes_36k_train_002126 | 2,285 | no_license | [
{
"docstring": "获取练习题列表,返回给老师客户端",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "返回老师的习题列表",
"name": "getTeaClass",
"signature": "def getTeaClass(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009371 | Implement the Python class `TeaGetClassListRequestHandler` described below.
Class description:
Implement the TeaGetClassListRequestHandler class.
Method signatures and docstrings:
- def get(self): 获取练习题列表,返回给老师客户端
- def getTeaClass(self): 返回老师的习题列表 | Implement the Python class `TeaGetClassListRequestHandler` described below.
Class description:
Implement the TeaGetClassListRequestHandler class.
Method signatures and docstrings:
- def get(self): 获取练习题列表,返回给老师客户端
- def getTeaClass(self): 返回老师的习题列表
<|skeleton|>
class TeaGetClassListRequestHandler:
def get(self)... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
<|body_0|>
def getTeaClass(self):
"""返回老师的习题列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
try:
self.teaClassPractice = dict()
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
print(self.teaId)
if self.getTeaClass():
self.writ... | the_stack_v2_python_sparse | app/src/main/pythonWork/TeaGetClassListRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
6f4ceabd22b7742d57b38049f7f0cf85eceec219 | [
"if not root:\n return None\nhead, tail = self.helper(root)\nhead.left = tail\ntail.right = head\nreturn head",
"head, tail = (curr, curr)\nif curr.left:\n lhead, ltail = self.helper(curr.left)\n ltail.right = curr\n curr.left = ltail\n head = lhead\nif curr.right:\n rhead, rtail = self.helper(c... | <|body_start_0|>
if not root:
return None
head, tail = self.helper(root)
head.left = tail
tail.right = head
return head
<|end_body_0|>
<|body_start_1|>
head, tail = (curr, curr)
if curr.left:
lhead, ltail = self.helper(curr.left)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Left point to prev right point to after"""
<|body_0|>
def helper(self, curr):
"""Idea: Construct a DLL for each subtree, then return the head and tail"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_002127 | 1,050 | no_license | [
{
"docstring": ":type root: Node :rtype: Node Left point to prev right point to after",
"name": "treeToDoublyList",
"signature": "def treeToDoublyList(self, root)"
},
{
"docstring": "Idea: Construct a DLL for each subtree, then return the head and tail",
"name": "helper",
"signature": "d... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node Left point to prev right point to after
- def helper(self, curr): Idea: Construct a DLL for each subtree, then ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def treeToDoublyList(self, root): :type root: Node :rtype: Node Left point to prev right point to after
- def helper(self, curr): Idea: Construct a DLL for each subtree, then ret... | 1a3c1f4d6e9d3444039f087763b93241f4ba7892 | <|skeleton|>
class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Left point to prev right point to after"""
<|body_0|>
def helper(self, curr):
"""Idea: Construct a DLL for each subtree, then return the head and tail"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def treeToDoublyList(self, root):
""":type root: Node :rtype: Node Left point to prev right point to after"""
if not root:
return None
head, tail = self.helper(root)
head.left = tail
tail.right = head
return head
def helper(self, curr)... | the_stack_v2_python_sparse | Algorithm/426_Convert_BST_TO_DLL.py | Gi1ia/TechNoteBook | train | 7 | |
0f5f2961aff3823559648c19cfe52f622b5f4290 | [
"for files_info in res_commit_api['files']:\n if files_info['filename'] == file_names_commit:\n raw_url = files_info['raw_url']\n response = request.urlopen(raw_url)\n data_file = response.read()\n data_file = data_file.decode()\n commit_file_data.append(data_file)\n com... | <|body_start_0|>
for files_info in res_commit_api['files']:
if files_info['filename'] == file_names_commit:
raw_url = files_info['raw_url']
response = request.urlopen(raw_url)
data_file = response.read()
data_file = data_file.decode()
... | create the dictionary | commit | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class commit:
"""create the dictionary"""
def commit_files(self, file_names_commit, count, res_commit_api, filename=None):
""":param file_name1: :param count: :param res_commit_api: :param filename: :return:"""
<|body_0|>
def lizard(self, file_names_commit, res_commit_api):
... | stack_v2_sparse_classes_36k_train_002128 | 5,608 | no_license | [
{
"docstring": ":param file_name1: :param count: :param res_commit_api: :param filename: :return:",
"name": "commit_files",
"signature": "def commit_files(self, file_names_commit, count, res_commit_api, filename=None)"
},
{
"docstring": ":param file_name1: :param res_commit_api: :return:",
"... | 4 | stack_v2_sparse_classes_30k_train_008719 | Implement the Python class `commit` described below.
Class description:
create the dictionary
Method signatures and docstrings:
- def commit_files(self, file_names_commit, count, res_commit_api, filename=None): :param file_name1: :param count: :param res_commit_api: :param filename: :return:
- def lizard(self, file_n... | Implement the Python class `commit` described below.
Class description:
create the dictionary
Method signatures and docstrings:
- def commit_files(self, file_names_commit, count, res_commit_api, filename=None): :param file_name1: :param count: :param res_commit_api: :param filename: :return:
- def lizard(self, file_n... | 4b31f2c7d87c3ad15c7ab8b71a94abdada1faf63 | <|skeleton|>
class commit:
"""create the dictionary"""
def commit_files(self, file_names_commit, count, res_commit_api, filename=None):
""":param file_name1: :param count: :param res_commit_api: :param filename: :return:"""
<|body_0|>
def lizard(self, file_names_commit, res_commit_api):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class commit:
"""create the dictionary"""
def commit_files(self, file_names_commit, count, res_commit_api, filename=None):
""":param file_name1: :param count: :param res_commit_api: :param filename: :return:"""
for files_info in res_commit_api['files']:
if files_info['filename'] == ... | the_stack_v2_python_sparse | fetching_data/commit_api.py | iamthebj/GitPred | train | 0 |
07f295edae5cfeefa88730d1ac46eade152a63b7 | [
"ProjectService.exists(project_id)\nteams_dto = TeamService.get_project_teams_as_dto(project_id)\nreturn (teams_dto.to_primitive(), 200)",
"if not TeamService.is_user_team_manager(team_id, token_auth.current_user()):\n return ({'Error': 'User is not an admin or a manager for the team', 'SubCode': 'UserPermissi... | <|body_start_0|>
ProjectService.exists(project_id)
teams_dto = TeamService.get_project_teams_as_dto(project_id)
return (teams_dto.to_primitive(), 200)
<|end_body_0|>
<|body_start_1|>
if not TeamService.is_user_team_manager(team_id, token_auth.current_user()):
return ({'Error... | ProjectsTeamsAPI | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectsTeamsAPI:
def get(self, project_id):
"""Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: pr... | stack_v2_sparse_classes_36k_train_002129 | 8,063 | permissive | [
{
"docstring": "Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: project_id in: path description: Unique project ID require... | 4 | stack_v2_sparse_classes_30k_train_010823 | Implement the Python class `ProjectsTeamsAPI` described below.
Class description:
Implement the ProjectsTeamsAPI class.
Method signatures and docstrings:
- def get(self, project_id): Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization descripti... | Implement the Python class `ProjectsTeamsAPI` described below.
Class description:
Implement the ProjectsTeamsAPI class.
Method signatures and docstrings:
- def get(self, project_id): Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization descripti... | 45bf3937c74902226096aee5b49e7abea62df524 | <|skeleton|>
class ProjectsTeamsAPI:
def get(self, project_id):
"""Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectsTeamsAPI:
def get(self, project_id):
"""Get teams assigned with a project --- tags: - teams produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - name: project_id in: p... | the_stack_v2_python_sparse | backend/api/projects/teams.py | hotosm/tasking-manager | train | 526 | |
ec9c6babaecb52c60344580ef286589e98abd0d5 | [
"super().__init__(grid=grid, **kwargs)\nself.int_effs = {}\nself.tagger_ls = {}\nself.label_colours = {}\nself.leg_tagger_labels = {}\nself.initialise_figure()\nself.disc_min, self.disc_max = (1000.0, -1000.0)\nself.default_linestyles = get_good_linestyles()\nself.legend_flavs = None\nself.leg_tagger_loc = 'lower l... | <|body_start_0|>
super().__init__(grid=grid, **kwargs)
self.int_effs = {}
self.tagger_ls = {}
self.label_colours = {}
self.leg_tagger_labels = {}
self.initialise_figure()
self.disc_min, self.disc_max = (1000.0, -1000.0)
self.default_linestyles = get_good_l... | IntegratedEfficiencyPlot class. | IntegratedEfficiencyPlot | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IntegratedEfficiencyPlot:
"""IntegratedEfficiencyPlot class."""
def __init__(self, grid: bool=True, **kwargs) -> None:
"""IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the plots. **kwargs : kwargs Keyword arguments from `puma.PlotO... | stack_v2_sparse_classes_36k_train_002130 | 9,037 | permissive | [
{
"docstring": "IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the plots. **kwargs : kwargs Keyword arguments from `puma.PlotObject`",
"name": "__init__",
"signature": "def __init__(self, grid: bool=True, **kwargs) -> None"
},
{
"docstring": "A... | 6 | stack_v2_sparse_classes_30k_train_001622 | Implement the Python class `IntegratedEfficiencyPlot` described below.
Class description:
IntegratedEfficiencyPlot class.
Method signatures and docstrings:
- def __init__(self, grid: bool=True, **kwargs) -> None: IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the pl... | Implement the Python class `IntegratedEfficiencyPlot` described below.
Class description:
IntegratedEfficiencyPlot class.
Method signatures and docstrings:
- def __init__(self, grid: bool=True, **kwargs) -> None: IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the pl... | 1ea02ba4a10df7c27b639d40c33cd24801b8d72c | <|skeleton|>
class IntegratedEfficiencyPlot:
"""IntegratedEfficiencyPlot class."""
def __init__(self, grid: bool=True, **kwargs) -> None:
"""IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the plots. **kwargs : kwargs Keyword arguments from `puma.PlotO... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IntegratedEfficiencyPlot:
"""IntegratedEfficiencyPlot class."""
def __init__(self, grid: bool=True, **kwargs) -> None:
"""IntegratedEfficiency plot properties. Parameters ---------- grid : bool, optional Set the grid for the plots. **kwargs : kwargs Keyword arguments from `puma.PlotObject`"""
... | the_stack_v2_python_sparse | puma/integrated_eff.py | umami-hep/puma | train | 3 |
6de3647eeb2d48f64a6eeea9a2c62388f213057f | [
"urls = super().get_urls()\ncustom_urls = [path('<int:object_id>/detail/', self.admin_site.admin_view(self.detail_view), name='program_topic_detail')]\nreturn custom_urls + urls",
"topic = get_object_or_404(Topic, pk=object_id)\ncontext = dict(self.admin_site.each_context(request), opts=Program._meta, object=topi... | <|body_start_0|>
urls = super().get_urls()
custom_urls = [path('<int:object_id>/detail/', self.admin_site.admin_view(self.detail_view), name='program_topic_detail')]
return custom_urls + urls
<|end_body_0|>
<|body_start_1|>
topic = get_object_or_404(Topic, pk=object_id)
context ... | TopicAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicAdmin:
def get_urls(self):
"""Add custom URL's to this App."""
<|body_0|>
def detail_view(self, request, object_id=None):
"""Detail View"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
urls = super().get_urls()
custom_urls = [path('<int... | stack_v2_sparse_classes_36k_train_002131 | 3,664 | permissive | [
{
"docstring": "Add custom URL's to this App.",
"name": "get_urls",
"signature": "def get_urls(self)"
},
{
"docstring": "Detail View",
"name": "detail_view",
"signature": "def detail_view(self, request, object_id=None)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000552 | Implement the Python class `TopicAdmin` described below.
Class description:
Implement the TopicAdmin class.
Method signatures and docstrings:
- def get_urls(self): Add custom URL's to this App.
- def detail_view(self, request, object_id=None): Detail View | Implement the Python class `TopicAdmin` described below.
Class description:
Implement the TopicAdmin class.
Method signatures and docstrings:
- def get_urls(self): Add custom URL's to this App.
- def detail_view(self, request, object_id=None): Detail View
<|skeleton|>
class TopicAdmin:
def get_urls(self):
... | f819b19b3e6ece017b4e67d1b93235ee848f09a1 | <|skeleton|>
class TopicAdmin:
def get_urls(self):
"""Add custom URL's to this App."""
<|body_0|>
def detail_view(self, request, object_id=None):
"""Detail View"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopicAdmin:
def get_urls(self):
"""Add custom URL's to this App."""
urls = super().get_urls()
custom_urls = [path('<int:object_id>/detail/', self.admin_site.admin_view(self.detail_view), name='program_topic_detail')]
return custom_urls + urls
def detail_view(self, request,... | the_stack_v2_python_sparse | apps/program/admin.py | nidhi22-creator/PDA-WEB | train | 0 | |
932a276a316295b79aac852162ae8b144dfd4f27 | [
"super().__init__(initial_class_observations, max_features, random_state)\nself._mc_correct_weight = 0.0\nself._nb_correct_weight = 0.0",
"if self._observed_class_distribution == {}:\n if 0 == y:\n self._mc_correct_weight += weight\nelif max(self._observed_class_distribution, key=self._observed_class_di... | <|body_start_0|>
super().__init__(initial_class_observations, max_features, random_state)
self._mc_correct_weight = 0.0
self._nb_correct_weight = 0.0
<|end_body_0|>
<|body_start_1|>
if self._observed_class_distribution == {}:
if 0 == y:
self._mc_correct_weigh... | Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instance or None, optional (default=None) If int, random_state ... | RandomLearningNodeNBAdaptive | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instanc... | stack_v2_sparse_classes_36k_train_002132 | 2,832 | permissive | [
{
"docstring": "LearningNodeNBAdaptive class constructor.",
"name": "__init__",
"signature": "def __init__(self, initial_class_observations, max_features, random_state)"
},
{
"docstring": "Update the node with the provided instance. Parameters ---------- X: numpy.ndarray of length equal to the n... | 3 | null | Implement the Python class `RandomLearningNodeNBAdaptive` described below.
Class description:
Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split.... | Implement the Python class `RandomLearningNodeNBAdaptive` described below.
Class description:
Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split.... | bfe504b4ca24b77e211fd55dc42844fc494671d7 | <|skeleton|>
class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instanc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomLearningNodeNBAdaptive:
"""Naive Bayes Adaptive learning node class. Parameters ---------- initial_class_observations: dict (class_value, weight) or None Initial class observations. max_features: int Number of attributes per subset for each node split. random_state: int, RandomState instance or None, op... | the_stack_v2_python_sparse | src/skmultiflow/trees/nodes/random_learning_node_nb_adaptive.py | jacobmontiel/scikit-multiflow | train | 1 |
15ed22f7fffd066270fb8d0534cc859287a9c769 | [
"super().__init__(x, y)\nself.fill_color = QtCore.Qt.green\nself.line_color = QtCore.Qt.red\nself.center_x = self.x\nself.center_y = self.y\nself.time = random.randint(0, 360)\nself.radius = random.randint(10, 20)",
"self.time += 1\nself.x = math.sin(math.radians(self.time)) * self.radius + self.center_x\nself.y ... | <|body_start_0|>
super().__init__(x, y)
self.fill_color = QtCore.Qt.green
self.line_color = QtCore.Qt.red
self.center_x = self.x
self.center_y = self.y
self.time = random.randint(0, 360)
self.radius = random.randint(10, 20)
<|end_body_0|>
<|body_start_1|>
... | Class to represent a Hummingbird. | Hummingbird | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):... | stack_v2_sparse_classes_36k_train_002133 | 13,878 | no_license | [
{
"docstring": "Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero.",
"name": "__init__",
"signature": "def __init__(self, x, y)"
},
{
"docstring": "A Hummingbird flies in a circle centered arou... | 2 | stack_v2_sparse_classes_30k_train_002428 | Implement the Python class `Hummingbird` described below.
Class description:
Class to represent a Hummingbird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default ... | Implement the Python class `Hummingbird` described below.
Class description:
Class to represent a Hummingbird.
Method signatures and docstrings:
- def __init__(self, x, y): Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default ... | 0e3470085083012f893adb22aa46d46039016965 | <|skeleton|>
class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
<|body_0|>
def move(self, w, h):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Hummingbird:
"""Class to represent a Hummingbird."""
def __init__(self, x, y):
"""Create a new Hummingbird with the given x and y values. :param int x: The x-coordinate; default is zero. :param int y: The y-coordinate; default is zero."""
super().__init__(x, y)
self.fill_color = Q... | the_stack_v2_python_sparse | CS_210 (Introduction to Programming)/Labs/Lab34_AviaryApp.py | JacobOrner/USAFA | train | 0 |
239519dffa9eff23eff0421662d87e6635d66aea | [
"super(ModelB, self).__init__()\nself.input_dim = input_dim\nself.hidden_dim = hidden_dim\nself.num_classes = num_classes\nself.gcn1 = GraphConvolution(input_dim, hidden_dim)\nself.pool1 = SelfAttentionPooling(hidden_dim, 0.5)\nself.gcn2 = GraphConvolution(hidden_dim, hidden_dim)\nself.pool2 = SelfAttentionPooling(... | <|body_start_0|>
super(ModelB, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.num_classes = num_classes
self.gcn1 = GraphConvolution(input_dim, hidden_dim)
self.pool1 = SelfAttentionPooling(hidden_dim, 0.5)
self.gcn2 = GraphConvoluti... | ModelB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelB:
def __init__(self, input_dim, hidden_dim, num_classes=2):
"""图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)"""
<|body_0|>
def forward(self, adjacency, input_feature, graph_indicator):
"""每一层G... | stack_v2_sparse_classes_36k_train_002134 | 10,598 | no_license | [
{
"docstring": "图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)",
"name": "__init__",
"signature": "def __init__(self, input_dim, hidden_dim, num_classes=2)"
},
{
"docstring": "每一层GCN分别进行pooling和输出",
"name": "forward",
"s... | 2 | stack_v2_sparse_classes_30k_train_019218 | Implement the Python class `ModelB` described below.
Class description:
Implement the ModelB class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, num_classes=2): 图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)
- def for... | Implement the Python class `ModelB` described below.
Class description:
Implement the ModelB class.
Method signatures and docstrings:
- def __init__(self, input_dim, hidden_dim, num_classes=2): 图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)
- def for... | 8d8a173b62d51cc98c8e7a2304a1e404448bceb6 | <|skeleton|>
class ModelB:
def __init__(self, input_dim, hidden_dim, num_classes=2):
"""图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)"""
<|body_0|>
def forward(self, adjacency, input_feature, graph_indicator):
"""每一层G... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelB:
def __init__(self, input_dim, hidden_dim, num_classes=2):
"""图分类模型结构,适用于较大的数据集 Args: ----- input_dim: int, 输入特征的维度 hidden_dim: int, 隐藏层单元数 num_classes: int, 分类类别数 (default: 2)"""
super(ModelB, self).__init__()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
... | the_stack_v2_python_sparse | GraphAttentionPool/model.py | RacleRay/DeepLearningFoundation | train | 3 | |
383deee568bade880bee06ca2ff2ed83b49a2bd0 | [
"fig_legend = self.get_legend()\nif self.show_legend is not False and fig_legend is not None:\n fig_legend.set_visible(True)\nself.grid(grid_on=True)",
"classes = dataset.classes\nif colors is None:\n if classes.size <= 6:\n colors = ['blue', 'red', 'lightgreen', 'black', 'gray', 'cyan']\n fro... | <|body_start_0|>
fig_legend = self.get_legend()
if self.show_legend is not False and fig_legend is not None:
fig_legend.set_visible(True)
self.grid(grid_on=True)
<|end_body_0|>
<|body_start_1|>
classes = dataset.classes
if colors is None:
if classes.size ... | Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and handle figures. | CPlotDataset | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CPlotDataset:
"""Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and handle figures."""
def apply_params... | stack_v2_sparse_classes_36k_train_002135 | 3,292 | permissive | [
{
"docstring": "Apply defined parameters to active subplot.",
"name": "apply_params_ds",
"signature": "def apply_params_ds(self)"
},
{
"docstring": "Plot patterns of each class with a different color/marker. Parameters ---------- dataset : CDataset Dataset that contain samples which we want plot... | 2 | stack_v2_sparse_classes_30k_train_011217 | Implement the Python class `CPlotDataset` described below.
Class description:
Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and h... | Implement the Python class `CPlotDataset` described below.
Class description:
Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and h... | 431373e65d8cfe2cb7cf042ce1a6c9519ea5a14a | <|skeleton|>
class CPlotDataset:
"""Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and handle figures."""
def apply_params... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CPlotDataset:
"""Plots a Dataset. Custom plotting parameters can be specified. Currently parameters default: - show_legend: True - grid: True See Also -------- .CDataset : store and manage a dataset. .CPlot : basic subplot functions. .CFigure : creates and handle figures."""
def apply_params_ds(self):
... | the_stack_v2_python_sparse | src/secml/figure/_plots/c_plot_ds.py | Cinofix/secml | train | 0 |
cc533a3edaf41d3453b46e5460b589dd5b06b699 | [
"self._hass = hass\nself._send_message = send_message\nself._logger = logger\nself._request = request\nself._authenticated = False\nself._connection = None",
"try:\n msg = AUTH_MESSAGE_SCHEMA(msg)\nexcept vol.Invalid as err:\n error_msg = f'Auth message incorrectly formatted: {humanize_error(msg, err)}'\n ... | <|body_start_0|>
self._hass = hass
self._send_message = send_message
self._logger = logger
self._request = request
self._authenticated = False
self._connection = None
<|end_body_0|>
<|body_start_1|>
try:
msg = AUTH_MESSAGE_SCHEMA(msg)
except v... | Connection that requires client to authenticate first. | AuthPhase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthPhase:
"""Connection that requires client to authenticate first."""
def __init__(self, logger, hass, send_message, request):
"""Initialize the authentiated connection."""
<|body_0|>
async def async_handle(self, msg):
"""Handle authentication."""
<|bod... | stack_v2_sparse_classes_36k_train_002136 | 2,895 | permissive | [
{
"docstring": "Initialize the authentiated connection.",
"name": "__init__",
"signature": "def __init__(self, logger, hass, send_message, request)"
},
{
"docstring": "Handle authentication.",
"name": "async_handle",
"signature": "async def async_handle(self, msg)"
},
{
"docstrin... | 3 | null | Implement the Python class `AuthPhase` described below.
Class description:
Connection that requires client to authenticate first.
Method signatures and docstrings:
- def __init__(self, logger, hass, send_message, request): Initialize the authentiated connection.
- async def async_handle(self, msg): Handle authenticat... | Implement the Python class `AuthPhase` described below.
Class description:
Connection that requires client to authenticate first.
Method signatures and docstrings:
- def __init__(self, logger, hass, send_message, request): Initialize the authentiated connection.
- async def async_handle(self, msg): Handle authenticat... | ed4ab403deaed9e8c95e0db728477fcb012bf4fa | <|skeleton|>
class AuthPhase:
"""Connection that requires client to authenticate first."""
def __init__(self, logger, hass, send_message, request):
"""Initialize the authentiated connection."""
<|body_0|>
async def async_handle(self, msg):
"""Handle authentication."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthPhase:
"""Connection that requires client to authenticate first."""
def __init__(self, logger, hass, send_message, request):
"""Initialize the authentiated connection."""
self._hass = hass
self._send_message = send_message
self._logger = logger
self._request = ... | the_stack_v2_python_sparse | homeassistant/components/websocket_api/auth.py | tchellomello/home-assistant | train | 8 |
ea0950f805cdc3c2b4f406229ce730cfc1c17b31 | [
"super().__init__(d_model, dropout_rate, max_len, reverse=True)\nself.pscale = paddle.to_tensor(scale)\nself.max_len = max_len * scale",
"assert dim % 2 == 0\nindices = paddle.arange(0, dim // 2, dtype=pos.dtype)\nindices = paddle.pow(paddle.cast(base, pos.dtype), -2 * indices / dim)\nembeddings = paddle.einsum('... | <|body_start_0|>
super().__init__(d_model, dropout_rate, max_len, reverse=True)
self.pscale = paddle.to_tensor(scale)
self.max_len = max_len * scale
<|end_body_0|>
<|body_start_1|>
assert dim % 2 == 0
indices = paddle.arange(0, dim // 2, dtype=pos.dtype)
indices = paddle... | Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf | ScaledRotaryRelPositionalEncoding | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScaledRotaryRelPositionalEncoding:
"""Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf"""
def __init__(self, d_model: int, dropout_rate: float, max_len: int=5000, scale=1):
"""Args: d_model (int): Embedding dimension.... | stack_v2_sparse_classes_36k_train_002137 | 10,278 | permissive | [
{
"docstring": "Args: d_model (int): Embedding dimension. dropout_rate (float): Dropout rate. max_len (int, optional): [Maximum input length.]. Defaults to 5000. scale (int): Interpolation max input length to `scale * max_len` positions.",
"name": "__init__",
"signature": "def __init__(self, d_model: in... | 4 | null | Implement the Python class `ScaledRotaryRelPositionalEncoding` described below.
Class description:
Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout_rate: float, max_len: int=... | Implement the Python class `ScaledRotaryRelPositionalEncoding` described below.
Class description:
Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf
Method signatures and docstrings:
- def __init__(self, d_model: int, dropout_rate: float, max_len: int=... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class ScaledRotaryRelPositionalEncoding:
"""Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf"""
def __init__(self, d_model: int, dropout_rate: float, max_len: int=5000, scale=1):
"""Args: d_model (int): Embedding dimension.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScaledRotaryRelPositionalEncoding:
"""Scaled Rotary Relative positional encoding module. POSITION INTERPOLATION: : https://arxiv.org/pdf/2306.15595v2.pdf"""
def __init__(self, d_model: int, dropout_rate: float, max_len: int=5000, scale=1):
"""Args: d_model (int): Embedding dimension. dropout_rate... | the_stack_v2_python_sparse | paddlespeech/s2t/modules/embedding.py | anniyanvr/DeepSpeech-1 | train | 0 |
efa8c265f300f619381be34ccb5b36ef6605feb4 | [
"self.event_threshold = event_threshold\nself._label_indices = {name: i for i, name in enumerate(label_names)}\nself.perf_data = {}\nfor label in label_names:\n for bench_name, bench_iterations in benchmark_names_and_iterations:\n for i in xrange(bench_iterations):\n report = read_perf_report(l... | <|body_start_0|>
self.event_threshold = event_threshold
self._label_indices = {name: i for i, name in enumerate(label_names)}
self.perf_data = {}
for label in label_names:
for bench_name, bench_iterations in benchmark_names_and_iterations:
for i in xrange(benc... | Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time spent in function_name). | _PerfTable | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time ... | stack_v2_sparse_classes_36k_train_002138 | 25,882 | permissive | [
{
"docstring": "Constructor. read_perf_report is a function that takes a label name, benchmark name, and benchmark iteration, and returns a dictionary describing the perf output for that given run.",
"name": "__init__",
"signature": "def __init__(self, benchmark_names_and_iterations, label_names, read_p... | 2 | stack_v2_sparse_classes_30k_train_012342 | Implement the Python class `_PerfTable` described below.
Class description:
Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...}... | Implement the Python class `_PerfTable` described below.
Class description:
Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...}... | e2745b756317aac3c7a27a4c10bdfe0921a82a1c | <|skeleton|>
class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _PerfTable:
"""Generates dicts from a perf table. Dicts look like: {'benchmark_name': {'perf_event_name': [LabelData]}} where LabelData is a list of perf dicts, each perf dict coming from the same label. Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the percentage of time spent in func... | the_stack_v2_python_sparse | app/src/main/java/com/syd/source/aosp/external/toolchain-utils/crosperf/results_report.py | lz-purple/Source | train | 4 |
ded52555f12874d113bb9d60b0eb20395ef4820d | [
"self.minHeap = []\nself.k = k\nif not nums:\n return\nfor i in range(k):\n if self.minHeap and len(self.minHeap) >= k:\n heapq.heappop(self.minHeap)\n if len(nums) > i:\n heapq.heappush(self.minHeap, nums[i])\n else:\n return\nfor i in range(k, len(nums)):\n if nums[i] > self.mi... | <|body_start_0|>
self.minHeap = []
self.k = k
if not nums:
return
for i in range(k):
if self.minHeap and len(self.minHeap) >= k:
heapq.heappop(self.minHeap)
if len(nums) > i:
heapq.heappush(self.minHeap, nums[i])
... | KthLargest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.minHeap = []
self.k = k
if not nums:
... | stack_v2_sparse_classes_36k_train_002139 | 1,191 | permissive | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017714 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 20ae1a048eddbc9a32c819cf61258e2b57572f05 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.minHeap = []
self.k = k
if not nums:
return
for i in range(k):
if self.minHeap and len(self.minHeap) >= k:
heapq.heappop(self.minHeap)
... | the_stack_v2_python_sparse | leetcode.com/python/703_Kth_Largest_Element_in_a_Stream.py | partho-maple/coding-interview-gym | train | 862 | |
e4e40cfb7699d61cf2739a1f4d5db252f074ba25 | [
"path_list = self.get_all_path_in_summary_md_file(summary_md_file_path)\nfor each_path in path_list:\n if not os.path.exists(os.path.join(root_path, each_path)):\n print('[-] Error: 路径 {} 不存在'.format(each_path))",
"result_list = list()\ntitle_re = re.compile('\\\\[.*\\\\]\\\\((.*)\\\\)')\nwith open(md_f... | <|body_start_0|>
path_list = self.get_all_path_in_summary_md_file(summary_md_file_path)
for each_path in path_list:
if not os.path.exists(os.path.join(root_path, each_path)):
print('[-] Error: 路径 {} 不存在'.format(each_path))
<|end_body_0|>
<|body_start_1|>
result_list ... | Checker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Checker:
def run(self, summary_md_file_path, root_path):
"""进行所有检查 :param summary_md_file_path: str(), 比如 "SUMMARY.md", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 "/Users/.../interview_collect", 表示所有 md 文件的根路径 :return: None"""
<|body_0|>
def get_all_path_in_summary_md_fil... | stack_v2_sparse_classes_36k_train_002140 | 1,945 | no_license | [
{
"docstring": "进行所有检查 :param summary_md_file_path: str(), 比如 \"SUMMARY.md\", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 \"/Users/.../interview_collect\", 表示所有 md 文件的根路径 :return: None",
"name": "run",
"signature": "def run(self, summary_md_file_path, root_path)"
},
{
"docstring": "通过读取 summar... | 2 | stack_v2_sparse_classes_30k_train_018346 | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def run(self, summary_md_file_path, root_path): 进行所有检查 :param summary_md_file_path: str(), 比如 "SUMMARY.md", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 "/Users/.../interview_coll... | Implement the Python class `Checker` described below.
Class description:
Implement the Checker class.
Method signatures and docstrings:
- def run(self, summary_md_file_path, root_path): 进行所有检查 :param summary_md_file_path: str(), 比如 "SUMMARY.md", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 "/Users/.../interview_coll... | a3ec3f4bf57099cbd6acf9ba4e9797e685d5a4ce | <|skeleton|>
class Checker:
def run(self, summary_md_file_path, root_path):
"""进行所有检查 :param summary_md_file_path: str(), 比如 "SUMMARY.md", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 "/Users/.../interview_collect", 表示所有 md 文件的根路径 :return: None"""
<|body_0|>
def get_all_path_in_summary_md_fil... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Checker:
def run(self, summary_md_file_path, root_path):
"""进行所有检查 :param summary_md_file_path: str(), 比如 "SUMMARY.md", 表示 SUMMARY.md 的路径 :param root_path: str(), 比如 "/Users/.../interview_collect", 表示所有 md 文件的根路径 :return: None"""
path_list = self.get_all_path_in_summary_md_file(summary_md_file... | the_stack_v2_python_sparse | python_script/check_summary.py | 276585877/interview_collect | train | 0 | |
74606cd7a291e6684d2183cfa916d17479446d97 | [
"method = 'POST'\npath = self.path('config/root')\ndata = {'access_key': access_key, 'secret_key': secret_key, 'region': region}\nresponse = (yield from self.req_handler(method, path, json=data))\nreturn ok(response)",
"method = 'POST'\npath = self.path('config/lease')\ndata = {'lease': format_duration(lease), 'l... | <|body_start_0|>
method = 'POST'
path = self.path('config/root')
data = {'access_key': access_key, 'secret_key': secret_key, 'region': region}
response = (yield from self.req_handler(method, path, json=data))
return ok(response)
<|end_body_0|>
<|body_start_1|>
method = '... | The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM keys must be configured with the "root" path and policies must be written usi... | AWSBackend | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSBackend:
"""The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM keys must be configured with the "root"... | stack_v2_sparse_classes_36k_train_002141 | 5,597 | permissive | [
{
"docstring": "Configures the root IAM credentials used. Before doing anything, the AWS backend needs credentials that are able to manage IAM policies, users, access keys, etc. This endpoint is used to configure those credentials. They don't necessarilly need to be root keys as long as they have permission to ... | 6 | stack_v2_sparse_classes_30k_train_010323 | Implement the Python class `AWSBackend` described below.
Class description:
The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM ... | Implement the Python class `AWSBackend` described below.
Class description:
The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM ... | 03e1bfb6f0404dcf97ce87a98c539027c4e78a37 | <|skeleton|>
class AWSBackend:
"""The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM keys must be configured with the "root"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSBackend:
"""The AWS backend dynamically generates AWS access keys for a set of IAM policies. The AWS access keys have a configurable lease set and are automatically revoked at the end of the lease. After mounting this backend, credentials to generate IAM keys must be configured with the "root" path and pol... | the_stack_v2_python_sparse | aiovault/v1/secret/backends/aws.py | johnnoone/aiovault | train | 1 |
bd6dc6ae0ee95de2a2c7c0ef7e4a1378b507a6fa | [
"def set_OUT_DATA_WIDTH(u):\n if self.master_to_slave:\n u.OUT_DATA_WIDTH = newDataWidth\n else:\n u.DATA_WIDTH = newDataWidth\n u.OUT_DATA_WIDTH = self.end.DATA_WIDTH\nreturn self._genericInstance(AxiS_resizer, 'resize', set_OUT_DATA_WIDTH)",
"lastseen = self.parent._reg(self.name + '_... | <|body_start_0|>
def set_OUT_DATA_WIDTH(u):
if self.master_to_slave:
u.OUT_DATA_WIDTH = newDataWidth
else:
u.DATA_WIDTH = newDataWidth
u.OUT_DATA_WIDTH = self.end.DATA_WIDTH
return self._genericInstance(AxiS_resizer, 'resize', set_O... | Helper class which simplifies building of large stream paths | AxiSBuilder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxiSBuilder:
"""Helper class which simplifies building of large stream paths"""
def resize(self, newDataWidth):
"""Change data width of axi stream"""
<|body_0|>
def startOfFrame(self) -> RtlSignal:
"""generate start of frame signal, high when we expect new frame ... | stack_v2_sparse_classes_36k_train_002142 | 5,559 | permissive | [
{
"docstring": "Change data width of axi stream",
"name": "resize",
"signature": "def resize(self, newDataWidth)"
},
{
"docstring": "generate start of frame signal, high when we expect new frame to start",
"name": "startOfFrame",
"signature": "def startOfFrame(self) -> RtlSignal"
},
... | 6 | null | Implement the Python class `AxiSBuilder` described below.
Class description:
Helper class which simplifies building of large stream paths
Method signatures and docstrings:
- def resize(self, newDataWidth): Change data width of axi stream
- def startOfFrame(self) -> RtlSignal: generate start of frame signal, high when... | Implement the Python class `AxiSBuilder` described below.
Class description:
Helper class which simplifies building of large stream paths
Method signatures and docstrings:
- def resize(self, newDataWidth): Change data width of axi stream
- def startOfFrame(self) -> RtlSignal: generate start of frame signal, high when... | 4c1d54c7b15929032ad2ba984bf48b45f3549c49 | <|skeleton|>
class AxiSBuilder:
"""Helper class which simplifies building of large stream paths"""
def resize(self, newDataWidth):
"""Change data width of axi stream"""
<|body_0|>
def startOfFrame(self) -> RtlSignal:
"""generate start of frame signal, high when we expect new frame ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxiSBuilder:
"""Helper class which simplifies building of large stream paths"""
def resize(self, newDataWidth):
"""Change data width of axi stream"""
def set_OUT_DATA_WIDTH(u):
if self.master_to_slave:
u.OUT_DATA_WIDTH = newDataWidth
else:
... | the_stack_v2_python_sparse | hwtLib/amba/axis_comp/builder.py | Nic30/hwtLib | train | 36 |
3a96028f733a6bc03b05d0164cb61c3133b3b295 | [
"post_body = json.dumps({'identity_provider': kwargs})\nresp, body = self.put('OS-FEDERATION/identity_providers/%s' % identity_provider_id, post_body)\nself.expected_success(201, resp.status)\nbody = json.loads(body)\nreturn rest_client.ResponseBody(resp, body)",
"url = 'identity_providers'\nif params:\n url +... | <|body_start_0|>
post_body = json.dumps({'identity_provider': kwargs})
resp, body = self.put('OS-FEDERATION/identity_providers/%s' % identity_provider_id, post_body)
self.expected_success(201, resp.status)
body = json.loads(body)
return rest_client.ResponseBody(resp, body)
<|end_... | IdentityProvidersClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-... | stack_v2_sparse_classes_36k_train_002143 | 3,718 | permissive | [
{
"docstring": "Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-identity-provider",
"name": "register_identity_provider",
"signature": "def register_identity_prov... | 5 | null | Implement the Python class `IdentityProvidersClient` described below.
Class description:
Implement the IdentityProvidersClient class.
Method signatures and docstrings:
- def register_identity_provider(self, identity_provider_id, **kwargs): Register an identity provider. For a full list of available parameters, please... | Implement the Python class `IdentityProvidersClient` described below.
Class description:
Implement the IdentityProvidersClient class.
Method signatures and docstrings:
- def register_identity_provider(self, identity_provider_id, **kwargs): Register an identity provider. For a full list of available parameters, please... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityProvidersClient:
def register_identity_provider(self, identity_provider_id, **kwargs):
"""Register an identity provider. For a full list of available parameters, please refer to the official API reference: https://docs.openstack.org/api-ref/identity/v3-ext/index.html#register-an-identity-provi... | the_stack_v2_python_sparse | tempest/lib/services/identity/v3/identity_providers_client.py | openstack/tempest | train | 270 | |
92e73572b4c87f84fefac8bd2c4fb051458ff2ef | [
"super().__init__(*args, **kwargs)\nself.root: Any = LeoNode()\nself.root.h = 'ROOT'\nself.cur: Any = self.root\nself.idx = {}\nself.in_ = None\nself.in_attrs = {}\nself.path = []",
"self.in_ = name\nself.in_attrs = attrs\nif name == 'v':\n nd = LeoNode()\n self.cur.children.append(nd)\n nd.parent = self... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.root: Any = LeoNode()
self.root.h = 'ROOT'
self.cur: Any = self.root
self.idx = {}
self.in_ = None
self.in_attrs = {}
self.path = []
<|end_body_0|>
<|body_start_1|>
self.in_ = name
se... | Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used internally during SAX read idx mapping from gnx to node `in_` name of XML element ... | LeoReader | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LeoReader:
"""Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used internally during SAX read idx mapping from g... | stack_v2_sparse_classes_36k_train_002144 | 6,690 | permissive | [
{
"docstring": "Set ivars",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "collect information from v and t elements",
"name": "startElement",
"signature": "def startElement(self, name, attrs)"
},
{
"docstring": "decode unknownAttributes... | 4 | stack_v2_sparse_classes_30k_train_010943 | Implement the Python class `LeoReader` described below.
Class description:
Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used intern... | Implement the Python class `LeoReader` described below.
Class description:
Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used intern... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class LeoReader:
"""Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used internally during SAX read idx mapping from g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LeoReader:
"""Read .leo files into a simple python data structure with h, b, u (unknown attribs), gnx and children information. Clones and derived files are ignored. Useful for scanning multiple .leo files quickly. :IVariables: root root node cur used internally during SAX read idx mapping from gnx to node `i... | the_stack_v2_python_sparse | leo/external/leosax.py | leo-editor/leo-editor | train | 1,671 |
5b4664d16779ca9554081da377aadb94df46ef10 | [
"self.show_io_types = show_io_types\nself.show_tags = show_tags\nself.universal = universal",
"if self.show_io_types:\n cats = [obj.__class__.__name__ for obj in form_objects]\n for cat in iterutils.unique_everseen(cats):\n yield ('input:' + cat)\n if form_out:\n yield ('output:' + form_out... | <|body_start_0|>
self.show_io_types = show_io_types
self.show_tags = show_tags
self.universal = universal
<|end_body_0|>
<|body_start_1|>
if self.show_io_types:
cats = [obj.__class__.__name__ for obj in form_objects]
for cat in iterutils.unique_everseen(cats):
... | Specify how the mobyle xmls should be categorized. | CategoryInfo | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryInfo:
"""Specify how the mobyle xmls should be categorized."""
def __init__(self, show_io_types, show_tags, universal):
"""@param show_io_types: True if we should categorize by io type @param show_tags: True if we should categorize by tag @param universal: None or a category ... | stack_v2_sparse_classes_36k_train_002145 | 6,320 | no_license | [
{
"docstring": "@param show_io_types: True if we should categorize by io type @param show_tags: True if we should categorize by tag @param universal: None or a category encompassing all xmls",
"name": "__init__",
"signature": "def __init__(self, show_io_types, show_tags, universal)"
},
{
"docstr... | 2 | null | Implement the Python class `CategoryInfo` described below.
Class description:
Specify how the mobyle xmls should be categorized.
Method signatures and docstrings:
- def __init__(self, show_io_types, show_tags, universal): @param show_io_types: True if we should categorize by io type @param show_tags: True if we shoul... | Implement the Python class `CategoryInfo` described below.
Class description:
Specify how the mobyle xmls should be categorized.
Method signatures and docstrings:
- def __init__(self, show_io_types, show_tags, universal): @param show_io_types: True if we should categorize by io type @param show_tags: True if we shoul... | 91c6f8331f18c914eb3dfc51bc166915998c5081 | <|skeleton|>
class CategoryInfo:
"""Specify how the mobyle xmls should be categorized."""
def __init__(self, show_io_types, show_tags, universal):
"""@param show_io_types: True if we should categorize by io type @param show_tags: True if we should categorize by tag @param universal: None or a category ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CategoryInfo:
"""Specify how the mobyle xmls should be categorized."""
def __init__(self, show_io_types, show_tags, universal):
"""@param show_io_types: True if we should categorize by io type @param show_tags: True if we should categorize by tag @param universal: None or a category encompassing ... | the_stack_v2_python_sparse | mobyle.py | argriffing/xgcode | train | 1 |
f2453a83c9d38086702c4e3fec2a9b8486dd0657 | [
"if not root:\n return '[]'\nret = []\n\ndef helper(tree: TreeNode, ind=0):\n if not tree:\n return\n ret.append({ind: tree.val})\n helper(tree.left, 2 * ind + 1)\n helper(tree.right, 2 * ind + 2)\nhelper(root)\nreturn str(ret)",
"ele_dict = {}\ndata = data.replace('[', '').replace(']', '').... | <|body_start_0|>
if not root:
return '[]'
ret = []
def helper(tree: TreeNode, ind=0):
if not tree:
return
ret.append({ind: tree.val})
helper(tree.left, 2 * ind + 1)
helper(tree.right, 2 * ind + 2)
helper(root)
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_002146 | 1,591 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 4a3ba15284c45b2d8bf38306c8c8526ae174615c | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
ret = []
def helper(tree: TreeNode, ind=0):
if not tree:
return
ret.append({ind: tree.val})
... | the_stack_v2_python_sparse | Hard/297. Serialize and Deserialize Binary Tree/Serialize and Deserialize Binary Tree.py | wangyendt/LeetCode | train | 6 | |
4b277afb0a635aed4d246f16c0b95ad6c8ccd3e1 | [
"for index, value in enumerate(sequence):\n print(index, value)\n if destination_value == value:\n return index",
"sequence_length = len(sequence)\nif not sequence_length:\n return -1\nindex = sequence_length - 1\nif sequence[index] == destination_value:\n return index\nreturn self.linearSearch... | <|body_start_0|>
for index, value in enumerate(sequence):
print(index, value)
if destination_value == value:
return index
<|end_body_0|>
<|body_start_1|>
sequence_length = len(sequence)
if not sequence_length:
return -1
index = sequenc... | 传统查找方法总结 | TraditionalSearch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
<|body_0|>
def linearSearchRecursion(self, destination_value, sequence):
"""递归式线性查找"""
<|body_1|>
def binarySearchRecursion(self, value, so... | stack_v2_sparse_classes_36k_train_002147 | 2,239 | permissive | [
{
"docstring": "传统线行查找",
"name": "linearSearchTraditional",
"signature": "def linearSearchTraditional(self, destination_value, sequence)"
},
{
"docstring": "递归式线性查找",
"name": "linearSearchRecursion",
"signature": "def linearSearchRecursion(self, destination_value, sequence)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_015585 | Implement the Python class `TraditionalSearch` described below.
Class description:
传统查找方法总结
Method signatures and docstrings:
- def linearSearchTraditional(self, destination_value, sequence): 传统线行查找
- def linearSearchRecursion(self, destination_value, sequence): 递归式线性查找
- def binarySearchRecursion(self, value, sorted... | Implement the Python class `TraditionalSearch` described below.
Class description:
传统查找方法总结
Method signatures and docstrings:
- def linearSearchTraditional(self, destination_value, sequence): 传统线行查找
- def linearSearchRecursion(self, destination_value, sequence): 递归式线性查找
- def binarySearchRecursion(self, value, sorted... | ec385235f56b2ca42974f2f6067f708ab4f693fc | <|skeleton|>
class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
<|body_0|>
def linearSearchRecursion(self, destination_value, sequence):
"""递归式线性查找"""
<|body_1|>
def binarySearchRecursion(self, value, so... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TraditionalSearch:
"""传统查找方法总结"""
def linearSearchTraditional(self, destination_value, sequence):
"""传统线行查找"""
for index, value in enumerate(sequence):
print(index, value)
if destination_value == value:
return index
def linearSearchRecursion(se... | the_stack_v2_python_sparse | DataStructure/12_线性查找与二分查找.py | xiaopingzhong/AlgorithmAndDataStructure | train | 0 |
7d1b9baa94cd53c41b2e78671dae21d926f7bd39 | [
"self.lrow = len(matrix)\nif self.lrow == 0:\n self.dp = [[]]\n return\nself.lcol = len(matrix[0])\nself.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]\nfor i in range(self.lrow):\n for j in range(self.lcol):\n self.dp[i][j] = self.dp[i][j - 1] + matrix[i][j]",
"r = 0\nfor row in r... | <|body_start_0|>
self.lrow = len(matrix)
if self.lrow == 0:
self.dp = [[]]
return
self.lcol = len(matrix[0])
self.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]
for i in range(self.lrow):
for j in range(self.lcol):
... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_002148 | 1,038 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_015924 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 65549f72c565d9f11641c86d6cef9c7988805817 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
self.lrow = len(matrix)
if self.lrow == 0:
self.dp = [[]]
return
self.lcol = len(matrix[0])
self.dp = [[0 for _ in range(self.lcol)] for _ in range(self.lrow)]
for... | the_stack_v2_python_sparse | utils/numSumMatrix.py | wisesky/LeetCode-Practice | train | 0 | |
bda0ce5682229a52140fb43b9f3618bba1a7c378 | [
"total_pairs = 0\nleft, right = (0, 1)\nnums.sort()\nwhile left < len(nums) and right < len(nums):\n if left == right or nums[right] - nums[left] < K:\n right += 1\n elif nums[right] - nums[left] > K:\n left += 1\n else:\n total_pairs += 1\n left += 1\n while left < len(n... | <|body_start_0|>
total_pairs = 0
left, right = (0, 1)
nums.sort()
while left < len(nums) and right < len(nums):
if left == right or nums[right] - nums[left] < K:
right += 1
elif nums[right] - nums[left] > K:
left += 1
el... | Array | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def k_diff_pairs_(self, nums: List[int], K) -> int:
"""Approach: Hash Map Time Com... | stack_v2_sparse_classes_36k_train_002149 | 1,482 | no_license | [
{
"docstring": "Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:",
"name": "k_diff_pairs",
"signature": "def k_diff_pairs(self, nums: List[int], K: int) -> int"
},
{
"docstring": "Approach: Hash Map Time Complexity: O(N) Space Complexity: O... | 2 | stack_v2_sparse_classes_30k_train_001456 | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def k_diff_pairs(self, nums: List[int], K: int) -> int: Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def k_diff_pairs_(sel... | Implement the Python class `Array` described below.
Class description:
Implement the Array class.
Method signatures and docstrings:
- def k_diff_pairs(self, nums: List[int], K: int) -> int: Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:
- def k_diff_pairs_(sel... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
<|body_0|>
def k_diff_pairs_(self, nums: List[int], K) -> int:
"""Approach: Hash Map Time Com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Array:
def k_diff_pairs(self, nums: List[int], K: int) -> int:
"""Approach: Sorting + Two Pointer Time Complexity: O(N log N) Space Complexity: O(N) :param nums: :return:"""
total_pairs = 0
left, right = (0, 1)
nums.sort()
while left < len(nums) and right < len(nums):
... | the_stack_v2_python_sparse | goldman_sachs/K_diff_pairs_in_array.py | Shiv2157k/leet_code | train | 1 | |
2cf7a4d8220fee6adb15198b05c358a693727144 | [
"row = len(matrix)\nif row == 0:\n return\ncol = len(matrix[0])\nif col == 0:\n return\nself.dp = [[0 for j in range(col + 1)] for i in range(row)]\nfor i in range(0, row):\n for j in range(0, col):\n self.dp[i][j + 1] = self.dp[i][j] + matrix[i][j]",
"ans = 0\nfor i in range(row1, row2 + 1):\n ... | <|body_start_0|>
row = len(matrix)
if row == 0:
return
col = len(matrix[0])
if col == 0:
return
self.dp = [[0 for j in range(col + 1)] for i in range(row)]
for i in range(0, row):
for j in range(0, col):
self.dp[i][j + 1... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_002150 | 1,075 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | e42ec45d98f990d446bbf4f1a568b70855af5380 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
row = len(matrix)
if row == 0:
return
col = len(matrix[0])
if col == 0:
return
self.dp = [[0 for j in range(col + 1)] for i in range(row)]
for i in range(0... | the_stack_v2_python_sparse | sumRegion2DMatrix.py | LYoung-Hub/Algorithm-Data-Structure | train | 0 | |
bfddf40cb678c98d2b73767b34afb4259402e163 | [
"try:\n notification = Notification.objects.get(pk=pk)\n serializer = self.serializer_class(notification, context={'request': request})\n return Response(serializer.data, status.HTTP_200_OK)\nexcept ObjectDoesNotExist:\n return Response({'errors': 'Notification does not exist'}, status.HTTP_404_NOT_FOUN... | <|body_start_0|>
try:
notification = Notification.objects.get(pk=pk)
serializer = self.serializer_class(notification, context={'request': request})
return Response(serializer.data, status.HTTP_200_OK)
except ObjectDoesNotExist:
return Response({'errors': '... | get: delete: | NotificationDetailsView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NotificationDetailsView:
"""get: delete:"""
def get(self, request, pk):
"""Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data for requested notification"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_002151 | 7,717 | permissive | [
{
"docstring": "Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data for requested notification",
"name": "get",
"signature": "def get(self, request, pk)"
},
{
"docstring": "Delete a given notificat... | 3 | stack_v2_sparse_classes_30k_train_018903 | Implement the Python class `NotificationDetailsView` described below.
Class description:
get: delete:
Method signatures and docstrings:
- def get(self, request, pk): Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data f... | Implement the Python class `NotificationDetailsView` described below.
Class description:
get: delete:
Method signatures and docstrings:
- def get(self, request, pk): Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data f... | daf55ce4819f57cec8510c5726e86a0b1e78e3e1 | <|skeleton|>
class NotificationDetailsView:
"""get: delete:"""
def get(self, request, pk):
"""Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data for requested notification"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NotificationDetailsView:
"""get: delete:"""
def get(self, request, pk):
"""Retrieve a specific notification from the database given it's id. :params pk: an id of the notification to retrieve :returns notification: a json data for requested notification"""
try:
notification = N... | the_stack_v2_python_sparse | authors/apps/notifications/views.py | andela/ah-magnificent6 | train | 0 |
63ab1289ef3cf0e9a1f18e9b32e38c50ce22ef12 | [
"config = orm.Config.objects.get()\norm.ConfigUCI.objects.create(section='registry registry', option='base_uri', value=\"node.firmware_build.kwargs_dict.get('registry_base_uri')\", config=config)\norm.ConfigUCI.objects.create(section='registry registry', option='cert', value=\"'/etc/confine/registry-server.crt'\", ... | <|body_start_0|>
config = orm.Config.objects.get()
orm.ConfigUCI.objects.create(section='registry registry', option='base_uri', value="node.firmware_build.kwargs_dict.get('registry_base_uri')", config=config)
orm.ConfigUCI.objects.create(section='registry registry', option='cert', value="'/etc/c... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Update firmware configuration to include registry section."""
<|body_0|>
def backwards(self, orm):
"""Restore firmware configuration."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
config = orm.Config.objects.... | stack_v2_sparse_classes_36k_train_002152 | 11,500 | no_license | [
{
"docstring": "Update firmware configuration to include registry section.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Restore firmware configuration.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021298 | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Update firmware configuration to include registry section.
- def backwards(self, orm): Restore firmware configuration. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Update firmware configuration to include registry section.
- def backwards(self, orm): Restore firmware configuration.
<|skeleton|>
class Migration:
... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Update firmware configuration to include registry section."""
<|body_0|>
def backwards(self, orm):
"""Restore firmware configuration."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Update firmware configuration to include registry section."""
config = orm.Config.objects.get()
orm.ConfigUCI.objects.create(section='registry registry', option='base_uri', value="node.firmware_build.kwargs_dict.get('registry_base_uri')", config=c... | the_stack_v2_python_sparse | controller/apps/firmware/migrations/0035_datamigration__add_registry_uci.py | m00dy/vct-controller | train | 2 | |
7b9c906d6cd3f83f63e95ab467f7d7f9b6f76781 | [
"global dev_plan_list_page, admin_page\ndev_plan_list_page = DevPlanListPage(self.driver)\nadmin_page = AdminPage(self.driver)\nadmin_page.into_subsystem('业务管理')\nadmin_page.select_menu('首页/渠道业务管理/年度发展计划')",
"admin_page.select_menu('计划列表')\ndev_plan_list_page.query_by_year(_year='2020')\nassert '2020' in dev_plan... | <|body_start_0|>
global dev_plan_list_page, admin_page
dev_plan_list_page = DevPlanListPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道业务管理/年度发展计划')
<|end_body_0|>
<|body_start_1|>
admin_page.select_men... | TestDevPlanList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDevPlanList:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_dev_plan(self, set_up):
"""年度计划查询 :return:"""
<|body_1|>
def test_reset_dev_plan_query(self):
"""重置年度计划查询 :return:"""
<|body_2|>
def test_click_create_d... | stack_v2_sparse_classes_36k_train_002153 | 2,658 | no_license | [
{
"docstring": "前置操作 :return:",
"name": "set_up",
"signature": "def set_up(self)"
},
{
"docstring": "年度计划查询 :return:",
"name": "test_query_dev_plan",
"signature": "def test_query_dev_plan(self, set_up)"
},
{
"docstring": "重置年度计划查询 :return:",
"name": "test_reset_dev_plan_query... | 6 | stack_v2_sparse_classes_30k_train_014536 | Implement the Python class `TestDevPlanList` described below.
Class description:
Implement the TestDevPlanList class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_dev_plan(self, set_up): 年度计划查询 :return:
- def test_reset_dev_plan_query(self): 重置年度计划查询 :return:
- def test_click_c... | Implement the Python class `TestDevPlanList` described below.
Class description:
Implement the TestDevPlanList class.
Method signatures and docstrings:
- def set_up(self): 前置操作 :return:
- def test_query_dev_plan(self, set_up): 年度计划查询 :return:
- def test_reset_dev_plan_query(self): 重置年度计划查询 :return:
- def test_click_c... | 86d1b085af2d3808ac8472d541f4bf26d26591e0 | <|skeleton|>
class TestDevPlanList:
def set_up(self):
"""前置操作 :return:"""
<|body_0|>
def test_query_dev_plan(self, set_up):
"""年度计划查询 :return:"""
<|body_1|>
def test_reset_dev_plan_query(self):
"""重置年度计划查询 :return:"""
<|body_2|>
def test_click_create_d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDevPlanList:
def set_up(self):
"""前置操作 :return:"""
global dev_plan_list_page, admin_page
dev_plan_list_page = DevPlanListPage(self.driver)
admin_page = AdminPage(self.driver)
admin_page.into_subsystem('业务管理')
admin_page.select_menu('首页/渠道业务管理/年度发展计划')
d... | the_stack_v2_python_sparse | src/cases/business_manage/channel_business_manage/developmentPlan/test_dev_plan_list_page_170.py | 102244653/SeleniumByPython | train | 2 | |
b3bcdd74bd6b256ca7f9ca5992c86b5396af0adc | [
"session_ = session if session is not None else API.SESSION\nurl = API.URL + '/request/domains/format/json'\nr = session_.get(url)\nif r.status_code == 404:\n raise Exception('response status: 404')\nreturn Domains(json.loads(r.text))",
"session_ = session if session is not None else API.SESSION\nurl = API.URL... | <|body_start_0|>
session_ = session if session is not None else API.SESSION
url = API.URL + '/request/domains/format/json'
r = session_.get(url)
if r.status_code == 404:
raise Exception('response status: 404')
return Domains(json.loads(r.text))
<|end_body_0|>
<|body_... | API | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class API:
def get_domains(session: requests.Session=None):
"""! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Accept-Encoding: gzip, deflate User-Agent: okhttp/3.14.7"""
<|body_0|>
def get_mes... | stack_v2_sparse_classes_36k_train_002154 | 4,442 | no_license | [
{
"docstring": "! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Accept-Encoding: gzip, deflate User-Agent: okhttp/3.14.7",
"name": "get_domains",
"signature": "def get_domains(session: requests.Session=None)"
},
... | 2 | stack_v2_sparse_classes_30k_train_007792 | Implement the Python class `API` described below.
Class description:
Implement the API class.
Method signatures and docstrings:
- def get_domains(session: requests.Session=None): ! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Acc... | Implement the Python class `API` described below.
Class description:
Implement the API class.
Method signatures and docstrings:
- def get_domains(session: requests.Session=None): ! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Acc... | be4da628b8a1786d20aad3cb573396ff830660ff | <|skeleton|>
class API:
def get_domains(session: requests.Session=None):
"""! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Accept-Encoding: gzip, deflate User-Agent: okhttp/3.14.7"""
<|body_0|>
def get_mes... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class API:
def get_domains(session: requests.Session=None):
"""! Get all valide domains. GET /request/domains/format/json HTTP/1.1 Accept: application/json Host: mob1.temp-mail.org Connection: close Accept-Encoding: gzip, deflate User-Agent: okhttp/3.14.7"""
session_ = session if session is not None... | the_stack_v2_python_sparse | tempmail_api/api.py | MD-Levitan/TempMailApi | train | 5 | |
4e011dd7ba8b65984b56e49d75ca9ce71a50d890 | [
"if not root:\n return root\nif p == root or q == root:\n return root\nleft = self.lowestCommonAncestor(root.left, p, q)\nright = self.lowestCommonAncestor(root.right, p, q)\nif left and right:\n return root\nreturn left if left else right",
"if root in (None, p, q):\n return root\nleft, right = (self... | <|body_start_0|>
if not root:
return root
if p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left el... | 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_shortest(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: T... | stack_v2_sparse_classes_36k_train_002155 | 4,355 | 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... | 4 | stack_v2_sparse_classes_30k_test_000218 | 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_shortest(self, root, p, q): :type... | 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_shortest(self, root, p, q): :type... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def lowestCommonAncestor(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode"""
<|body_0|>
def lowestCommonAncestor_shortest(self, root, p, q):
""":type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: T... | 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:
return root
if p == root or q == root:
return root
left = self.lowestCommonAncestor(root.left, p, q)
... | the_stack_v2_python_sparse | src/lt_236.py | oxhead/CodingYourWay | train | 0 | |
3fbb5ea69236b5eea27dbcc847286ab1a51fac8e | [
"if len(left) > 0:\n l_mid_idx = int(len(left) / 2)\n left_node = TreeNode(val=left[l_mid_idx])\n root.left = left_node\n self.create_subtree(left_node, left[:l_mid_idx], left[l_mid_idx + 1:] if len(left) > l_mid_idx + 1 else [])\nif len(right) > 0:\n r_mid_idx = int(len(right) / 2)\n right_node =... | <|body_start_0|>
if len(left) > 0:
l_mid_idx = int(len(left) / 2)
left_node = TreeNode(val=left[l_mid_idx])
root.left = left_node
self.create_subtree(left_node, left[:l_mid_idx], left[l_mid_idx + 1:] if len(left) > l_mid_idx + 1 else [])
if len(right) > 0:... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def create_subtree(self, root: TreeNode, left: List[int], right: List[int]):
"""Both left and right are sorted in a strictly increasing order :param root: :param left: :param right: :return:"""
<|body_0|>
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
... | stack_v2_sparse_classes_36k_train_002156 | 3,664 | no_license | [
{
"docstring": "Both left and right are sorted in a strictly increasing order :param root: :param left: :param right: :return:",
"name": "create_subtree",
"signature": "def create_subtree(self, root: TreeNode, left: List[int], right: List[int])"
},
{
"docstring": "To solve this, we will follow t... | 2 | stack_v2_sparse_classes_30k_train_018272 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def create_subtree(self, root: TreeNode, left: List[int], right: List[int]): Both left and right are sorted in a strictly increasing order :param root: :param left: :param right:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def create_subtree(self, root: TreeNode, left: List[int], right: List[int]): Both left and right are sorted in a strictly increasing order :param root: :param left: :param right:... | 27e1f356d748c29427568b89b700a05b293107a3 | <|skeleton|>
class Solution:
def create_subtree(self, root: TreeNode, left: List[int], right: List[int]):
"""Both left and right are sorted in a strictly increasing order :param root: :param left: :param right: :return:"""
<|body_0|>
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def create_subtree(self, root: TreeNode, left: List[int], right: List[int]):
"""Both left and right are sorted in a strictly increasing order :param root: :param left: :param right: :return:"""
if len(left) > 0:
l_mid_idx = int(len(left) / 2)
left_node = TreeN... | the_stack_v2_python_sparse | Top Interview Questions Easy Collection/Trees/Convert Sorted Array to Binary Search Tree/solution.py | zhweiliu/learn_leetcode | train | 0 | |
c113a2e38661aed9a75740556c6091f6a23cab40 | [
"super(StyleTask, self).__init__()\nif num_segments < 3:\n raise Exception('num_segments must be >= 3 for StyleTask.')\nif speed <= 0 or speed > 1:\n raise Exception('power must be between (0, 1] for StyleTask.')\nspeed /= 10000\nself.num_segments = num_segments\nself.angle = angle\nself.seg_rads = angle / nu... | <|body_start_0|>
super(StyleTask, self).__init__()
if num_segments < 3:
raise Exception('num_segments must be >= 3 for StyleTask.')
if speed <= 0 or speed > 1:
raise Exception('power must be between (0, 1] for StyleTask.')
speed /= 10000
self.num_segments ... | StyleTask | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (... | stack_v2_sparse_classes_36k_train_002157 | 4,891 | no_license | [
{
"docstring": "Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (float): desired angle of turn in radians num_segments (int): number of segments to check p... | 3 | stack_v2_sparse_classes_30k_train_007505 | Implement the Python class `StyleTask` described below.
Class description:
Implement the StyleTask class.
Method signatures and docstrings:
- def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4): Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (s... | Implement the Python class `StyleTask` described below.
Class description:
Implement the StyleTask class.
Method signatures and docstrings:
- def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4): Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (s... | e2fd7ab924d143bf6354806a104f49d982f32fb1 | <|skeleton|>
class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StyleTask:
def __init__(self, axis, speed, angle=2 * math.pi, num_segments=4):
"""Rotate using a given power past a certain angle and check that it reaches a num_segments Parameters: axis (string): orientation (x, y, z) of turn power (float): desired twist power of turn in (0, 1] angle (float): desire... | the_stack_v2_python_sparse | onboard/catkin_ws/src/task_planning/scripts/old/style_task.py | DukeRobotics/robosub-ros | train | 24 | |
fd94796047c557b42d455180121d18b4c96ee72f | [
"from scoop.content.models.picture import Picture\nuuid = self.value\ncss_class = '{0}{1}'.format(' ' if 'class' in self.kwargs else '', self.kwargs.get('class', ''))\nimage = Picture.objects.get_by_uuid(uuid)\nreturn {'image': image, 'class': css_class}",
"base = super(AnimationInline, self).get_template_name()[... | <|body_start_0|>
from scoop.content.models.picture import Picture
uuid = self.value
css_class = '{0}{1}'.format(' ' if 'class' in self.kwargs else '', self.kwargs.get('class', ''))
image = Picture.objects.get_by_uuid(uuid)
return {'image': image, 'class': css_class}
<|end_body_0|... | Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}} | AnimationInline | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnimationInline:
"""Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""R... | stack_v2_sparse_classes_36k_train_002158 | 6,816 | no_license | [
{
"docstring": "Renvoyer le contexte de rendu de l'inline",
"name": "get_context",
"signature": "def get_context(self)"
},
{
"docstring": "Renvoyer le chemin du template",
"name": "get_template_name",
"signature": "def get_template_name(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014686 | Implement the Python class `AnimationInline` described below.
Class description:
Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_t... | Implement the Python class `AnimationInline` described below.
Class description:
Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}}
Method signatures and docstrings:
- def get_context(self): Renvoyer le contexte de rendu de l'inline
- def get_t... | 8cef6f6e89c1990e2b25f83e54e0c3481d83b6d7 | <|skeleton|>
class AnimationInline:
"""Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
<|body_0|>
def get_template_name(self):
"""R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnimationInline:
"""Inline d'insertion d'animations Format : {{animation imageuuid [class=css]}} Exemple : {{animation dF4y8P class="bordered"}}"""
def get_context(self):
"""Renvoyer le contexte de rendu de l'inline"""
from scoop.content.models.picture import Picture
uuid = self.v... | the_stack_v2_python_sparse | scoop/content/util/inlines.py | artscoop/scoop | train | 0 |
58acf9b021c23cb8a6f947132690dd48af82702c | [
"res = 0\nwhile height.count(0) != len(height):\n ceng = [c != 0 for c in height]\n height = [c - 1 if c != 0 else 0 for c in height]\n stack = []\n for k in range(len(ceng)):\n if ceng[k] == 1:\n if stack != []:\n res += k - stack.pop() - 1\n stack.append(k)\... | <|body_start_0|>
res = 0
while height.count(0) != len(height):
ceng = [c != 0 for c in height]
height = [c - 1 if c != 0 else 0 for c in height]
stack = []
for k in range(len(ceng)):
if ceng[k] == 1:
if stack != []:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
while height.count(0) != len(heigh... | stack_v2_sparse_classes_36k_train_002159 | 1,691 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap2",
"signature": "def trap2(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "trap",
"signature": "def trap(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007546 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap2(self, height): :type height: List[int] :rtype: int
- def trap(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def trap2(self, height): :type height: List[int] :rtype: int
- def trap(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def trap2(self, heig... | 3dec0f75cb9c04c3eed05eb87eb59254ec0b379a | <|skeleton|>
class Solution:
def trap2(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def trap(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def trap2(self, height):
""":type height: List[int] :rtype: int"""
res = 0
while height.count(0) != len(height):
ceng = [c != 0 for c in height]
height = [c - 1 if c != 0 else 0 for c in height]
stack = []
for k in range(len(cen... | the_stack_v2_python_sparse | 42. Trapping Rain Water.py | cosJin/top100liked | train | 0 | |
14c22047a04b3ec9cac12a21dd33cb0eec3d29f7 | [
"for event in events:\n queue.get()\n print(event)",
"events = ['operation: creating base image', 'Total: 1 packages', 'Fetched ', 'Completed ', 'operation: done creating base image', 'operation: creating developer image', 'operation: done creating developer image', 'operation: creating test image', 'operat... | <|body_start_0|>
for event in events:
queue.get()
print(event)
<|end_body_0|>
<|body_start_1|>
events = ['operation: creating base image', 'Total: 1 packages', 'Fetched ', 'Completed ', 'operation: done creating base image', 'operation: creating developer image', 'operation: don... | Test class for image_lib.BrilloImageOperation. | BrilloImageOperationTest | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrilloImageOperationTest:
"""Test class for image_lib.BrilloImageOperation."""
def BrilloImageFake(self, events, queue):
"""Test function to emulate brillo image."""
<|body_0|>
def testParseOutputBaseImageStage(self):
"""Test Base Image Creation Stage."""
... | stack_v2_sparse_classes_36k_train_002160 | 14,494 | permissive | [
{
"docstring": "Test function to emulate brillo image.",
"name": "BrilloImageFake",
"signature": "def BrilloImageFake(self, events, queue)"
},
{
"docstring": "Test Base Image Creation Stage.",
"name": "testParseOutputBaseImageStage",
"signature": "def testParseOutputBaseImageStage(self)"... | 6 | null | Implement the Python class `BrilloImageOperationTest` described below.
Class description:
Test class for image_lib.BrilloImageOperation.
Method signatures and docstrings:
- def BrilloImageFake(self, events, queue): Test function to emulate brillo image.
- def testParseOutputBaseImageStage(self): Test Base Image Creat... | Implement the Python class `BrilloImageOperationTest` described below.
Class description:
Test class for image_lib.BrilloImageOperation.
Method signatures and docstrings:
- def BrilloImageFake(self, events, queue): Test function to emulate brillo image.
- def testParseOutputBaseImageStage(self): Test Base Image Creat... | e71f21b9b4b9b839f5093301974a45545dad2691 | <|skeleton|>
class BrilloImageOperationTest:
"""Test class for image_lib.BrilloImageOperation."""
def BrilloImageFake(self, events, queue):
"""Test function to emulate brillo image."""
<|body_0|>
def testParseOutputBaseImageStage(self):
"""Test Base Image Creation Stage."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BrilloImageOperationTest:
"""Test class for image_lib.BrilloImageOperation."""
def BrilloImageFake(self, events, queue):
"""Test function to emulate brillo image."""
for event in events:
queue.get()
print(event)
def testParseOutputBaseImageStage(self):
... | the_stack_v2_python_sparse | third_party/chromite/lib/image_lib_unittest.py | zenoalbisser/chromium | train | 0 |
ced2d9b715e2c0f1d0c57e331383cda2eaa99552 | [
"logger.debug('Start clean data in UpdateUserForm.')\nname = self.cleaned_data.get('name')\nphone = self.cleaned_data.get('phone')\ndate_of_birth = self.cleaned_data.get('date_of_birth')\nself.validator_all(name, phone, date_of_birth)\nlogger.debug('Exit clean data in UpdateUserForm.')",
"logger.debug('Start vali... | <|body_start_0|>
logger.debug('Start clean data in UpdateUserForm.')
name = self.cleaned_data.get('name')
phone = self.cleaned_data.get('phone')
date_of_birth = self.cleaned_data.get('date_of_birth')
self.validator_all(name, phone, date_of_birth)
logger.debug('Exit clean ... | Form to update the users. | UpdateUserForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
<|body_0|>
def validator_all(self, name, phone, date_of_birth):
"""Checks validator in all fields."""
<|body_1|>
def verify_password(self, password):
"""V... | stack_v2_sparse_classes_36k_train_002161 | 2,539 | permissive | [
{
"docstring": "Get user fields.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Checks validator in all fields.",
"name": "validator_all",
"signature": "def validator_all(self, name, phone, date_of_birth)"
},
{
"docstring": "Verifies if the given password ma... | 3 | stack_v2_sparse_classes_30k_train_012081 | Implement the Python class `UpdateUserForm` described below.
Class description:
Form to update the users.
Method signatures and docstrings:
- def clean(self): Get user fields.
- def validator_all(self, name, phone, date_of_birth): Checks validator in all fields.
- def verify_password(self, password): Verifies if the ... | Implement the Python class `UpdateUserForm` described below.
Class description:
Form to update the users.
Method signatures and docstrings:
- def clean(self): Get user fields.
- def validator_all(self, name, phone, date_of_birth): Checks validator in all fields.
- def verify_password(self, password): Verifies if the ... | 5387eb80dfb354e948abe64f7d8bbe087fc4f136 | <|skeleton|>
class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
<|body_0|>
def validator_all(self, name, phone, date_of_birth):
"""Checks validator in all fields."""
<|body_1|>
def verify_password(self, password):
"""V... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateUserForm:
"""Form to update the users."""
def clean(self):
"""Get user fields."""
logger.debug('Start clean data in UpdateUserForm.')
name = self.cleaned_data.get('name')
phone = self.cleaned_data.get('phone')
date_of_birth = self.cleaned_data.get('date_of_bi... | the_stack_v2_python_sparse | medical_prescription/user/forms/updateuserform.py | ristovao/2017.2-Receituario-Medico | train | 0 |
f82a24c586be711f7508f3d18bbc07d2d9a63cd7 | [
"f = open(taz_data_path, 'r')\nall_lines = f.readlines()\nf.close()\nidx = 0\nwhile all_lines[idx][0].isalpha():\n idx += 1\nfor a_line in all_lines[idx:]:\n if len(a_line) == 0:\n break\n if not a_line[0].isspace():\n raise SyntaxError('Syntax error in ' + taz_data_path)\n if '\\t' in a_l... | <|body_start_0|>
f = open(taz_data_path, 'r')
all_lines = f.readlines()
f.close()
idx = 0
while all_lines[idx][0].isalpha():
idx += 1
for a_line in all_lines[idx:]:
if len(a_line) == 0:
break
if not a_line[0].isspace():
... | Pre-checks to run on the data given to emme2. Could be run every time emme2 is run. | CheckTravelModelInput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckTravelModelInput:
"""Pre-checks to run on the data given to emme2. Could be run every time emme2 is run."""
def check_syntax_of_emme2_input_tazdata(self, taz_data_path):
"""TAZDATA.MA2 needs to have the header at the top. There should be no leading spaces for the header. The dat... | stack_v2_sparse_classes_36k_train_002162 | 3,566 | no_license | [
{
"docstring": "TAZDATA.MA2 needs to have the header at the top. There should be no leading spaces for the header. The data values need at least one leading space. Spaces and colons both count as white space. Throws an exception if there is a problem.",
"name": "check_syntax_of_emme2_input_tazdata",
"si... | 2 | null | Implement the Python class `CheckTravelModelInput` described below.
Class description:
Pre-checks to run on the data given to emme2. Could be run every time emme2 is run.
Method signatures and docstrings:
- def check_syntax_of_emme2_input_tazdata(self, taz_data_path): TAZDATA.MA2 needs to have the header at the top. ... | Implement the Python class `CheckTravelModelInput` described below.
Class description:
Pre-checks to run on the data given to emme2. Could be run every time emme2 is run.
Method signatures and docstrings:
- def check_syntax_of_emme2_input_tazdata(self, taz_data_path): TAZDATA.MA2 needs to have the header at the top. ... | c392d15b35aa1d47bbc185ed76314f8e6dd9f92f | <|skeleton|>
class CheckTravelModelInput:
"""Pre-checks to run on the data given to emme2. Could be run every time emme2 is run."""
def check_syntax_of_emme2_input_tazdata(self, taz_data_path):
"""TAZDATA.MA2 needs to have the header at the top. There should be no leading spaces for the header. The dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckTravelModelInput:
"""Pre-checks to run on the data given to emme2. Could be run every time emme2 is run."""
def check_syntax_of_emme2_input_tazdata(self, taz_data_path):
"""TAZDATA.MA2 needs to have the header at the top. There should be no leading spaces for the header. The data values need... | the_stack_v2_python_sparse | opus_emme2/check_travel_model_input.py | psrc/urbansim | train | 4 |
7c9ff0b45db87c652e3861d436b59f59a5344f3d | [
"self.key = key\nself.subjectid = subjectid\nself.region_ids = set([])\nself.set_regions()",
"d = _dictp(JSON_FILE)\nregions = d.getp(self.key).get('regions')\nfor key, region in regions.items():\n assert isinstance(region, dict)\n if self.subjectid is None:\n self.region_ids.add(key)\n else:\n ... | <|body_start_0|>
self.key = key
self.subjectid = subjectid
self.region_ids = set([])
self.set_regions()
<|end_body_0|>
<|body_start_1|>
d = _dictp(JSON_FILE)
regions = d.getp(self.key).get('regions')
for key, region in regions.items():
assert isinstan... | really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject (fish) | Subject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject... | stack_v2_sparse_classes_36k_train_002163 | 28,538 | no_license | [
{
"docstring": "(str, str) Key is the unique key for the image, subjectid is set as an integer to uniquely identify a subject",
"name": "__init__",
"signature": "def __init__(self, key, subjectid=None)"
},
{
"docstring": "Checks all regions defined on the image, regions which are defined on the ... | 3 | stack_v2_sparse_classes_30k_train_001580 | Implement the Python class `Subject` described below.
Class description:
really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are t... | Implement the Python class `Subject` described below.
Class description:
really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are t... | 9123aa6baf538b662143b9098d963d55165e8409 | <|skeleton|>
class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Subject:
"""really a fish object, has many regions Should not be accessed directly. Iterate through the Images class subjects_generator. If no subjectid is used to initialise the class, then the iterator will ignore subject assignmensts, ie all regions are treated as belonging to the same subject (fish)"""
... | the_stack_v2_python_sparse | opencvlib/imgpipes/vgg.py | gmonkman/python | train | 0 |
11ed8ad45e08fd9869f4b8a3d8fe57b8f2461de9 | [
"self.patience = patience\nself.verbose = verbose\nself.counter = 0\nself.best_score = None\nself.early_stop = False\nself.loss_min = np.Inf\nself.delta = delta\nself.trace_func = trace_func",
"score = loss\nif self.best_score is None:\n self.best_score = score\nelif self.best_score < score + self.delta:\n ... | <|body_start_0|>
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.loss_min = np.Inf
self.delta = delta
self.trace_func = trace_func
<|end_body_0|>
<|body_start_1|>
score = loss
... | Early stop blending algorithm if loss doesn't improve after a given patience | EarlyStopping | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Early stop blending algorithm if loss doesn't improve after a given patience"""
def __init__(self, patience=4, verbose=False, delta=0, trace_func=print) -> None:
"""[summary] Args: patience (int, optional): How long to wait after las time loss improved. Defaults to ... | stack_v2_sparse_classes_36k_train_002164 | 13,133 | no_license | [
{
"docstring": "[summary] Args: patience (int, optional): How long to wait after las time loss improved. Defaults to 10. verbose (bool, optional): If True, prints a message for each loss improvement. Defaults to False. delta (int, optional): Minimum change in the monitored quantity to qualify as an improvement.... | 2 | stack_v2_sparse_classes_30k_train_005130 | Implement the Python class `EarlyStopping` described below.
Class description:
Early stop blending algorithm if loss doesn't improve after a given patience
Method signatures and docstrings:
- def __init__(self, patience=4, verbose=False, delta=0, trace_func=print) -> None: [summary] Args: patience (int, optional): Ho... | Implement the Python class `EarlyStopping` described below.
Class description:
Early stop blending algorithm if loss doesn't improve after a given patience
Method signatures and docstrings:
- def __init__(self, patience=4, verbose=False, delta=0, trace_func=print) -> None: [summary] Args: patience (int, optional): Ho... | 50faaa8882a182e2d70ee358f28303c42c19e5db | <|skeleton|>
class EarlyStopping:
"""Early stop blending algorithm if loss doesn't improve after a given patience"""
def __init__(self, patience=4, verbose=False, delta=0, trace_func=print) -> None:
"""[summary] Args: patience (int, optional): How long to wait after las time loss improved. Defaults to ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
"""Early stop blending algorithm if loss doesn't improve after a given patience"""
def __init__(self, patience=4, verbose=False, delta=0, trace_func=print) -> None:
"""[summary] Args: patience (int, optional): How long to wait after las time loss improved. Defaults to 10. verbose (... | the_stack_v2_python_sparse | src/app/blending/utils.py | ManuLasker/ai_pet_webdemo | train | 3 |
ea46ad16a3451a9a60ce0d237dd551f2d4e11aef | [
"try:\n from thread import allocate_lock, start_new_thread\nexcept ImportError:\n from _thread import allocate_lock, start_new_thread\nself.func = None\nself.nthread = nthread\nself.__threadids = [None] * nthread\nself.__threads = [None] * nthread\nself.__returns = [None] * nthread\nfor it in range(nthread):\... | <|body_start_0|>
try:
from thread import allocate_lock, start_new_thread
except ImportError:
from _thread import allocate_lock, start_new_thread
self.func = None
self.nthread = nthread
self.__threadids = [None] * nthread
self.__threads = [None] * n... | A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int | ThreadPool | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadPool:
"""A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int"""
def __init__(self, nthread):
"""@param nthread: number of threads for the pool. @type nthread: int"""
<|body_0|... | stack_v2_sparse_classes_36k_train_002165 | 3,910 | permissive | [
{
"docstring": "@param nthread: number of threads for the pool. @type nthread: int",
"name": "__init__",
"signature": "def __init__(self, nthread)"
},
{
"docstring": "Event loop for the pre-created threads.",
"name": "eventloop",
"signature": "def eventloop(self, tdata)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_007450 | Implement the Python class `ThreadPool` described below.
Class description:
A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int
Method signatures and docstrings:
- def __init__(self, nthread): @param nthread: number of thre... | Implement the Python class `ThreadPool` described below.
Class description:
A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int
Method signatures and docstrings:
- def __init__(self, nthread): @param nthread: number of thre... | ff0c71c5081dc67522d42bc65719e16c8365ab47 | <|skeleton|>
class ThreadPool:
"""A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int"""
def __init__(self, nthread):
"""@param nthread: number of threads for the pool. @type nthread: int"""
<|body_0|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadPool:
"""A synchronized thread pool. The number of pre-created threads is not changeable. @ivar nthread: number of threads in the pool. @itype nthread: int"""
def __init__(self, nthread):
"""@param nthread: number of threads for the pool. @type nthread: int"""
try:
from ... | the_stack_v2_python_sparse | solvcon/mthread.py | gitter-badger/solvcon | train | 1 |
f2ee7f09cd7883b0a77fa7228113203c47f4fb27 | [
"limit = df[CLOSE].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[CLOSE], limit)",
"limit = df[DIF].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[DIF], limit)",
"limit = df[MACD].max()\nif limit > 0:\n return cls.__get_max_limit_tm(df[MACD], limit)",
"limits = series[series >= limi... | <|body_start_0|>
limit = df[CLOSE].max()
if limit > 0:
return cls.__get_max_limit_tm(df[CLOSE], limit)
<|end_body_0|>
<|body_start_1|>
limit = df[DIF].max()
if limit > 0:
return cls.__get_max_limit_tm(df[DIF], limit)
<|end_body_1|>
<|body_start_2|>
limit... | 检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD | MaxLimitDetect | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaxLimitDetect:
"""检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD"""
def get_close_limit_tm_in(cls, df):
"""获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:"""
<|body_0|>
def get_dif_limit_tm_in(cls, df):
"""获取区间内DIF最大值对应的... | stack_v2_sparse_classes_36k_train_002166 | 36,499 | no_license | [
{
"docstring": "获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:",
"name": "get_close_limit_tm_in",
"signature": "def get_close_limit_tm_in(cls, df)"
},
{
"docstring": "获取区间内DIF最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return... | 4 | null | Implement the Python class `MaxLimitDetect` described below.
Class description:
检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD
Method signatures and docstrings:
- def get_close_limit_tm_in(cls, df): 获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:
- def get_dif_limit_tm_in(cls... | Implement the Python class `MaxLimitDetect` described below.
Class description:
检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD
Method signatures and docstrings:
- def get_close_limit_tm_in(cls, df): 获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:
- def get_dif_limit_tm_in(cls... | 9446d33c0978c325c8b24a876ac2c42fe323dbe6 | <|skeleton|>
class MaxLimitDetect:
"""检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD"""
def get_close_limit_tm_in(cls, df):
"""获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:"""
<|body_0|>
def get_dif_limit_tm_in(cls, df):
"""获取区间内DIF最大值对应的... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaxLimitDetect:
"""检测极值:最大值的时间。用于检测3种极值的时间,3种极值分别是:DIF/CLOSE/MACD"""
def get_close_limit_tm_in(cls, df):
"""获取区间内CLOSE最大值对应的时间。 :param df: DataFrame类型, 相邻的金叉和死叉之间或两个金叉之间的所有数据[包含金叉点,不包含死叉点] :return:"""
limit = df[CLOSE].max()
if limit > 0:
return cls.__get_max_limit_tm(... | the_stack_v2_python_sparse | back_forecast/learn_quant/MACD/jukuan_macd_signal.py | lnkyzhang/wayToFreedomOfWealth | train | 3 |
f85bb3f42fe4a35f9b7daca320b18a99abd442ce | [
"array = [0] * length\nfor op in updates:\n start, end, inc = (op[0], op[1], op[2])\n cond1 = 0 <= start < length\n cond2 = 0 <= end < length\n if cond1 and cond2:\n for i in range(start, end + 1):\n array[i] += inc\nreturn array",
"array = [0] * length\nfor op in updates:\n start... | <|body_start_0|>
array = [0] * length
for op in updates:
start, end, inc = (op[0], op[1], op[2])
cond1 = 0 <= start < length
cond2 = 0 <= end < length
if cond1 and cond2:
for i in range(start, end + 1):
array[i] += inc
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getModifiedArray(self, length, updates):
"""Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]"""
<|body_0|>
def getModifiedArray2(self, length, updates):
"""Two passes: 1st pass... | stack_v2_sparse_classes_36k_train_002167 | 2,196 | no_license | [
{
"docstring": "Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]",
"name": "getModifiedArray",
"signature": "def getModifiedArray(self, length, updates)"
},
{
"docstring": "Two passes: 1st pass only make changes to the ... | 2 | stack_v2_sparse_classes_30k_train_014307 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getModifiedArray(self, length, updates): Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]
- def g... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getModifiedArray(self, length, updates): Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]
- def g... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def getModifiedArray(self, length, updates):
"""Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]"""
<|body_0|>
def getModifiedArray2(self, length, updates):
"""Two passes: 1st pass... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getModifiedArray(self, length, updates):
"""Brute force: TLE Time: O(KN), K = len(updates), N = length :type length: int :type updates: List[List[int]] :rtype: List[int]"""
array = [0] * length
for op in updates:
start, end, inc = (op[0], op[1], op[2])
... | the_stack_v2_python_sparse | py/leetcode_py/370.py | imsure/tech-interview-prep | train | 0 | |
06a72380412a61e31b47c4be5bda90006cbcfe97 | [
"form_valid = isinstance(response, HttpResponseRedirect)\nif request.POST.get('_save') and form_valid:\n return redirect('admin:index')\nreturn response",
"try:\n singleton = self.model.objects.get()\nexcept (self.model.DoesNotExist, self.model.MultipleObjectsReturned):\n kwargs.setdefault('extra_context... | <|body_start_0|>
form_valid = isinstance(response, HttpResponseRedirect)
if request.POST.get('_save') and form_valid:
return redirect('admin:index')
return response
<|end_body_0|>
<|body_start_1|>
try:
singleton = self.model.objects.get()
except (self.mod... | Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton attribute to the div contain... | SingletonAdmin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_36k_train_002168 | 3,870 | permissive | [
{
"docstring": "Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid.",
"name": "handle_save",
"signature": "def handle_save(self, request, response)"
},
{
"docstring": "Redirec... | 4 | stack_v2_sparse_classes_30k_train_007968 | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | Implement the Python class `SingletonAdmin` described below.
Class description:
Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your... | c4fad2fe2cacaa21dd252a7407a84229dd20a46c | <|skeleton|>
class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingletonAdmin:
"""Admin class for models that should only contain a single instance in the database. Redirect all views to the change view when the instance exists, and to the add view when it doesn't. *** NOTE:be sure to copy the change_form.html into your templates/admin/ directory and add a data-singleton... | the_stack_v2_python_sparse | backend/apps/utils/admin.py | MadeInHaus/django-template | train | 1 |
90dc6be698ff696618077f385a3f3ab30313a263 | [
"super(GetConnTests, self).setUp()\nconn = get_conn(verify=False)\nindex_name = settings.ELASTICSEARCH_INDEX\nconn.indices.delete(index_name)\nfrom search import indexing_api\nindexing_api._CONN = None\nindexing_api._CONN_VERIFIED = False",
"with self.assertRaises(ReindexException) as ex:\n get_conn()\nassert ... | <|body_start_0|>
super(GetConnTests, self).setUp()
conn = get_conn(verify=False)
index_name = settings.ELASTICSEARCH_INDEX
conn.indices.delete(index_name)
from search import indexing_api
indexing_api._CONN = None
indexing_api._CONN_VERIFIED = False
<|end_body_0|>
... | Tests for get_conn | GetConnTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_mapping(self):
"""Test that error is... | stack_v2_sparse_classes_36k_train_002169 | 14,428 | no_license | [
{
"docstring": "Start without any index",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that an error is raised if we don't have an index",
"name": "test_no_index",
"signature": "def test_no_index(self)"
},
{
"docstring": "Test that error is raised if we... | 3 | stack_v2_sparse_classes_30k_train_012658 | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_mapping(self): Test that error is raised if we d... | Implement the Python class `GetConnTests` described below.
Class description:
Tests for get_conn
Method signatures and docstrings:
- def setUp(self): Start without any index
- def test_no_index(self): Test that an error is raised if we don't have an index
- def test_no_mapping(self): Test that error is raised if we d... | 3c166bc52dfe8d7aa04f922134f4f6deeff49eb6 | <|skeleton|>
class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
<|body_0|>
def test_no_index(self):
"""Test that an error is raised if we don't have an index"""
<|body_1|>
def test_no_mapping(self):
"""Test that error is... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetConnTests:
"""Tests for get_conn"""
def setUp(self):
"""Start without any index"""
super(GetConnTests, self).setUp()
conn = get_conn(verify=False)
index_name = settings.ELASTICSEARCH_INDEX
conn.indices.delete(index_name)
from search import indexing_api
... | the_stack_v2_python_sparse | search/indexing_api_test.py | avontd2868/micromasters | train | 0 |
e401b6543aef324d411f8957034696d771c55e71 | [
"try:\n project = models.Project.objects.filter(pk=project_id)\n if not project:\n raise NotFound('ERROR_NOT_EXIST_PROJECT')\n return Response(project.values('name', 'code', 'introduction', 'state', 'tags'))\nexcept models.Project.DoesNotExist:\n raise NotFound('ERROR_NOT_EXIST_PROJECT')\nexcept ... | <|body_start_0|>
try:
project = models.Project.objects.filter(pk=project_id)
if not project:
raise NotFound('ERROR_NOT_EXIST_PROJECT')
return Response(project.values('name', 'code', 'introduction', 'state', 'tags'))
except models.Project.DoesNotExist:
... | ProjectAPIView | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectAPIView:
def get(self, request, project_id):
"""获取项目详细信息"""
<|body_0|>
def put(self, request, project_id):
"""更新项目信息"""
<|body_1|>
def delete(self, request, project_id):
"""删除项目"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_002170 | 4,497 | permissive | [
{
"docstring": "获取项目详细信息",
"name": "get",
"signature": "def get(self, request, project_id)"
},
{
"docstring": "更新项目信息",
"name": "put",
"signature": "def put(self, request, project_id)"
},
{
"docstring": "删除项目",
"name": "delete",
"signature": "def delete(self, request, pro... | 3 | stack_v2_sparse_classes_30k_train_018761 | Implement the Python class `ProjectAPIView` described below.
Class description:
Implement the ProjectAPIView class.
Method signatures and docstrings:
- def get(self, request, project_id): 获取项目详细信息
- def put(self, request, project_id): 更新项目信息
- def delete(self, request, project_id): 删除项目 | Implement the Python class `ProjectAPIView` described below.
Class description:
Implement the ProjectAPIView class.
Method signatures and docstrings:
- def get(self, request, project_id): 获取项目详细信息
- def put(self, request, project_id): 更新项目信息
- def delete(self, request, project_id): 删除项目
<|skeleton|>
class ProjectAPI... | 5bff2d94e6252c1689d6ae74529d0fd30fb20c0d | <|skeleton|>
class ProjectAPIView:
def get(self, request, project_id):
"""获取项目详细信息"""
<|body_0|>
def put(self, request, project_id):
"""更新项目信息"""
<|body_1|>
def delete(self, request, project_id):
"""删除项目"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectAPIView:
def get(self, request, project_id):
"""获取项目详细信息"""
try:
project = models.Project.objects.filter(pk=project_id)
if not project:
raise NotFound('ERROR_NOT_EXIST_PROJECT')
return Response(project.values('name', 'code', 'introduct... | the_stack_v2_python_sparse | studioapps/project/views.py | weicunheng/test-studio | train | 1 | |
20fefe8cf543fee8525213e4cfc0a527aa7beb3c | [
"def dbfn(storeConnection):\n decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)\n try:\n return appObj.ApiKeyManager.getAPIKeyDict(decodedJWTToken=decodedJWTToken, tenant=tenant, apiKeyID=apiKeyID, storeConnection=stor... | <|body_start_0|>
def dbfn(storeConnection):
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
try:
return appObj.ApiKeyManager.getAPIKeyDict(decodedJWTToken=decodedJWTToken, tenant=tenant... | Get API key data from id | APIKeysInfo | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class APIKeysInfo:
"""Get API key data from id"""
def get(self, tenant, apiKeyID):
"""Get apikey for login api to use"""
<|body_0|>
def delete(self, tenant, apiKeyID):
"""Delete API Key"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def dbfn(storeCon... | stack_v2_sparse_classes_36k_train_002171 | 9,554 | permissive | [
{
"docstring": "Get apikey for login api to use",
"name": "get",
"signature": "def get(self, tenant, apiKeyID)"
},
{
"docstring": "Delete API Key",
"name": "delete",
"signature": "def delete(self, tenant, apiKeyID)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008065 | Implement the Python class `APIKeysInfo` described below.
Class description:
Get API key data from id
Method signatures and docstrings:
- def get(self, tenant, apiKeyID): Get apikey for login api to use
- def delete(self, tenant, apiKeyID): Delete API Key | Implement the Python class `APIKeysInfo` described below.
Class description:
Get API key data from id
Method signatures and docstrings:
- def get(self, tenant, apiKeyID): Get apikey for login api to use
- def delete(self, tenant, apiKeyID): Delete API Key
<|skeleton|>
class APIKeysInfo:
"""Get API key data from ... | d3908c46614fb1b638553282cd72ba3634277495 | <|skeleton|>
class APIKeysInfo:
"""Get API key data from id"""
def get(self, tenant, apiKeyID):
"""Get apikey for login api to use"""
<|body_0|>
def delete(self, tenant, apiKeyID):
"""Delete API Key"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class APIKeysInfo:
"""Get API key data from id"""
def get(self, tenant, apiKeyID):
"""Get apikey for login api to use"""
def dbfn(storeConnection):
decodedJWTToken = verifyJWTTokenGivesUserWithAPIKeyPrivilagesAndReturnFormattedJWTToken(appObj=appObj, request=request, tenant=tenant)
... | the_stack_v2_python_sparse | services/src/APIlogin_APIKeys.py | rmetcalf9/saas_user_management_system | train | 1 |
185ba61c3bfed4b42b8272f8317ac3c7c6ee3149 | [
"self.dns_root = dns_root\nself.forest = forest\nself.identity = identity\nself.netbios_name = netbios_name\nself.parent_domain = parent_domain\nself.tombstone_days = tombstone_days",
"if dictionary is None:\n return None\ndns_root = dictionary.get('dnsRoot')\nforest = dictionary.get('forest')\nidentity = cohe... | <|body_start_0|>
self.dns_root = dns_root
self.forest = forest
self.identity = identity
self.netbios_name = netbios_name
self.parent_domain = parent_domain
self.tombstone_days = tombstone_days
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
ret... | Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies AD NetBIOS name. parent_domain (stri... | AdDomain | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies ... | stack_v2_sparse_classes_36k_train_002172 | 2,708 | permissive | [
{
"docstring": "Constructor for the AdDomain class",
"name": "__init__",
"signature": "def __init__(self, dns_root=None, forest=None, identity=None, netbios_name=None, parent_domain=None, tombstone_days=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | null | Implement the Python class `AdDomain` described below.
Class description:
Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the do... | Implement the Python class `AdDomain` described below.
Class description:
Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the do... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies AD NetBIOS na... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_domain.py | cohesity/management-sdk-python | train | 24 |
8ed9114963a5ae6745ce47fbe24e26786d3ad766 | [
"self._clip_reward = clip_reward\nself.intrinsic_model = intrinsic_rewards.RNDIntrinsicReward(sess=sess, tf_device=tf_device, summary_writer=summary_writer)\nsuper(RNDDQNAgent, self).__init__(sess=sess, num_actions=num_actions, observation_shape=observation_shape, gamma=gamma, update_horizon=update_horizon, min_rep... | <|body_start_0|>
self._clip_reward = clip_reward
self.intrinsic_model = intrinsic_rewards.RNDIntrinsicReward(sess=sess, tf_device=tf_device, summary_writer=summary_writer)
super(RNDDQNAgent, self).__init__(sess=sess, num_actions=num_actions, observation_shape=observation_shape, gamma=gamma, upda... | Implements a DQN agent with a RND intrinsic reward. | RNDDQNAgent | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_... | stack_v2_sparse_classes_36k_train_002173 | 10,489 | permissive | [
{
"docstring": "Initializes the agent and constructs the components of its graph. Args: sess: `tf.Session`, for executing ops. num_actions: int, number of actions the agent can take at any state. observation_shape: tuple of ints describing the observation shape. gamma: float, discount factor with the usual RL m... | 2 | stack_v2_sparse_classes_30k_train_014493 | Implement the Python class `RNDDQNAgent` described below.
Class description:
Implements a DQN agent with a RND intrinsic reward.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=200... | Implement the Python class `RNDDQNAgent` described below.
Class description:
Implements a DQN agent with a RND intrinsic reward.
Method signatures and docstrings:
- def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=200... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNDDQNAgent:
"""Implements a DQN agent with a RND intrinsic reward."""
def __init__(self, sess, num_actions, observation_shape=base_dqn_agent.NATURE_DQN_OBSERVATION_SHAPE, gamma=0.99, update_horizon=1, min_replay_history=20000, update_period=4, target_update_period=8000, epsilon_fn=linearly_decaying_epsi... | the_stack_v2_python_sparse | bonus_based_exploration/intrinsic_motivation/intrinsic_dqn_agent.py | Jimmy-INL/google-research | train | 1 |
5cc06d7b28f74db07919c51ec63fba673e933e54 | [
"n = 3\nk = 2\ninput_bytes = b'abcdefgh' + b'ijklmnop'\noutput_shares = botan.zfec_encode(k, n, input_bytes)\nself.assertEqual(output_shares, [b'abcdefgh', b'ijklmnop', b'qrstuvwX'])",
"def byte_iter():\n b = 0\n while True:\n yield bytes([b])\n b = (b + 1) % 256\nrandom_bytes = byte_iter()\nf... | <|body_start_0|>
n = 3
k = 2
input_bytes = b'abcdefgh' + b'ijklmnop'
output_shares = botan.zfec_encode(k, n, input_bytes)
self.assertEqual(output_shares, [b'abcdefgh', b'ijklmnop', b'qrstuvwX'])
<|end_body_0|>
<|body_start_1|>
def byte_iter():
b = 0
... | Tests relating to the ZFEC bindings | BotanPythonZfecTests | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BotanPythonZfecTests:
"""Tests relating to the ZFEC bindings"""
def test_encode(self):
"""Simple encoder test. Could benefit from more variations"""
<|body_0|>
def test_encode_decode(self):
"""Simple round-trip tests."""
<|body_1|>
def _encode_decode... | stack_v2_sparse_classes_36k_train_002174 | 41,200 | permissive | [
{
"docstring": "Simple encoder test. Could benefit from more variations",
"name": "test_encode",
"signature": "def test_encode(self)"
},
{
"docstring": "Simple round-trip tests.",
"name": "test_encode_decode",
"signature": "def test_encode_decode(self)"
},
{
"docstring": "one ins... | 3 | stack_v2_sparse_classes_30k_train_003076 | Implement the Python class `BotanPythonZfecTests` described below.
Class description:
Tests relating to the ZFEC bindings
Method signatures and docstrings:
- def test_encode(self): Simple encoder test. Could benefit from more variations
- def test_encode_decode(self): Simple round-trip tests.
- def _encode_decode_tes... | Implement the Python class `BotanPythonZfecTests` described below.
Class description:
Tests relating to the ZFEC bindings
Method signatures and docstrings:
- def test_encode(self): Simple encoder test. Could benefit from more variations
- def test_encode_decode(self): Simple round-trip tests.
- def _encode_decode_tes... | 560aec3a8bfa2456cc309bac478aca9ae53f0fff | <|skeleton|>
class BotanPythonZfecTests:
"""Tests relating to the ZFEC bindings"""
def test_encode(self):
"""Simple encoder test. Could benefit from more variations"""
<|body_0|>
def test_encode_decode(self):
"""Simple round-trip tests."""
<|body_1|>
def _encode_decode... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BotanPythonZfecTests:
"""Tests relating to the ZFEC bindings"""
def test_encode(self):
"""Simple encoder test. Could benefit from more variations"""
n = 3
k = 2
input_bytes = b'abcdefgh' + b'ijklmnop'
output_shares = botan.zfec_encode(k, n, input_bytes)
sel... | the_stack_v2_python_sparse | src/scripts/test_python.py | randombit/botan | train | 2,362 |
c1b3571c1db4c4ad2562061ebbd1de87d411d3e2 | [
"story_ids = topic.get_canonical_story_ids()\nexisting_story_ids = set(stories_dict.keys()).intersection(story_ids)\nexp_ids: List[str] = list(itertools.chain.from_iterable((stories_dict[story_id].story_contents.get_all_linked_exp_ids() for story_id in existing_story_ids)))\nexisting_exp_ids = set(exps_dict.keys())... | <|body_start_0|>
story_ids = topic.get_canonical_story_ids()
existing_story_ids = set(stories_dict.keys()).intersection(story_ids)
exp_ids: List[str] = list(itertools.chain.from_iterable((stories_dict[story_id].story_contents.get_all_linked_exp_ids() for story_id in existing_story_ids)))
... | Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job. | GenerateExplorationOpportunitySummariesJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateExplorationOpportunitySummariesJob:
"""Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job."""
def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_dom... | stack_v2_sparse_classes_36k_train_002175 | 17,468 | permissive | [
{
"docstring": "Generate opportunities related to a topic. Args: topic: Topic. Topic for which to generate the opportunities. stories_dict: dict(str, Story). All stories in the datastore, keyed by their ID. exps_dict: dict(str, Exploration). All explorations in the datastore, keyed by their ID. Returns: dict(st... | 2 | stack_v2_sparse_classes_30k_train_019321 | Implement the Python class `GenerateExplorationOpportunitySummariesJob` described below.
Class description:
Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.
Method signatures and docstrings:
- def _generate_opportunities_related_t... | Implement the Python class `GenerateExplorationOpportunitySummariesJob` described below.
Class description:
Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job.
Method signatures and docstrings:
- def _generate_opportunities_related_t... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class GenerateExplorationOpportunitySummariesJob:
"""Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job."""
def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_dom... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GenerateExplorationOpportunitySummariesJob:
"""Job that regenerates ExplorationOpportunitySummaryModel. NOTE: The DeleteExplorationOpportunitySummariesJob must be run before this job."""
def _generate_opportunities_related_to_topic(topic: topic_domain.Topic, stories_dict: Dict[str, story_domain.Story], e... | the_stack_v2_python_sparse | core/jobs/batch_jobs/opportunity_management_jobs.py | oppia/oppia | train | 6,172 |
c62aec4f31195ec2a94f985c8b7a65d59111b571 | [
"anomalies = cls._FetchUntriagedAnomalies()\nrecovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)\nmap(_AddLogForRecoveredAnomaly, recovered_anomalies)",
"anomalies = []\nfutures = []\nsheriff_keys = sheriff.Sheriff.query().fetch(keys_only=True)\nfor key in sheriff_keys:\n query = anomaly.Anomaly.... | <|body_start_0|>
anomalies = cls._FetchUntriagedAnomalies()
recovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)
map(_AddLogForRecoveredAnomaly, recovered_anomalies)
<|end_body_0|>
<|body_start_1|>
anomalies = []
futures = []
sheriff_keys = sheriff.Sheriff.q... | Class for triaging anomalies. | TriageAnomalies | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
<|body_0|>
def _FetchUntriagedAnomalies(cls):
"""Fetches recent untriaged anomalies asynchronously from all sheriffs."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_002176 | 9,110 | permissive | [
{
"docstring": "Processes anomalies.",
"name": "Process",
"signature": "def Process(cls)"
},
{
"docstring": "Fetches recent untriaged anomalies asynchronously from all sheriffs.",
"name": "_FetchUntriagedAnomalies",
"signature": "def _FetchUntriagedAnomalies(cls)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001320 | Implement the Python class `TriageAnomalies` described below.
Class description:
Class for triaging anomalies.
Method signatures and docstrings:
- def Process(cls): Processes anomalies.
- def _FetchUntriagedAnomalies(cls): Fetches recent untriaged anomalies asynchronously from all sheriffs. | Implement the Python class `TriageAnomalies` described below.
Class description:
Class for triaging anomalies.
Method signatures and docstrings:
- def Process(cls): Processes anomalies.
- def _FetchUntriagedAnomalies(cls): Fetches recent untriaged anomalies asynchronously from all sheriffs.
<|skeleton|>
class Triage... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
<|body_0|>
def _FetchUntriagedAnomalies(cls):
"""Fetches recent untriaged anomalies asynchronously from all sheriffs."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TriageAnomalies:
"""Class for triaging anomalies."""
def Process(cls):
"""Processes anomalies."""
anomalies = cls._FetchUntriagedAnomalies()
recovered_anomalies = _FindAndUpdateRecoveredAnomalies(anomalies)
map(_AddLogForRecoveredAnomaly, recovered_anomalies)
def _Fet... | the_stack_v2_python_sparse | third_party/catapult/dashboard/dashboard/auto_triage.py | metux/chromium-suckless | train | 5 |
c3c3fde184da253638c3d2551198d48154dcec03 | [
"num = n\ncount = 0\nwhile num > 0:\n num -= 9 * 10 ** count * (count + 1)\n count += 1\nbits = count - 1\nbitsSumBefore = 0\nfor i in range(1, bits + 1):\n bitsSumBefore += 10 ** (i - 1) * 9 * i\nret1, ret2 = divmod(n - bitsSumBefore, bits + 1)\nreturn int(str(10 ** bits + ret1 - 1)[bits]) if ret2 == 0 el... | <|body_start_0|>
num = n
count = 0
while num > 0:
num -= 9 * 10 ** count * (count + 1)
count += 1
bits = count - 1
bitsSumBefore = 0
for i in range(1, bits + 1):
bitsSumBefore += 10 ** (i - 1) * 9 * i
ret1, ret2 = divmod(n - bit... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit2(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = n
count = 0
while num > 0:
num -... | stack_v2_sparse_classes_36k_train_002177 | 1,219 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit",
"signature": "def findNthDigit(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "findNthDigit2",
"signature": "def findNthDigit2(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017990 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findNthDigit(self, n): :type n: int :rtype: int
- def findNthDigit2(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 findNthDigit(self, n): :type n: int :rtype: int
- def findNthDigit2(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def findNthDigit(self, n):
"... | b9b302841100551b837c01be4ea6ad3aaade748e | <|skeleton|>
class Solution:
def findNthDigit(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def findNthDigit2(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 findNthDigit(self, n):
""":type n: int :rtype: int"""
num = n
count = 0
while num > 0:
num -= 9 * 10 ** count * (count + 1)
count += 1
bits = count - 1
bitsSumBefore = 0
for i in range(1, bits + 1):
bitsS... | the_stack_v2_python_sparse | 201610_Week3/20161020_1.py | Troy-Wang/LeetCode | train | 0 | |
bcf1b9c13fa954c345b9ae9778b1cea8e402d049 | [
"super(Proj, self).__init__()\nself.clamp_min = ClampMin()\nself.min_norm = min_norm\nself.norm_k = Norm(axis=-1, keep_dims=True)\nself.maxnorm = 1 - 0.004",
"norm = self.clamp_min(self.norm_k(x), self.min_norm)\nmaxnorm = self.maxnorm / c ** 0.5\ncond = norm > maxnorm\nprojected = x / norm * maxnorm\nreturn mnp.... | <|body_start_0|>
super(Proj, self).__init__()
self.clamp_min = ClampMin()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.maxnorm = 1 - 0.004
<|end_body_0|>
<|body_start_1|>
norm = self.clamp_min(self.norm_k(x), self.min_norm)
maxnorm = ... | proj class | Proj | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Proj:
"""proj class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Proj, self).__init__()
self.clamp_min = ClampMin()
... | stack_v2_sparse_classes_36k_train_002178 | 8,596 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, min_norm)"
},
{
"docstring": "class construction",
"name": "construct",
"signature": "def construct(self, x, c)"
}
] | 2 | null | Implement the Python class `Proj` described below.
Class description:
proj class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, x, c): class construction | Implement the Python class `Proj` described below.
Class description:
proj class
Method signatures and docstrings:
- def __init__(self, min_norm): init fun
- def construct(self, x, c): class construction
<|skeleton|>
class Proj:
"""proj class"""
def __init__(self, min_norm):
"""init fun"""
<... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class Proj:
"""proj class"""
def __init__(self, min_norm):
"""init fun"""
<|body_0|>
def construct(self, x, c):
"""class construction"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Proj:
"""proj class"""
def __init__(self, min_norm):
"""init fun"""
super(Proj, self).__init__()
self.clamp_min = ClampMin()
self.min_norm = min_norm
self.norm_k = Norm(axis=-1, keep_dims=True)
self.maxnorm = 1 - 0.004
def construct(self, x, c):
... | the_stack_v2_python_sparse | research/nlp/hypertext/src/poincare.py | mindspore-ai/models | train | 301 |
f4c16a2fa10d2e6ab9031260a8da16039fec0769 | [
"self._email = email\nself._pw = pw\nself._driver = self._get_driver()\ntry:\n self._login()\nexcept Exception as exc:\n print('Problem logging in: ')\n raise",
"try:\n return webdriver.PhantomJS()\nexcept Exception:\n return webdriver.Firefox()",
"self._driver.get(LOGIN_URL)\nself._driver.find_e... | <|body_start_0|>
self._email = email
self._pw = pw
self._driver = self._get_driver()
try:
self._login()
except Exception as exc:
print('Problem logging in: ')
raise
<|end_body_0|>
<|body_start_1|>
try:
return webdriver.Phan... | Packt | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Packt:
def __init__(self, email, pw):
"""setup"""
<|body_0|>
def _get_driver(self):
"""safaribooks py webscraping 2nd ed 9781786462589/"""
<|body_1|>
def _login(self):
"""login to site"""
<|body_2|>
def get_books(self):
"""go... | stack_v2_sparse_classes_36k_train_002179 | 2,129 | no_license | [
{
"docstring": "setup",
"name": "__init__",
"signature": "def __init__(self, email, pw)"
},
{
"docstring": "safaribooks py webscraping 2nd ed 9781786462589/",
"name": "_get_driver",
"signature": "def _get_driver(self)"
},
{
"docstring": "login to site",
"name": "_login",
... | 5 | null | Implement the Python class `Packt` described below.
Class description:
Implement the Packt class.
Method signatures and docstrings:
- def __init__(self, email, pw): setup
- def _get_driver(self): safaribooks py webscraping 2nd ed 9781786462589/
- def _login(self): login to site
- def get_books(self): go to ebooks tab... | Implement the Python class `Packt` described below.
Class description:
Implement the Packt class.
Method signatures and docstrings:
- def __init__(self, email, pw): setup
- def _get_driver(self): safaribooks py webscraping 2nd ed 9781786462589/
- def _login(self): login to site
- def get_books(self): go to ebooks tab... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Packt:
def __init__(self, email, pw):
"""setup"""
<|body_0|>
def _get_driver(self):
"""safaribooks py webscraping 2nd ed 9781786462589/"""
<|body_1|>
def _login(self):
"""login to site"""
<|body_2|>
def get_books(self):
"""go... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Packt:
def __init__(self, email, pw):
"""setup"""
self._email = email
self._pw = pw
self._driver = self._get_driver()
try:
self._login()
except Exception as exc:
print('Problem logging in: ')
raise
def _get_driver(self):
... | the_stack_v2_python_sparse | _algorithms_challenges/pybites/100DaysOfCode-master/066/packt.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
337eddbef26f1ccbfe0db7343b8bfe540a7d8811 | [
"c, h = carry\nhidden_features = h.shape[-1]\n\ndef _concat_dense(inputs, params, use_bias=True):\n kernels, biases = zip(*params.values())\n kernel = jnp.asarray(jnp.concatenate(kernels, axis=-1), jnp.float32)\n y = jnp.dot(inputs, kernel)\n if use_bias:\n bias = jnp.asarray(jnp.concatenate(bias... | <|body_start_0|>
c, h = carry
hidden_features = h.shape[-1]
def _concat_dense(inputs, params, use_bias=True):
kernels, biases = zip(*params.values())
kernel = jnp.asarray(jnp.concatenate(kernels, axis=-1), jnp.float32)
y = jnp.dot(inputs, kernel)
... | DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state components before matmul. Parameters are compatible with `flax.nn.LSTMCell`. | OptimizedLSTMCell | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptimizedLSTMCell:
"""DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state components before matmul. Parameters a... | stack_v2_sparse_classes_36k_train_002180 | 16,408 | permissive | [
{
"docstring": "A long short-term memory (LSTM) cell. the mathematical definition of the cell is as follows .. math:: \\\\begin{array}{ll} i = \\\\sigma(W_{ii} x + W_{hi} h + b_{hi}) \\\\\\\\ f = \\\\sigma(W_{if} x + W_{hf} h + b_{hf}) \\\\\\\\ g = \\\\tanh(W_{ig} x + W_{hg} h + b_{hg}) \\\\\\\\ o = \\\\sigma(W... | 2 | stack_v2_sparse_classes_30k_train_016879 | Implement the Python class `OptimizedLSTMCell` described below.
Class description:
DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state... | Implement the Python class `OptimizedLSTMCell` described below.
Class description:
DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state... | 87a483b2b93fa1dd7934da520348e6ce8d7851b4 | <|skeleton|>
class OptimizedLSTMCell:
"""DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state components before matmul. Parameters a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OptimizedLSTMCell:
"""DEPRECATION WARNING: The `flax.nn` module is Deprecated, use `flax.linen` instead. Learn more and find an upgrade guide at https://github.com/google/flax/blob/master/flax/linen/README.md" More efficient LSTM Cell that concatenates state components before matmul. Parameters are compatible... | the_stack_v2_python_sparse | flax/nn/recurrent.py | marcvanzee/flax | train | 3 |
80129edcefe5ee72f4174f8b26a36f06ff007080 | [
"self.to = to\nself.support_phone = support_phone\nself.subject = subject\nself.first_name = first_name\nself.brand_color = brand_color\nself.brand_logo = brand_logo\nself.institution_name = institution_name\nself.institution_address = institution_address\nself.signature = signature\nself.additional_properties = ad... | <|body_start_0|>
self.to = to
self.support_phone = support_phone
self.subject = subject
self.first_name = first_name
self.brand_color = brand_color
self.brand_logo = brand_logo
self.institution_name = institution_name
self.institution_address = institution... | Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email. This field is optional. This is also available in the Finicity Developer Portal. sub... | ConnectEmailOptions | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectEmailOptions:
"""Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email. This field is optional. This is also ... | stack_v2_sparse_classes_36k_train_002181 | 4,945 | permissive | [
{
"docstring": "Constructor for the ConnectEmailOptions class",
"name": "__init__",
"signature": "def __init__(self, to=None, support_phone=None, subject=None, first_name=None, brand_color=None, brand_logo=None, institution_name=None, institution_address=None, signature=None, additional_properties={})"
... | 2 | stack_v2_sparse_classes_30k_train_009716 | Implement the Python class `ConnectEmailOptions` described below.
Class description:
Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email... | Implement the Python class `ConnectEmailOptions` described below.
Class description:
Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class ConnectEmailOptions:
"""Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email. This field is optional. This is also ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectEmailOptions:
"""Implementation of the 'Connect Email Options' model. Customizable email details Attributes: to (string): The email address you wish to receive the email support_phone (string): Phone number that will be listed for support in the email. This field is optional. This is also available in ... | the_stack_v2_python_sparse | finicityapi/models/connect_email_options.py | monarchmoney/finicity-python | train | 0 |
d53b630b93502f2da5afbaad1d72ae347ddf1ccb | [
"try:\n ArgsMetaschemaProperty.instance2args(obj)\n KwargsMetaschemaProperty.instance2kwargs(obj)\n return True\nexcept MetaschemaTypeError:\n if raise_errors:\n raise ValueError(\"Class dosn't have an input_args attribute.\")\n return False",
"args = ArgsMetaschemaProperty.instance2args(obj... | <|body_start_0|>
try:
ArgsMetaschemaProperty.instance2args(obj)
KwargsMetaschemaProperty.instance2kwargs(obj)
return True
except MetaschemaTypeError:
if raise_errors:
raise ValueError("Class dosn't have an input_args attribute.")
... | Type for evaluating instances of Python classes. | InstanceMetaschemaType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceMetaschemaType:
"""Type for evaluating instances of Python classes."""
def validate(cls, obj, raise_errors=False):
"""Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised... | stack_v2_sparse_classes_36k_train_002182 | 4,172 | permissive | [
{
"docstring": "Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the object fails to be validated. Defaults to False. Returns: bool: True if the object could be of this type, False otherwise.",
... | 4 | null | Implement the Python class `InstanceMetaschemaType` described below.
Class description:
Type for evaluating instances of Python classes.
Method signatures and docstrings:
- def validate(cls, obj, raise_errors=False): Validate an object to check if it could be of this type. Args: obj (object): Object to validate. rais... | Implement the Python class `InstanceMetaschemaType` described below.
Class description:
Type for evaluating instances of Python classes.
Method signatures and docstrings:
- def validate(cls, obj, raise_errors=False): Validate an object to check if it could be of this type. Args: obj (object): Object to validate. rais... | dcc4d75a4d2c6aaa7e50e75095a16df1df6b2b0a | <|skeleton|>
class InstanceMetaschemaType:
"""Type for evaluating instances of Python classes."""
def validate(cls, obj, raise_errors=False):
"""Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceMetaschemaType:
"""Type for evaluating instances of Python classes."""
def validate(cls, obj, raise_errors=False):
"""Validate an object to check if it could be of this type. Args: obj (object): Object to validate. raise_errors (bool, optional): If True, errors will be raised when the obj... | the_stack_v2_python_sparse | yggdrasil/metaschema/datatypes/InstanceMetaschemaType.py | leighmatth/yggdrasil | train | 0 |
f96bd47755255aaf662c4fa06d39cfd77f07de2c | [
"self._topic = topic\nself._name = name\nself._action_type = action_type\nself.timeout = 1\nself.action_result = None\nself.prefered_callback = ' '\nSubscriber('mock/' + name, String, self.receive_commands)\nSubscriber('mock/gui_result', Bool, self.set_gui_result)\nself._server = ActionServer(self._topic, self._act... | <|body_start_0|>
self._topic = topic
self._name = name
self._action_type = action_type
self.timeout = 1
self.action_result = None
self.prefered_callback = ' '
Subscriber('mock/' + name, String, self.receive_commands)
Subscriber('mock/gui_result', Bool, sel... | MockActionServer base class | MockActionServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MockActionServer:
"""MockActionServer base class"""
def __init__(self, name, topic, action_type):
"""Creating a custom mock action server."""
<|body_0|>
def receive_commands(self, msg):
"""Decides the result of the next call."""
<|body_1|>
def decide... | stack_v2_sparse_classes_36k_train_002183 | 4,576 | no_license | [
{
"docstring": "Creating a custom mock action server.",
"name": "__init__",
"signature": "def __init__(self, name, topic, action_type)"
},
{
"docstring": "Decides the result of the next call.",
"name": "receive_commands",
"signature": "def receive_commands(self, msg)"
},
{
"docst... | 4 | stack_v2_sparse_classes_30k_train_011964 | Implement the Python class `MockActionServer` described below.
Class description:
MockActionServer base class
Method signatures and docstrings:
- def __init__(self, name, topic, action_type): Creating a custom mock action server.
- def receive_commands(self, msg): Decides the result of the next call.
- def decide(sel... | Implement the Python class `MockActionServer` described below.
Class description:
MockActionServer base class
Method signatures and docstrings:
- def __init__(self, name, topic, action_type): Creating a custom mock action server.
- def receive_commands(self, msg): Decides the result of the next call.
- def decide(sel... | eecaf082b47e52582c5f009eefbf46dd692aba4f | <|skeleton|>
class MockActionServer:
"""MockActionServer base class"""
def __init__(self, name, topic, action_type):
"""Creating a custom mock action server."""
<|body_0|>
def receive_commands(self, msg):
"""Decides the result of the next call."""
<|body_1|>
def decide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MockActionServer:
"""MockActionServer base class"""
def __init__(self, name, topic, action_type):
"""Creating a custom mock action server."""
self._topic = topic
self._name = name
self._action_type = action_type
self.timeout = 1
self.action_result = None
... | the_stack_v2_python_sparse | pandora_control/pandora_end_effector_controller/src/pandora_end_effector_controller/mocks/action_servers.py | skohlbr/pandora_ros_pkgs | train | 0 |
e0aa1e8a0e9099758f637ffda994538449e8f115 | [
"from itertools import islice\nbatch_size = 250\nsaved = 0\nobjs = (self.model(market=market, date=parse_datetime(i[0]), open=i[1], hight=i[2], low=i[3], close=i[4], volume=i[5]) for i in ohlcv)\nwhile True:\n batch = list(islice(objs, batch_size))\n if not batch:\n return saved\n self.bulk_create(b... | <|body_start_0|>
from itertools import islice
batch_size = 250
saved = 0
objs = (self.model(market=market, date=parse_datetime(i[0]), open=i[1], hight=i[2], low=i[3], close=i[4], volume=i[5]) for i in ohlcv)
while True:
batch = list(islice(objs, batch_size))
... | MarketOHLCVManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarketOHLCVManager:
def bulk_ohlcv(self, market: object, ohlcv: list) -> int:
"""To save a lot of data. It does not check whether the date for the market already exists. :param market: MarketOHLCV :param ohlcv: list by example: - MarketOHLCV('kraken', 'BTC/USD') - [[1550479200000, 3698.0... | stack_v2_sparse_classes_36k_train_002184 | 2,930 | no_license | [
{
"docstring": "To save a lot of data. It does not check whether the date for the market already exists. :param market: MarketOHLCV :param ohlcv: list by example: - MarketOHLCV('kraken', 'BTC/USD') - [[1550479200000, 3698.0, 3700.6, 3697.9, 3700.6, 5.0886]]",
"name": "bulk_ohlcv",
"signature": "def bulk... | 2 | stack_v2_sparse_classes_30k_train_011977 | Implement the Python class `MarketOHLCVManager` described below.
Class description:
Implement the MarketOHLCVManager class.
Method signatures and docstrings:
- def bulk_ohlcv(self, market: object, ohlcv: list) -> int: To save a lot of data. It does not check whether the date for the market already exists. :param mark... | Implement the Python class `MarketOHLCVManager` described below.
Class description:
Implement the MarketOHLCVManager class.
Method signatures and docstrings:
- def bulk_ohlcv(self, market: object, ohlcv: list) -> int: To save a lot of data. It does not check whether the date for the market already exists. :param mark... | 826d0858648239d49f05ce0b2a3122e2765b8460 | <|skeleton|>
class MarketOHLCVManager:
def bulk_ohlcv(self, market: object, ohlcv: list) -> int:
"""To save a lot of data. It does not check whether the date for the market already exists. :param market: MarketOHLCV :param ohlcv: list by example: - MarketOHLCV('kraken', 'BTC/USD') - [[1550479200000, 3698.0... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarketOHLCVManager:
def bulk_ohlcv(self, market: object, ohlcv: list) -> int:
"""To save a lot of data. It does not check whether the date for the market already exists. :param market: MarketOHLCV :param ohlcv: list by example: - MarketOHLCV('kraken', 'BTC/USD') - [[1550479200000, 3698.0, 3700.6, 3697... | the_stack_v2_python_sparse | src/exchanges/managers.py | henrypalacios/crypstation | train | 0 | |
9c20bad68cc6c3e8b2a65bfe61b3ce37f8e03dc2 | [
"if analysis_name not in SubjectAnalyses.analysis_dict:\n print('Please enter a valid analysis name: \\n{}'.format('\\n'.join(list(SubjectAnalyses.analysis_dict.keys()))))\n return\nself.analysis_name = analysis_name\nself.open_pool = open_pool\nself.n_jobs = n_jobs\nself.G = G_per_job\nself.subject_montage =... | <|body_start_0|>
if analysis_name not in SubjectAnalyses.analysis_dict:
print('Please enter a valid analysis name: \n{}'.format('\n'.join(list(SubjectAnalyses.analysis_dict.keys()))))
return
self.analysis_name = analysis_name
self.open_pool = open_pool
self.n_jobs... | Class to run a specified analyses on all subjects. | Group | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Group:
"""Class to run a specified analyses on all subjects."""
def __init__(self, analysis_name='', log_dir=None, open_pool=False, n_jobs=20, G_per_job=12, subject_montage=None, task=None, **kwargs):
"""Parameters ---------- analysis_name: str The name of analysis to run. It should ... | stack_v2_sparse_classes_36k_train_002185 | 12,431 | no_license | [
{
"docstring": "Parameters ---------- analysis_name: str The name of analysis to run. It should be the name of a SubjectLevel analysis class. log_dir: str Where to write the log file. If not given, will save to default location. See default_log_dir() open_pool: bool Whether to open a parallel pool for within su... | 3 | stack_v2_sparse_classes_30k_train_018160 | Implement the Python class `Group` described below.
Class description:
Class to run a specified analyses on all subjects.
Method signatures and docstrings:
- def __init__(self, analysis_name='', log_dir=None, open_pool=False, n_jobs=20, G_per_job=12, subject_montage=None, task=None, **kwargs): Parameters ---------- a... | Implement the Python class `Group` described below.
Class description:
Class to run a specified analyses on all subjects.
Method signatures and docstrings:
- def __init__(self, analysis_name='', log_dir=None, open_pool=False, n_jobs=20, G_per_job=12, subject_montage=None, task=None, **kwargs): Parameters ---------- a... | a2b7cd2b9c8ff311fd2d60916acd1959e3b07306 | <|skeleton|>
class Group:
"""Class to run a specified analyses on all subjects."""
def __init__(self, analysis_name='', log_dir=None, open_pool=False, n_jobs=20, G_per_job=12, subject_montage=None, task=None, **kwargs):
"""Parameters ---------- analysis_name: str The name of analysis to run. It should ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Group:
"""Class to run a specified analyses on all subjects."""
def __init__(self, analysis_name='', log_dir=None, open_pool=False, n_jobs=20, G_per_job=12, subject_montage=None, task=None, **kwargs):
"""Parameters ---------- analysis_name: str The name of analysis to run. It should be the name o... | the_stack_v2_python_sparse | miller_ecog_tools/GroupLevel/group.py | jayfmil/miller_ecog_tools | train | 4 |
1fc17d7a570ee3a4b6a1914f30ce03cac5ad8262 | [
"self.A = A\nself.D = D\nself.sigma = sigma\nif self.sigma is None:\n self.sigma = [1.0] * len(A)\nself.rules = None\nself.average_process_time = None",
"self.sigma = entropy_weight(X)\ncpl_X = []\ncpl_y = []\nincpl_X = []\nincpl_y = []\nfor i in range(len(X)):\n flag = False\n for c in X[i]:\n if... | <|body_start_0|>
self.A = A
self.D = D
self.sigma = sigma
if self.sigma is None:
self.sigma = [1.0] * len(A)
self.rules = None
self.average_process_time = None
<|end_body_0|>
<|body_start_1|>
self.sigma = entropy_weight(X)
cpl_X = []
c... | EDBRBBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EDBRBBase:
def __init__(self, A, D, sigma=None):
"""Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重"""
<|body_0|>
def fit(self, X, y, is_class):
"""Build a decision tree regressor from the training set (X, y). Parameters -------... | stack_v2_sparse_classes_36k_train_002186 | 6,697 | no_license | [
{
"docstring": "Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重",
"name": "__init__",
"signature": "def __init__(self, A, D, sigma=None)"
},
{
"docstring": "Build a decision tree regressor from the training set (X, y). Parameters ---------- X : array-like 输... | 3 | stack_v2_sparse_classes_30k_val_000816 | Implement the Python class `EDBRBBase` described below.
Class description:
Implement the EDBRBBase class.
Method signatures and docstrings:
- def __init__(self, A, D, sigma=None): Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重
- def fit(self, X, y, is_class): Build a decision t... | Implement the Python class `EDBRBBase` described below.
Class description:
Implement the EDBRBBase class.
Method signatures and docstrings:
- def __init__(self, A, D, sigma=None): Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重
- def fit(self, X, y, is_class): Build a decision t... | 4c86d0e832aa6d734ef3df88a5affe9923cd2182 | <|skeleton|>
class EDBRBBase:
def __init__(self, A, D, sigma=None):
"""Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重"""
<|body_0|>
def fit(self, X, y, is_class):
"""Build a decision tree regressor from the training set (X, y). Parameters -------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EDBRBBase:
def __init__(self, A, D, sigma=None):
"""Parameters A: list(float),二维 属性参考值 D: list(float),一维 结果评价等级 sigma: list(float),一维 属性权重"""
self.A = A
self.D = D
self.sigma = sigma
if self.sigma is None:
self.sigma = [1.0] * len(A)
self.rules = Non... | the_stack_v2_python_sparse | code/DBRB_missingData/EDBRB3/ebrb.py | Fuzhou-U-ACM-Research-Group/YongyuLiu | train | 0 | |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__()\nself.ratio = ratio\nself.kernel_size = kernel_size\nif pooling_class == 'icosahedron':\n self.pooling_class = Icosahedron()\n self.laps = get_icosahedron_laplacians(N, depth, laplacian_type)\nelif pooling_class == 'healpix':\n self.pooling_class = Healpix()\n self.laps = get_healpix... | <|body_start_0|>
super().__init__()
self.ratio = ratio
self.kernel_size = kernel_size
if pooling_class == 'icosahedron':
self.pooling_class = Icosahedron()
self.laps = get_icosahedron_laplacians(N, depth, laplacian_type)
elif pooling_class == 'healpix':
... | Spherical GCNN Autoencoder. | SphericalUNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalUNet:
"""Spherical GCNN Autoencoder."""
def __init__(self, pooling_class, N, depth, laplacian_type, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The dept... | stack_v2_sparse_classes_36k_train_002187 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The depth of the UNet, which is bounded by the N and the type of pooling kernel_size (int): chebychev polynomial degree ratio (float): Parameter for equian... | 2 | stack_v2_sparse_classes_30k_train_003491 | Implement the Python class `SphericalUNet` described below.
Class description:
Spherical GCNN Autoencoder.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, kernel_size, ratio=1): Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): ... | Implement the Python class `SphericalUNet` described below.
Class description:
Spherical GCNN Autoencoder.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, kernel_size, ratio=1): Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): ... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalUNet:
"""Spherical GCNN Autoencoder."""
def __init__(self, pooling_class, N, depth, laplacian_type, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The dept... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalUNet:
"""Spherical GCNN Autoencoder."""
def __init__(self, pooling_class, N, depth, laplacian_type, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The depth of the UNet... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
85e097bf77eb7059717f5b98b090a6f8797cb239 | [
"if user is None or user.is_active is False:\n raise ValueError('{\"detail\":\"' + str(_('In order to perform this operation, your account must be active')) + '\"}')\nif user.is_staff:\n images = accounts_models.PublicFeed.objects.all()\nelse:\n images = accounts_models.PublicFeed.objects.filter(user_id=us... | <|body_start_0|>
if user is None or user.is_active is False:
raise ValueError('{"detail":"' + str(_('In order to perform this operation, your account must be active')) + '"}')
if user.is_staff:
images = accounts_models.PublicFeed.objects.all()
else:
images = a... | this class contain a crud for the image upload to public feed 420 | UploadImagePublicProfileService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UploadImagePublicProfileService:
"""this class contain a crud for the image upload to public feed 420"""
def list(self, user: accounts_models.User) -> accounts_models.PublicFeed:
"""Get all images upload to public feed 420. if user is admin o staff the can see all images upload for a... | stack_v2_sparse_classes_36k_train_002188 | 42,606 | no_license | [
{
"docstring": "Get all images upload to public feed 420. if user is admin o staff the can see all images upload for any user in weedmtach. :param user: user weedmatch :type user: Model User :return: Model PublicFeed :raise: ValueError",
"name": "list",
"signature": "def list(self, user: accounts_models... | 5 | stack_v2_sparse_classes_30k_train_003771 | Implement the Python class `UploadImagePublicProfileService` described below.
Class description:
this class contain a crud for the image upload to public feed 420
Method signatures and docstrings:
- def list(self, user: accounts_models.User) -> accounts_models.PublicFeed: Get all images upload to public feed 420. if ... | Implement the Python class `UploadImagePublicProfileService` described below.
Class description:
this class contain a crud for the image upload to public feed 420
Method signatures and docstrings:
- def list(self, user: accounts_models.User) -> accounts_models.PublicFeed: Get all images upload to public feed 420. if ... | 497b8724d6e02582f28bc9c5a19f93ec21db84d8 | <|skeleton|>
class UploadImagePublicProfileService:
"""this class contain a crud for the image upload to public feed 420"""
def list(self, user: accounts_models.User) -> accounts_models.PublicFeed:
"""Get all images upload to public feed 420. if user is admin o staff the can see all images upload for a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UploadImagePublicProfileService:
"""this class contain a crud for the image upload to public feed 420"""
def list(self, user: accounts_models.User) -> accounts_models.PublicFeed:
"""Get all images upload to public feed 420. if user is admin o staff the can see all images upload for any user in we... | the_stack_v2_python_sparse | accounts/services.py | carlos-o/weedmatchheroku | train | 0 |
ac0161de90c9246f28e6c132b8e1475d3af8c24f | [
"table = getattr(self, model + '_table', None)\nself.default_r_v = None\nif table is None:\n raise AttributeError('%s model not available' % model)\nself.table = table()\nself.range = (min(self.table[0]), max(self.table[0]))\nself.arange = (self.range[0] * 10000.0, self.range[1] * 10000.0)\nself.sigma = sigma\ns... | <|body_start_0|>
table = getattr(self, model + '_table', None)
self.default_r_v = None
if table is None:
raise AttributeError('%s model not available' % model)
self.table = table()
self.range = (min(self.table[0]), max(self.table[0]))
self.arange = (self.range... | Extinction model for de-reddening spectra. | ExtinctionModel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `... | stack_v2_sparse_classes_36k_train_002189 | 3,929 | permissive | [
{
"docstring": "Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `nishiyama2009_table`. cval : float, optional Value to fill for missing data. sigma : float, optional Spline fit tension. extrapolate : bool, optional If set, missin... | 4 | stack_v2_sparse_classes_30k_train_009198 | Implement the Python class `ExtinctionModel` described below.
Class description:
Extinction model for de-reddening spectra.
Method signatures and docstrings:
- def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False): Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyam... | Implement the Python class `ExtinctionModel` described below.
Class description:
Extinction model for de-reddening spectra.
Method signatures and docstrings:
- def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False): Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyam... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtinctionModel:
"""Extinction model for de-reddening spectra."""
def __init__(self, model='rieke1989', cval=np.nan, sigma=10.0, extrapolate=False):
"""Set extinction model. Parameters ---------- model : {'rieke1989', 'nishiyama2009'} Model to use. Options are `rieke1989_table` and `nishiyama2009... | the_stack_v2_python_sparse | sofia_redux/spectroscopy/extinction_model.py | SOFIA-USRA/sofia_redux | train | 12 |
e599954a3666e240df306c864b0f223fdfa958fc | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('biken_riken', 'biken_riken')\nurl = 'http://datamechanics.io/data/bm181354_rikenm/htaindex_data_places_25.csv'\nBoston_df = pd.read_csv(url)\narr_transportation = Boston_df['t_cost_ami']\narr_housing = B... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('biken_riken', 'biken_riken')
url = 'http://datamechanics.io/data/bm181354_rikenm/htaindex_data_places_25.csv'
Boston_df = pd.read_csv(url)
... | index | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class index:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happeni... | stack_v2_sparse_classes_36k_train_002190 | 4,795 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_011044 | Implement the Python class `index` described below.
Class description:
Implement the index class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Cr... | Implement the Python class `index` described below.
Class description:
Implement the index class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): Cr... | b5ccaad97f6e35f9580e645ca764f36eb3406f43 | <|skeleton|>
class index:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happeni... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class index:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('biken_riken', 'biken_riken')
url = 'h... | the_stack_v2_python_sparse | biken_riken/index.py | dwang1995/course-2018-spr-proj | train | 1 | |
1c09e2ced8ed33aaf69f92e353bcdee1631818af | [
"assert packs_to_autobump, f'packs_to_autobump in the pr: {pr.number}, cant be empty.'\nself.pr = pr\nself.branch = pr.head.ref\nself.git_repo = git_repo\nself.packs_to_autobump = packs_to_autobump\nself.github_run_id = run_id",
"body = PR_COMMENT_TITLE.format(self.github_run_id)\nwith Checkout(self.git_repo, sel... | <|body_start_0|>
assert packs_to_autobump, f'packs_to_autobump in the pr: {pr.number}, cant be empty.'
self.pr = pr
self.branch = pr.head.ref
self.git_repo = git_repo
self.packs_to_autobump = packs_to_autobump
self.github_run_id = run_id
<|end_body_0|>
<|body_start_1|>
... | BranchAutoBumper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BranchAutoBumper:
def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str):
"""Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. ru... | stack_v2_sparse_classes_36k_train_002191 | 11,815 | permissive | [
{
"docstring": "Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub action run id.",
"name": "__init__",
"signature": "def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_aut... | 2 | stack_v2_sparse_classes_30k_train_001326 | Implement the Python class `BranchAutoBumper` described below.
Class description:
Implement the BranchAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str): Args: pr: Pull Request related to the branch. git_repo:... | Implement the Python class `BranchAutoBumper` described below.
Class description:
Implement the BranchAutoBumper class.
Method signatures and docstrings:
- def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str): Args: pr: Pull Request related to the branch. git_repo:... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class BranchAutoBumper:
def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str):
"""Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BranchAutoBumper:
def __init__(self, pr: PullRequest, git_repo: Repo, packs_to_autobump: List[PackAutoBumper], run_id: str):
"""Args: pr: Pull Request related to the branch. git_repo: Git API object packs_to_autobump: Pack that was changed in this PR and need to autobump its versions. run_id: GitHub a... | the_stack_v2_python_sparse | Utils/github_workflow_scripts/autobump_release_notes/autobump_rn.py | demisto/content | train | 1,023 | |
338d8b8b6d1547208b069f31b3f73533834694b3 | [
"if not root:\n return []\nmapping = collections.defaultdict(int)\ng_max = 0\nunvisited = [root]\nwhile unvisited:\n p = unvisited.pop()\n if not p:\n continue\n mapping[p.val] += 1\n if g_max < mapping[p.val]:\n g_max = mapping[p.val]\n if p.left:\n unvisited.append(p.left)\n... | <|body_start_0|>
if not root:
return []
mapping = collections.defaultdict(int)
g_max = 0
unvisited = [root]
while unvisited:
p = unvisited.pop()
if not p:
continue
mapping[p.val] += 1
if g_max < mapping[p... | Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: Li... | stack_v2_sparse_classes_36k_train_002192 | 2,494 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findMode",
"signature": "def findMode(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "findMode",
"signature": "def findMode(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010875 | Implement the Python class `Solution` described below.
Class description:
Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree.
Method signatures and docstrings:
- ... | Implement the Python class `Solution` described below.
Class description:
Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree.
Method signatures and docstrings:
- ... | 843db7190a95ebe310f5e867c02d28d43ca99248 | <|skeleton|>
class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Runtime: 109 ms, faster than 14.15% of Python online submissions for Find Mode in Binary Search Tree. Memory Usage: 21.3 MB, less than 49.52% of Python online submissions for Find Mode in Binary Search Tree."""
def findMode(self, root):
""":type root: TreeNode :rtype: List[int]"""
... | the_stack_v2_python_sparse | datastructure/tree/find_mode_in_binary_search_tree.py | YuanZheCSYZ/algorithm | train | 0 |
73cfca98fc58ed7c7557c9d1758f8a631e328151 | [
"if str1 in str2:\n flag = True\nelse:\n flag = False\nreturn flag",
"if isinstance(dict1, str):\n dict1 = json.loads(dict1)\nif isinstance(dict2, str):\n dict2 = json.loads(dict2)\nreturn operator.eq(dict1, dict2)"
] | <|body_start_0|>
if str1 in str2:
flag = True
else:
flag = False
return flag
<|end_body_0|>
<|body_start_1|>
if isinstance(dict1, str):
dict1 = json.loads(dict1)
if isinstance(dict2, str):
dict2 = json.loads(dict2)
return o... | CommonUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommonUtil:
def is_contain(self, str1, str2):
"""判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False"""
<|body_0|>
def is_equal_to(self, dict1, dict2):
"""判断dict1与dict2是否相等 :param dict1: 预期结果 :param dict2: 实际结果 :return: 相等返回true,不等返... | stack_v2_sparse_classes_36k_train_002193 | 892 | no_license | [
{
"docstring": "判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False",
"name": "is_contain",
"signature": "def is_contain(self, str1, str2)"
},
{
"docstring": "判断dict1与dict2是否相等 :param dict1: 预期结果 :param dict2: 实际结果 :return: 相等返回true,不等返回false",
"name": "is_... | 2 | stack_v2_sparse_classes_30k_test_000663 | Implement the Python class `CommonUtil` described below.
Class description:
Implement the CommonUtil class.
Method signatures and docstrings:
- def is_contain(self, str1, str2): 判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False
- def is_equal_to(self, dict1, dict2): 判断dict1与dict2是... | Implement the Python class `CommonUtil` described below.
Class description:
Implement the CommonUtil class.
Method signatures and docstrings:
- def is_contain(self, str1, str2): 判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False
- def is_equal_to(self, dict1, dict2): 判断dict1与dict2是... | 735987d448fc41df29926ba26aea4548ef0e1792 | <|skeleton|>
class CommonUtil:
def is_contain(self, str1, str2):
"""判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False"""
<|body_0|>
def is_equal_to(self, dict1, dict2):
"""判断dict1与dict2是否相等 :param dict1: 预期结果 :param dict2: 实际结果 :return: 相等返回true,不等返... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommonUtil:
def is_contain(self, str1, str2):
"""判断str1是否在str2中 :param str1: 预期结果 :param str2:实际结果 :return:如果str1在str2中返回True,反之返回False"""
if str1 in str2:
flag = True
else:
flag = False
return flag
def is_equal_to(self, dict1, dict2):
"""判断... | the_stack_v2_python_sparse | util/common_util.py | Dhs94/API-test2 | train | 0 | |
b6aeef1893b97dc077623d2793b057460fa64d79 | [
"data = pd.read_table(cut_file_name, names=['category', 'theme', 'URL', 'content'], encoding='utf-8')\ncontent = data['content'].values.tolist()\ncontent_S = []\nfor line in content:\n semp = jieba.lcut(line)\n if len(semp) > 1 and semp != '\\r\\n':\n content_S.append(semp)\ndf_content = pd.DataFrame({... | <|body_start_0|>
data = pd.read_table(cut_file_name, names=['category', 'theme', 'URL', 'content'], encoding='utf-8')
content = data['content'].values.tolist()
content_S = []
for line in content:
semp = jieba.lcut(line)
if len(semp) > 1 and semp != '\r\n':
... | 适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。 | TF_IDF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TF_IDF:
"""适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。"""
def Data_Cleaning(self, cut_file_name, stop_file_name):
"""对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:"""
<|body_0|>
def drop_stopwords(self, contents, stopwords):
"""基于停用... | stack_v2_sparse_classes_36k_train_002194 | 5,404 | no_license | [
{
"docstring": "对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:",
"name": "Data_Cleaning",
"signature": "def Data_Cleaning(self, cut_file_name, stop_file_name)"
},
{
"docstring": "基于停用词库清洗原先已分词好的df_content库,建立新的词库 :param contents: 待处理分词后的词 :param stopwords: 停用词 :return:... | 3 | stack_v2_sparse_classes_30k_train_014234 | Implement the Python class `TF_IDF` described below.
Class description:
适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。
Method signatures and docstrings:
- def Data_Cleaning(self, cut_file_name, stop_file_name): 对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:
- def drop_stopwords(self, conte... | Implement the Python class `TF_IDF` described below.
Class description:
适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。
Method signatures and docstrings:
- def Data_Cleaning(self, cut_file_name, stop_file_name): 对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:
- def drop_stopwords(self, conte... | e70f8e5a33b5599d36ffad8c11f36dcd5e0be1c0 | <|skeleton|>
class TF_IDF:
"""适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。"""
def Data_Cleaning(self, cut_file_name, stop_file_name):
"""对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:"""
<|body_0|>
def drop_stopwords(self, contents, stopwords):
"""基于停用... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TF_IDF:
"""适用业务场景:可以根据一段文字内容的描述,判断出属于什么类型的新闻;这是有监督学习的模型算法。"""
def Data_Cleaning(self, cut_file_name, stop_file_name):
"""对文件进行分词处理 :param file_name: 分词文件名称 :param stopfile_name: 停用词文件名称 :return:"""
data = pd.read_table(cut_file_name, names=['category', 'theme', 'URL', 'content'], encoding... | the_stack_v2_python_sparse | Data_Mining/Text_Analysis/Analysis.py | 799142139zhufei/Data_Structure | train | 10 |
e4ceabb3c20504f422f05403c896f12c18adb84f | [
"self.config = json.load(open('faucet_config.json', 'r'))\nself.wallet = Wallet()\nself.wallet.generate_address_randomKey()\nit = iter(self.wallet.addresses)\nself.faucet_address = next(it)\nself.sent_transactions = {}",
"from_address = self.faucet_address\nif amount is None:\n amount = self.config['coins_to_s... | <|body_start_0|>
self.config = json.load(open('faucet_config.json', 'r'))
self.wallet = Wallet()
self.wallet.generate_address_randomKey()
it = iter(self.wallet.addresses)
self.faucet_address = next(it)
self.sent_transactions = {}
<|end_body_0|>
<|body_start_1|>
f... | Faucet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Faucet:
def __init__(self):
"""Constructor"""
<|body_0|>
def send_coins(self, to_address, amount=None):
"""Sends configurable amount of coins to the provided address :param to_address: :return:"""
<|body_1|>
def generate_transaction(self, from_address, t... | stack_v2_sparse_classes_36k_train_002195 | 3,085 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Sends configurable amount of coins to the provided address :param to_address: :return:",
"name": "send_coins",
"signature": "def send_coins(self, to_address, amount=None)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_016586 | Implement the Python class `Faucet` described below.
Class description:
Implement the Faucet class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def send_coins(self, to_address, amount=None): Sends configurable amount of coins to the provided address :param to_address: :return:
- def generate... | Implement the Python class `Faucet` described below.
Class description:
Implement the Faucet class.
Method signatures and docstrings:
- def __init__(self): Constructor
- def send_coins(self, to_address, amount=None): Sends configurable amount of coins to the provided address :param to_address: :return:
- def generate... | acaee6b4ff3a60d1857119b02e74a1d5dc1d43f4 | <|skeleton|>
class Faucet:
def __init__(self):
"""Constructor"""
<|body_0|>
def send_coins(self, to_address, amount=None):
"""Sends configurable amount of coins to the provided address :param to_address: :return:"""
<|body_1|>
def generate_transaction(self, from_address, t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Faucet:
def __init__(self):
"""Constructor"""
self.config = json.load(open('faucet_config.json', 'r'))
self.wallet = Wallet()
self.wallet.generate_address_randomKey()
it = iter(self.wallet.addresses)
self.faucet_address = next(it)
self.sent_transactions ... | the_stack_v2_python_sparse | Faucet/faucet.py | tsonev85/BeerChainNetwork | train | 0 | |
b1c77a78e55f5e7a9ab1154871b970af629d52bb | [
"self.root_public_folder_vec = root_public_folder_vec\nself.target_folder_path = target_folder_path\nself.target_root_public_folder = target_root_public_folder",
"if dictionary is None:\n return None\nroot_public_folder_vec = None\nif dictionary.get('rootPublicFolderVec') != None:\n root_public_folder_vec =... | <|body_start_0|>
self.root_public_folder_vec = root_public_folder_vec
self.target_folder_path = target_folder_path
self.target_root_public_folder = target_root_public_folder
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
root_public_folder_vec = N... | Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide the list of Root Public Folders to be restored. Provision is there for restoring full and partial P... | RestoreO365PublicFoldersParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365PublicFoldersParams:
"""Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide the list of Root Public Folders to be res... | stack_v2_sparse_classes_36k_train_002196 | 3,416 | permissive | [
{
"docstring": "Constructor for the RestoreO365PublicFoldersParams class",
"name": "__init__",
"signature": "def __init__(self, root_public_folder_vec=None, target_folder_path=None, target_root_public_folder=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dict... | 2 | stack_v2_sparse_classes_30k_train_002028 | Implement the Python class `RestoreO365PublicFoldersParams` described below.
Class description:
Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide th... | Implement the Python class `RestoreO365PublicFoldersParams` described below.
Class description:
Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide th... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365PublicFoldersParams:
"""Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide the list of Root Public Folders to be res... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreO365PublicFoldersParams:
"""Implementation of the 'RestoreO365PublicFoldersParams' model. TODO: type description here. Attributes: root_public_folder_vec (list of RestoreO365PublicFoldersParams_RootPublicFolder): In a RestoreJob , user will provide the list of Root Public Folders to be restored. Provis... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_public_folders_params.py | cohesity/management-sdk-python | train | 24 |
94876b1dde609ad32965fee9597bd933fb084861 | [
"resList = []\nif not root:\n return ''\nnodeQueue = deque()\nnodeQueue.append(root)\nwhile len(nodeQueue) > 0:\n node = nodeQueue.popleft()\n if node == None:\n resList.append('#')\n else:\n resList.append(str(node.val))\n nodeQueue.append(node.left)\n nodeQueue.append(node.... | <|body_start_0|>
resList = []
if not root:
return ''
nodeQueue = deque()
nodeQueue.append(root)
while len(nodeQueue) > 0:
node = nodeQueue.popleft()
if node == None:
resList.append('#')
else:
resList.... | Codec1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_002197 | 4,578 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | Implement the Python class `Codec1` described below.
Class description:
Implement the Codec1 class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtyp... | e2fecd266bfced6208694b19a2d81182b13dacd6 | <|skeleton|>
class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec1:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
resList = []
if not root:
return ''
nodeQueue = deque()
nodeQueue.append(root)
while len(nodeQueue) > 0:
node = nodeQueue.popleft... | the_stack_v2_python_sparse | Codec.py | HuipengXu/leetcode | train | 0 | |
0b39e075641d1965b4fc9c321316219a96560465 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | XArmServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XArmServicer:
"""Missing associated documentation comment in .proto file."""
def move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_jnt_values(self, request, context):
"""Missing associated ... | stack_v2_sparse_classes_36k_train_002198 | 6,650 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "move_jspace_path",
"signature": "def move_jspace_path(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "get_jnt_values",
"signature": "def get... | 4 | stack_v2_sparse_classes_30k_train_019497 | Implement the Python class `XArmServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def move_jspace_path(self, request, context): Missing associated documentation comment in .proto file.
- def get_jnt_values(self, request, context)... | Implement the Python class `XArmServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def move_jspace_path(self, request, context): Missing associated documentation comment in .proto file.
- def get_jnt_values(self, request, context)... | 405f15be1a3f7740f3eb7d234d96998f6d057a54 | <|skeleton|>
class XArmServicer:
"""Missing associated documentation comment in .proto file."""
def move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def get_jnt_values(self, request, context):
"""Missing associated ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XArmServicer:
"""Missing associated documentation comment in .proto file."""
def move_jspace_path(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | the_stack_v2_python_sparse | robot_con/xarm_shuidi/xarm/xarm_pb2_grpc.py | Shogo-Hayakawa/wrs | train | 0 |
ef90d635387747e05cb8c780b05a6a4ed0deb1ec | [
"if username.data != current_user.username:\n user = User.query.filter_by(username=username.data).first()\n if user:\n raise ValidationError('That username is taken. Please choose another.')",
"if email.data != current_user.email:\n user = User.query.filter_by(email=email.data).first()\n if use... | <|body_start_0|>
if username.data != current_user.username:
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError('That username is taken. Please choose another.')
<|end_body_0|>
<|body_start_1|>
if email.data != current_user.... | A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit. | UpdateAccountForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateAccountForm:
"""A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit."""
def validate_username(self, u... | stack_v2_sparse_classes_36k_train_002199 | 6,282 | no_license | [
{
"docstring": "Checks to see that username does not already exist. Args: username: User's updated username. Returns: None Raises: ValidationError: Username has already been taken.",
"name": "validate_username",
"signature": "def validate_username(self, username)"
},
{
"docstring": "Checks to se... | 2 | stack_v2_sparse_classes_30k_train_015613 | Implement the Python class `UpdateAccountForm` described below.
Class description:
A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit... | Implement the Python class `UpdateAccountForm` described below.
Class description:
A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit... | a2ecd6901021e4e0616f03110650f18f0329c92c | <|skeleton|>
class UpdateAccountForm:
"""A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit."""
def validate_username(self, u... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateAccountForm:
"""A form for updating an existing user's account information. Attributes: username: An input element of type text for the user's username. email: An input element of type email for the user's email. submit: An input element of type submit."""
def validate_username(self, username):
... | the_stack_v2_python_sparse | usctimeline/users/forms.py | WesternUSC/USC_Timeline | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.