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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9e2f94004a594cd8467a0e67abc893f9831b18fe | [
"self.pData = None\nself.pIndices = None\nself.vao = None\nself.vbo = None",
"if self.vbo:\n gl.glDeleteBuffers(2, self.vbo)\nif self.vao:\n gl.glDeleteVertexArrays(1, self.vao)\n self.vao = None",
"if self.vbo:\n gl.glDeleteBuffers(2, self.vbo)\nif self.vao:\n gl.glDeleteVertexArrays(1, self.vao... | <|body_start_0|>
self.pData = None
self.pIndices = None
self.vao = None
self.vbo = None
<|end_body_0|>
<|body_start_1|>
if self.vbo:
gl.glDeleteBuffers(2, self.vbo)
if self.vao:
gl.glDeleteVertexArrays(1, self.vao)
self.vao = None
<|en... | GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects. | GLObject | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GLObject:
"""GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects."""
def __init__(self):
"""Initialize GLObject"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_019100 | 3,391 | no_license | [
{
"docstring": "Initialize GLObject",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Delete Vertex Array Object and Vertex Buffer Objects",
"name": "release",
"signature": "def release(self)"
},
{
"docstring": "Initialize Vertex Array Object and Vertex B... | 4 | stack_v2_sparse_classes_30k_train_017769 | Implement the Python class `GLObject` described below.
Class description:
GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects.
Method signatures and docstrings:
- def __ini... | Implement the Python class `GLObject` described below.
Class description:
GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects.
Method signatures and docstrings:
- def __ini... | b24e3481942ef3d0bcc6b8923dfe19dc4f7101dc | <|skeleton|>
class GLObject:
"""GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects."""
def __init__(self):
"""Initialize GLObject"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GLObject:
"""GLObject represents OpenGL-drawable object. GLObject contains set of points and set of it's indices for all triangles of the object. Also GLObject have Vertex Array Object and Vertex Buffer Objects."""
def __init__(self):
"""Initialize GLObject"""
self.pData = None
se... | the_stack_v2_python_sparse | globject.py | GoldenMan123/pyopengl | train | 0 |
5d3944f0426afd56789c466d617d091a46042c04 | [
"first = ListNode(0)\nfirst.next = head\np = head\nlenth = 0\nwhile p:\n lenth += 1\n p = p.next\nj = 1\np_ = first\nwhile j < lenth - n + 1:\n p_ = p_.next\n j += 1\np_.next = p_.next.next\nreturn first.next",
"l = ListNode(0)\nl.next = head\nfirst = l.next\nsecond = l.next\nfor i in range(n):\n f... | <|body_start_0|>
first = ListNode(0)
first.next = head
p = head
lenth = 0
while p:
lenth += 1
p = p.next
j = 1
p_ = first
while j < lenth - n + 1:
p_ = p_.next
j += 1
p_.next = p_.next.next
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019101 | 1,599 | no_license | [
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self, head, n)"
},
{
"docstring": ":type head: ListNode :type n: int :rtype: ListNode",
"name": "removeNthFromEnd",
"signature": "def removeNthFromEnd(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
- def removeNthFromEnd(self, head, n): :type head: ListNode :type n: int :rtype: ListNode
... | 3d6b7dbe9002646d66e804664028ff8f0529bcf1 | <|skeleton|>
class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_0|>
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def removeNthFromEnd(self, head, n):
""":type head: ListNode :type n: int :rtype: ListNode"""
first = ListNode(0)
first.next = head
p = head
lenth = 0
while p:
lenth += 1
p = p.next
j = 1
p_ = first
while... | the_stack_v2_python_sparse | 1-50/#19.py | zqy628/LeetCode | train | 0 | |
251badc1e51f249f38f887043015104823861e5c | [
"self.mc = paramiko.SSHClient()\nself.mc.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nself.mc.connect(host, port=port, username=username, password=password)",
"if not cmd:\n return None\nretcod = None\ntry:\n stdin, stdout, stderr = self.mc.exec_command(cmd)\n retcod = stderr.read().decode('utf... | <|body_start_0|>
self.mc = paramiko.SSHClient()
self.mc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.mc.connect(host, port=port, username=username, password=password)
<|end_body_0|>
<|body_start_1|>
if not cmd:
return None
retcod = None
try:
... | 创建ssh 连接,执行远程命令 | sshCon | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class sshCon:
"""创建ssh 连接,执行远程命令"""
def __init__(self, host, port=22, username='root', password=None):
"""获取连接参数,建立ssh连接"""
<|body_0|>
def ExeCmd(self, cmd):
"""执行远程命令"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.mc = paramiko.SSHClient()
... | stack_v2_sparse_classes_36k_train_019102 | 1,039 | no_license | [
{
"docstring": "获取连接参数,建立ssh连接",
"name": "__init__",
"signature": "def __init__(self, host, port=22, username='root', password=None)"
},
{
"docstring": "执行远程命令",
"name": "ExeCmd",
"signature": "def ExeCmd(self, cmd)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019389 | Implement the Python class `sshCon` described below.
Class description:
创建ssh 连接,执行远程命令
Method signatures and docstrings:
- def __init__(self, host, port=22, username='root', password=None): 获取连接参数,建立ssh连接
- def ExeCmd(self, cmd): 执行远程命令 | Implement the Python class `sshCon` described below.
Class description:
创建ssh 连接,执行远程命令
Method signatures and docstrings:
- def __init__(self, host, port=22, username='root', password=None): 获取连接参数,建立ssh连接
- def ExeCmd(self, cmd): 执行远程命令
<|skeleton|>
class sshCon:
"""创建ssh 连接,执行远程命令"""
def __init__(self, ho... | c052269e1a3b72ebb06167173b14d6a1215ee10a | <|skeleton|>
class sshCon:
"""创建ssh 连接,执行远程命令"""
def __init__(self, host, port=22, username='root', password=None):
"""获取连接参数,建立ssh连接"""
<|body_0|>
def ExeCmd(self, cmd):
"""执行远程命令"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class sshCon:
"""创建ssh 连接,执行远程命令"""
def __init__(self, host, port=22, username='root', password=None):
"""获取连接参数,建立ssh连接"""
self.mc = paramiko.SSHClient()
self.mc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.mc.connect(host, port=port, username=username, password=p... | the_stack_v2_python_sparse | phxweb/upgrade/deploy_zypfront/remote_exe/sshCon.py | sadwebing/phx_web | train | 0 |
c9325e4d717cee9511153d605511f71036e48f39 | [
"self.ptm_short_names = ptm_short_names\nself.num_labels = num_labels\nself.max_length = max_length\nself.data_path = data_path\nself.task_name = task_name",
"for tmp_index, tmp_short_name in enumerate(self.ptm_short_names, 1):\n logger.warning(f'--> {tmp_index}: {tmp_short_name} model start evaluating.')\n ... | <|body_start_0|>
self.ptm_short_names = ptm_short_names
self.num_labels = num_labels
self.max_length = max_length
self.data_path = data_path
self.task_name = task_name
<|end_body_0|>
<|body_start_1|>
for tmp_index, tmp_short_name in enumerate(self.ptm_short_names, 1):
... | EvaluatePipeline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluatePipeline:
def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name):
"""多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 :param max_length: 待训练模型最大长度 :param data_path: 待训练数据路径 :param task_name: 待训练任务名称"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_019103 | 2,924 | permissive | [
{
"docstring": "多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 :param max_length: 待训练模型最大长度 :param data_path: 待训练数据路径 :param task_name: 待训练任务名称",
"name": "__init__",
"signature": "def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_009582 | Implement the Python class `EvaluatePipeline` described below.
Class description:
Implement the EvaluatePipeline class.
Method signatures and docstrings:
- def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name): 多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 ... | Implement the Python class `EvaluatePipeline` described below.
Class description:
Implement the EvaluatePipeline class.
Method signatures and docstrings:
- def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name): 多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 ... | eaf35cc8bfc02b0eeefc73a2ab478f4837e53535 | <|skeleton|>
class EvaluatePipeline:
def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name):
"""多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 :param max_length: 待训练模型最大长度 :param data_path: 待训练数据路径 :param task_name: 待训练任务名称"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluatePipeline:
def __init__(self, ptm_short_names, num_labels, max_length, data_path, task_name):
"""多模型训练pipeline :param ptm_short_names: 待训练模型简称列表 :param num_labels: 待训练模型目标分类数量 :param max_length: 待训练模型最大长度 :param data_path: 待训练数据路径 :param task_name: 待训练任务名称"""
self.ptm_short_names = ptm_... | the_stack_v2_python_sparse | xz_transformers/tasks/ptms_evaluate_pipeline.py | enningxie/transformers | train | 4 | |
976d12517229925a3fa1b6038c3167df1ee76d30 | [
"type(self).LAZY_LOADING_PLUGINS[plugin_name] = plugin_requirements\nfor m in related_modules:\n type(m).tag_with_plugin(plugin_name)",
"d = cls.LAZY_LOADING_PLUGINS.copy()\nall_plugins = []\nfor k in d:\n all_plugins.extend(d[k])\nd['all'] = all_plugins\nreturn d"
] | <|body_start_0|>
type(self).LAZY_LOADING_PLUGINS[plugin_name] = plugin_requirements
for m in related_modules:
type(m).tag_with_plugin(plugin_name)
<|end_body_0|>
<|body_start_1|>
d = cls.LAZY_LOADING_PLUGINS.copy()
all_plugins = []
for k in d:
all_plugins... | LazyLoadPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LazyLoadPlugin:
def __init__(self, plugin_name, plugin_requirements, related_modules):
""":param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] related_modules:"""
<|body_0|>
def get_extras_require(cls):
""":rtype: dict[Text,list... | stack_v2_sparse_classes_36k_train_019104 | 3,263 | permissive | [
{
"docstring": ":param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] related_modules:",
"name": "__init__",
"signature": "def __init__(self, plugin_name, plugin_requirements, related_modules)"
},
{
"docstring": ":rtype: dict[Text,list[Text]]",
"name": "... | 2 | null | Implement the Python class `LazyLoadPlugin` described below.
Class description:
Implement the LazyLoadPlugin class.
Method signatures and docstrings:
- def __init__(self, plugin_name, plugin_requirements, related_modules): :param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] rel... | Implement the Python class `LazyLoadPlugin` described below.
Class description:
Implement the LazyLoadPlugin class.
Method signatures and docstrings:
- def __init__(self, plugin_name, plugin_requirements, related_modules): :param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] rel... | 2eb9ce7aacaab6e49c1fc901c14c7b0d6b479523 | <|skeleton|>
class LazyLoadPlugin:
def __init__(self, plugin_name, plugin_requirements, related_modules):
""":param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] related_modules:"""
<|body_0|>
def get_extras_require(cls):
""":rtype: dict[Text,list... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LazyLoadPlugin:
def __init__(self, plugin_name, plugin_requirements, related_modules):
""":param Text plugin_name: :param list[Text] plugin_requirements: :param list[LazyLoadModule] related_modules:"""
type(self).LAZY_LOADING_PLUGINS[plugin_name] = plugin_requirements
for m in related_... | the_stack_v2_python_sparse | flytekit/tools/lazy_loader.py | jbrambleDC/flytekit | train | 1 | |
7fb25d5907b35b3dd6763e85b2a4c83e15b2e171 | [
"super().__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(vocab, embedding)\nself.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"initializer = tf.keras.initializers.Zeros()\nvalues = initializer(sh... | <|body_start_0|>
super().__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(vocab, embedding)
self.gru = tf.keras.layers.GRU(units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)
<|end_body_0|>
<|body_st... | Encode for machine translation | RNNEncoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Encode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector. units is an integer representing ... | stack_v2_sparse_classes_36k_train_019105 | 1,460 | no_license | [
{
"docstring": "vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector. units is an integer representing the number of hidden units in the RNN cell. batch is an integer representing the batch size",
"name": "__init__"... | 3 | stack_v2_sparse_classes_30k_train_015318 | Implement the Python class `RNNEncoder` described below.
Class description:
Encode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality o... | Implement the Python class `RNNEncoder` described below.
Class description:
Encode for machine translation
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality o... | b0c18df889d8bd0c24d4bdbbd69be06bc5c0a918 | <|skeleton|>
class RNNEncoder:
"""Encode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector. units is an integer representing ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RNNEncoder:
"""Encode for machine translation"""
def __init__(self, vocab, embedding, units, batch):
"""vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector. units is an integer representing the number of... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | Gaspela/holbertonschool-machine_learning | train | 0 |
8d8b7fbf533b6c6f41137c1a03cbf289b5f6481c | [
"if len(ransomNote) > len(magazine):\n return False\nm1 = [0] * 26\nm2 = [0] * 26\nfor c in ransomNote:\n m1[ord(c) - 97] += 1\nfor c in magazine:\n m2[ord(c) - 97] += 1\nprint(m1)\nprint(m2)\nfor i in range(26):\n if m1[i] != 0 and m1[i] > m2[i]:\n return False\nreturn True",
"if len(ransomNot... | <|body_start_0|>
if len(ransomNote) > len(magazine):
return False
m1 = [0] * 26
m2 = [0] * 26
for c in ransomNote:
m1[ord(c) - 97] += 1
for c in magazine:
m2[ord(c) - 97] += 1
print(m1)
print(m2)
for i in range(26):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canConstruct1(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_0|>
def canConstruct(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_019106 | 1,185 | no_license | [
{
"docstring": ":type ransomNote: str :type magazine: str :rtype: bool",
"name": "canConstruct1",
"signature": "def canConstruct1(self, ransomNote, magazine)"
},
{
"docstring": ":type ransomNote: str :type magazine: str :rtype: bool",
"name": "canConstruct",
"signature": "def canConstruc... | 2 | stack_v2_sparse_classes_30k_train_012193 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canConstruct1(self, ransomNote, magazine): :type ransomNote: str :type magazine: str :rtype: bool
- def canConstruct(self, ransomNote, magazine): :type ransomNote: str :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canConstruct1(self, ransomNote, magazine): :type ransomNote: str :type magazine: str :rtype: bool
- def canConstruct(self, ransomNote, magazine): :type ransomNote: str :type ... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def canConstruct1(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_0|>
def canConstruct(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canConstruct1(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
if len(ransomNote) > len(magazine):
return False
m1 = [0] * 26
m2 = [0] * 26
for c in ransomNote:
m1[ord(c) - 97] += 1
f... | the_stack_v2_python_sparse | python/leetcode_bak/383_Ransom_Note.py | bobcaoge/my-code | train | 0 | |
b713f59a987b94d3ccce32ab69e07745ad7bd57b | [
"self.playerResults = playerResults\nself.player = playerResults.player\nself.isYou = isYou",
"context = PlayerContext(game, None, player=self.player)\ncards = {}\ncardsByType = {str(cardType): list(cardsForType) for cardType, cardsForType in groupby(sorted(self.player.deck, key=lambda card: card.cardType), key=l... | <|body_start_0|>
self.playerResults = playerResults
self.player = playerResults.player
self.isYou = isYou
<|end_body_0|>
<|body_start_1|>
context = PlayerContext(game, None, player=self.player)
cards = {}
cardsByType = {str(cardType): list(cardsForType) for cardType, car... | A Wrapper for a Player's Game Results | PlayerResultsWrapper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlayerResultsWrapper:
"""A Wrapper for a Player's Game Results"""
def __init__(self, playerResults, isYou):
"""Initialize the Player Wrapper"""
<|body_0|>
def toJSON(self, game):
"""Return the Player as a JSON Dictionary"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_019107 | 1,704 | no_license | [
{
"docstring": "Initialize the Player Wrapper",
"name": "__init__",
"signature": "def __init__(self, playerResults, isYou)"
},
{
"docstring": "Return the Player as a JSON Dictionary",
"name": "toJSON",
"signature": "def toJSON(self, game)"
}
] | 2 | null | Implement the Python class `PlayerResultsWrapper` described below.
Class description:
A Wrapper for a Player's Game Results
Method signatures and docstrings:
- def __init__(self, playerResults, isYou): Initialize the Player Wrapper
- def toJSON(self, game): Return the Player as a JSON Dictionary | Implement the Python class `PlayerResultsWrapper` described below.
Class description:
A Wrapper for a Player's Game Results
Method signatures and docstrings:
- def __init__(self, playerResults, isYou): Initialize the Player Wrapper
- def toJSON(self, game): Return the Player as a JSON Dictionary
<|skeleton|>
class P... | 0b5a7573a3cf33430fe61e4ff8a8a7a0ae20b258 | <|skeleton|>
class PlayerResultsWrapper:
"""A Wrapper for a Player's Game Results"""
def __init__(self, playerResults, isYou):
"""Initialize the Player Wrapper"""
<|body_0|>
def toJSON(self, game):
"""Return the Player as a JSON Dictionary"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlayerResultsWrapper:
"""A Wrapper for a Player's Game Results"""
def __init__(self, playerResults, isYou):
"""Initialize the Player Wrapper"""
self.playerResults = playerResults
self.player = playerResults.player
self.isYou = isYou
def toJSON(self, game):
"""... | the_stack_v2_python_sparse | src/Server/Game/player_results_wrapper.py | dfwarden/DeckBuilding | train | 0 |
a0bfb0aec0a5a0db1b795389abf7866bdb28db3a | [
"self.enable_deepcopy = enable_deepcopy\nself.init_val = init_val\nself.root = TrieNode(self.init_val, self.enable_deepcopy)",
"i, n = (0, len(string))\nnode = self.root\nwhile i < n:\n if string[i] not in node.next:\n node.next[string[i]] = TrieNode(self.init_val, self.enable_deepcopy)\n if insert_o... | <|body_start_0|>
self.enable_deepcopy = enable_deepcopy
self.init_val = init_val
self.root = TrieNode(self.init_val, self.enable_deepcopy)
<|end_body_0|>
<|body_start_1|>
i, n = (0, len(string))
node = self.root
while i < n:
if string[i] not in node.next:
... | Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie) | Trie | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Trie:
"""Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie)"""
def __init__(self, init_val=None, enable_deepcopy=False):
"""Init a ... | stack_v2_sparse_classes_36k_train_019108 | 3,546 | no_license | [
{
"docstring": "Init a Trie using specific initial value. :param init_val: Initial value of each Trie node. :param enable_deepcopy: Whether using the deepcopy to initialize the value of Trie node. This option is useful to avoiding initialize all nodes with a same reference when using list/dict as initial value.... | 3 | stack_v2_sparse_classes_30k_train_019012 | Implement the Python class `Trie` described below.
Class description:
Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie)
Method signatures and docstrings:
- def __in... | Implement the Python class `Trie` described below.
Class description:
Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie)
Method signatures and docstrings:
- def __in... | 72d172ea25777980a49439042dbc39448fcad73d | <|skeleton|>
class Trie:
"""Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie)"""
def __init__(self, init_val=None, enable_deepcopy=False):
"""Init a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Trie:
"""Class of Trie, which is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. (See: https://en.wikipedia.org/wiki/Trie)"""
def __init__(self, init_val=None, enable_deepcopy=False):
"""Init a Trie using sp... | the_stack_v2_python_sparse | src/data_structure/trie.py | stupidchen/leetcode | train | 7 |
c27f66237bd7471a37a30351563b28a288450656 | [
"dp = [0 for a in range(amount + 1)]\ndp[0] = 1\nfor c in range(1, len(coins) + 1, 1):\n for a in range(1, amount + 1, 1):\n if a - coins[c - 1] >= 0:\n dp[a] += dp[a - coins[c - 1]]\nreturn dp[-1]",
"dp = [[0 for a in range(amount + 1)] for c in range(len(coins) + 1)]\ndp[0][0] = 1\nfor c in... | <|body_start_0|>
dp = [0 for a in range(amount + 1)]
dp[0] = 1
for c in range(1, len(coins) + 1, 1):
for a in range(1, amount + 1, 1):
if a - coins[c - 1] >= 0:
dp[a] += dp[a - coins[c - 1]]
return dp[-1]
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def change_1d(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_2d(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019109 | 2,373 | no_license | [
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change_1d",
"signature": "def change_1d(self, amount, coins)"
},
{
"docstring": ":type amount: int :type coins: List[int] :rtype: int",
"name": "change_2d",
"signature": "def change_2d(self, amount, coins)"
... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change_1d(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_2d(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def change_1d(self, amount, coins): :type amount: int :type coins: List[int] :rtype: int
- def change_2d(self, amount, coins): :type amount: int :type coins: List[int] :rtype: in... | 9ac54720f571a4bea09d0cceb0039381a78df9e8 | <|skeleton|>
class Solution:
def change_1d(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_0|>
def change_2d(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def change_1d(self, amount, coins):
""":type amount: int :type coins: List[int] :rtype: int"""
dp = [0 for a in range(amount + 1)]
dp[0] = 1
for c in range(1, len(coins) + 1, 1):
for a in range(1, amount + 1, 1):
if a - coins[c - 1] >= 0:
... | the_stack_v2_python_sparse | code/518_coin-change-2.py | linhdvu14/leetcode-solutions | train | 2 | |
2d632a488a8caae198836b10240e33ae41469f5f | [
"if not matrix or not matrix[0]:\n return []\noffset = 0\nodd = True\nver = len(matrix)\nhor = len(matrix[0])\nstep = max(ver, hor) * 2 - 1\nres = []\n\ndef check(x, y):\n if 0 <= x < ver and 0 <= y < hor:\n return True\n return False\nfor i in range(step):\n if odd:\n odd = False\n ... | <|body_start_0|>
if not matrix or not matrix[0]:
return []
offset = 0
odd = True
ver = len(matrix)
hor = len(matrix[0])
step = max(ver, hor) * 2 - 1
res = []
def check(x, y):
if 0 <= x < ver and 0 <= y < hor:
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrderFast(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findWords(self, words):
... | stack_v2_sparse_classes_36k_train_019110 | 4,234 | no_license | [
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrder",
"signature": "def findDiagonalOrder(self, matrix)"
},
{
"docstring": ":type matrix: List[List[int]] :rtype: List[int]",
"name": "findDiagonalOrderFast",
"signature": "def findDiagonalOrderFast(... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrderFast(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDiagonalOrder(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- def findDiagonalOrderFast(self, matrix): :type matrix: List[List[int]] :rtype: List[int]
- ... | 2711bc08f15266bec4ca135e8e3e629df46713eb | <|skeleton|>
class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_0|>
def findDiagonalOrderFast(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
<|body_1|>
def findWords(self, words):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDiagonalOrder(self, matrix):
""":type matrix: List[List[int]] :rtype: List[int]"""
if not matrix or not matrix[0]:
return []
offset = 0
odd = True
ver = len(matrix)
hor = len(matrix[0])
step = max(ver, hor) * 2 - 1
r... | the_stack_v2_python_sparse | 0.算法/20180824.py | unlimitediw/CheckCode | train | 0 | |
60c22c6051a4ff15d4c522fc4e069655920902e7 | [
"res = 0\nprime = [True] * n\nfor i in range(2, n):\n if prime[i]:\n res += 1\n j = 2 * i\n while j < n:\n prime[j] = False\n j += i\nreturn res",
"flag = [True] * n\nprime = []\nfor i in range(2, n):\n if flag[i]:\n prime.append(i)\n j = 0\n while pri... | <|body_start_0|>
res = 0
prime = [True] * n
for i in range(2, n):
if prime[i]:
res += 1
j = 2 * i
while j < n:
prime[j] = False
j += i
return res
<|end_body_0|>
<|body_start_1|>
f... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countPrimes1(self, n: int) -> int:
"""思路:埃氏筛法 @param n: @return:"""
<|body_0|>
def countPrimes2(self, n: int) -> int:
"""思路:线性筛法 @param n: @return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
prime = [True] * n
... | stack_v2_sparse_classes_36k_train_019111 | 1,501 | no_license | [
{
"docstring": "思路:埃氏筛法 @param n: @return:",
"name": "countPrimes1",
"signature": "def countPrimes1(self, n: int) -> int"
},
{
"docstring": "思路:线性筛法 @param n: @return:",
"name": "countPrimes2",
"signature": "def countPrimes2(self, n: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes1(self, n: int) -> int: 思路:埃氏筛法 @param n: @return:
- def countPrimes2(self, n: int) -> int: 思路:线性筛法 @param n: @return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countPrimes1(self, n: int) -> int: 思路:埃氏筛法 @param n: @return:
- def countPrimes2(self, n: int) -> int: 思路:线性筛法 @param n: @return:
<|skeleton|>
class Solution:
def count... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def countPrimes1(self, n: int) -> int:
"""思路:埃氏筛法 @param n: @return:"""
<|body_0|>
def countPrimes2(self, n: int) -> int:
"""思路:线性筛法 @param n: @return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countPrimes1(self, n: int) -> int:
"""思路:埃氏筛法 @param n: @return:"""
res = 0
prime = [True] * n
for i in range(2, n):
if prime[i]:
res += 1
j = 2 * i
while j < n:
prime[j] = False
... | the_stack_v2_python_sparse | LeetCode/数学/204. 计数质数.py | yiming1012/MyLeetCode | train | 2 | |
5f477eaf8233cc0cd2d72366b75ff88c2b2b54f7 | [
"if self.request.path.endswith('.fa'):\n otu_id = otu_id.rstrip('.fa')\n try:\n filename, fasta = await get_data_from_req(self.request).otus.get_fasta(otu_id)\n except ResourceNotFoundError:\n raise NotFound\n return web.Response(text=fasta, headers={'Content-Disposition': f'attachment; fi... | <|body_start_0|>
if self.request.path.endswith('.fa'):
otu_id = otu_id.rstrip('.fa')
try:
filename, fasta = await get_data_from_req(self.request).otus.get_fasta(otu_id)
except ResourceNotFoundError:
raise NotFound
return web.Respons... | OTUView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTUView:
async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]:
"""Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded by appending `.fa` to the path."""
<|body_0|>
async def patch(self, otu_id: str, /, ... | stack_v2_sparse_classes_36k_train_019112 | 16,946 | permissive | [
{
"docstring": "Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded by appending `.fa` to the path.",
"name": "get",
"signature": "async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]"
},
{
"docstring": "Update an OTU. Chec... | 3 | null | Implement the Python class `OTUView` described below.
Class description:
Implement the OTUView class.
Method signatures and docstrings:
- async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]: Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded b... | Implement the Python class `OTUView` described below.
Class description:
Implement the OTUView class.
Method signatures and docstrings:
- async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]: Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded b... | 1d17d2ba570cf5487e7514bec29250a5b368bb0a | <|skeleton|>
class OTUView:
async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]:
"""Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded by appending `.fa` to the path."""
<|body_0|>
async def patch(self, otu_id: str, /, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OTUView:
async def get(self, otu_id: str, /) -> Union[r200[OTU], r403, r404]:
"""Get an OTU. Fetches the details of an OTU. A FASTA file containing all sequences in the OTU can be downloaded by appending `.fa` to the path."""
if self.request.path.endswith('.fa'):
otu_id = otu_id.rs... | the_stack_v2_python_sparse | virtool/otus/api.py | virtool/virtool | train | 45 | |
e9560d463e5144538e379603b5e3d8e3baa7d891 | [
"grid = gd.makeGrid(grid_type, **grid_kwargs)\nwith scipyio.FortranFile(filename, mode='r') as f:\n print('Reading input from {0}'.format(filename))\n return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())",
"with scipyio.FortranFile(filename, mode='w') as f:\n print('Writing output to ... | <|body_start_0|>
grid = gd.makeGrid(grid_type, **grid_kwargs)
with scipyio.FortranFile(filename, mode='r') as f:
print('Reading input from {0}'.format(filename))
return f.read_record(self.data_type).reshape(grid.get_grid_dimensions())
<|end_body_0|>
<|body_start_1|>
with... | Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats | SciPyFortranFileIOHelper | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_36k_train_019113 | 23,117 | permissive | [
{
"docstring": "Load a field from a unformatted fortran file using a method from scipy Arguments: filename: string; full path of the file to load grid_type: string; keyword specifying what type of grid to use **grid_kwargs: keyword dictionary; keyword arguments giving parameters of the grid fieldname, timeslice... | 2 | stack_v2_sparse_classes_30k_train_004774 | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | Implement the Python class `SciPyFortranFileIOHelper` described below.
Class description:
Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats
Method signatures and docstrings:
- def load_field(self, ... | 08b627238c4bfa39026820c6116c1ed71f453b22 | <|skeleton|>
class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_gri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SciPyFortranFileIOHelper:
"""Class to load and write unformatted fortran files using SciPy Library. Public methods: As for parent class This class will work only for reading and writing 64-bit floats"""
def load_field(self, filename, unmask=True, timeslice=None, fieldname=None, check_for_grid_info=False,... | the_stack_v2_python_sparse | Dynamic_HD_Scripts/Dynamic_HD_Scripts/base/iohelper.py | ThomasRiddick/DynamicHD | train | 1 |
202f82b2edccbac31699b66e90c4413a1a79db79 | [
"f = [False for i in range(0, len(s) + 1)]\nf[0] = True\nfor i in range(1, len(s) + 1):\n j = i - 1\n while j >= 0:\n if f[j] and s[j:i] in wordDict:\n f[i] = True\n break\n j -= 1\nreturn f[len(s)]",
"dp = [True] + [False] * len(s)\nfor i in xrange(1, len(s) + 1):\n j... | <|body_start_0|>
f = [False for i in range(0, len(s) + 1)]
f[0] = True
for i in range(1, len(s) + 1):
j = i - 1
while j >= 0:
if f[j] and s[j:i] in wordDict:
f[i] = True
break
j -= 1
return f[... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_0|>
def wordBreak_self(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019114 | 925 | no_license | [
{
"docstring": ":type s: str :type wordDict: Set[str] :rtype: bool",
"name": "wordBreak",
"signature": "def wordBreak(self, s, wordDict)"
},
{
"docstring": ":type s: str :type wordDict: Set[str] :rtype: bool",
"name": "wordBreak_self",
"signature": "def wordBreak_self(self, s, wordDict)"... | 2 | stack_v2_sparse_classes_30k_train_017719 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool
- def wordBreak_self(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def wordBreak(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool
- def wordBreak_self(self, s, wordDict): :type s: str :type wordDict: Set[str] :rtype: bool
... | ea492ec864b50547214ecbbb2cdeeac21e70229b | <|skeleton|>
class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_0|>
def wordBreak_self(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def wordBreak(self, s, wordDict):
""":type s: str :type wordDict: Set[str] :rtype: bool"""
f = [False for i in range(0, len(s) + 1)]
f[0] = True
for i in range(1, len(s) + 1):
j = i - 1
while j >= 0:
if f[j] and s[j:i] in wordDi... | the_stack_v2_python_sparse | 139_word_break/sol.py | lianke123321/leetcode_sol | train | 0 | |
333bb71a0f464323e623b6126d50226f93b36e55 | [
"super(RecycleBinMetadataFile, self).__init__(debug=debug, output_writer=output_writer)\nself.deletion_time = None\nself.format_version = None\nself.original_filename = None\nself.original_file_size = None",
"data_type_map = self._GetDataTypeMap('recycle_bin_metadata_file_header')\nfile_header, _ = self._ReadStru... | <|body_start_0|>
super(RecycleBinMetadataFile, self).__init__(debug=debug, output_writer=output_writer)
self.deletion_time = None
self.format_version = None
self.original_filename = None
self.original_file_size = None
<|end_body_0|>
<|body_start_1|>
data_type_map = self.... | Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. original_size (int): original size of the deleted file. | RecycleBinMetadataFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. origina... | stack_v2_sparse_classes_36k_train_019115 | 4,156 | permissive | [
{
"docstring": "Initializes a Windows Recycle.Bin metadata ($I) file. Args: debug (Optional[bool]): True if debug information should be written. output_writer (Optional[OutputWriter]): output writer.",
"name": "__init__",
"signature": "def __init__(self, debug=False, output_writer=None)"
},
{
"d... | 4 | stack_v2_sparse_classes_30k_train_018055 | Implement the Python class `RecycleBinMetadataFile` described below.
Class description:
Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): ori... | Implement the Python class `RecycleBinMetadataFile` described below.
Class description:
Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): ori... | 55007dcac48efff42c497e739208ebfb88e4048d | <|skeleton|>
class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. origina... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecycleBinMetadataFile:
"""Windows Recycle.Bin metadata ($I) file. Attributes: deletion_time (int): FILETIME timestamp of the date and time the original file was deleted. format_version (int): format version of the metadata file. original_filename (str): original name of the deleted file. original_size (int):... | the_stack_v2_python_sparse | dtformats/recycle_bin.py | libyal/dtformats | train | 109 |
46bbb97a8e8f7caed5270b07abe10c59766a1fbd | [
"repo_file = config['repositoryFile']\nrepo_rhel_suse = config['configurations']['cluster-env']['repo_suse_rhel_template']\nrepo_ubuntu = config['configurations']['cluster-env']['repo_ubuntu_template']\nif is_empty(repo_file):\n return\nself.template = repo_rhel_suse if OSCheck.is_redhat_family() or OSCheck.is_s... | <|body_start_0|>
repo_file = config['repositoryFile']
repo_rhel_suse = config['configurations']['cluster-env']['repo_suse_rhel_template']
repo_ubuntu = config['configurations']['cluster-env']['repo_ubuntu_template']
if is_empty(repo_file):
return
self.template = repo_... | RepositoryUtil | [
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"OFL-1.1",
"MS-PL",
"AFL-2.1",
"GPL-2.0-only",
"Python-2.0",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryUtil:
def __init__(self, config):
"""Constructor for RepositoryUtil :type config dict"""
<|body_0|>
def create_repo_files(self):
"""Creates repositories in a consistent manner for all types :return: a dictionary with repo ID => repo file name mapping"""
... | stack_v2_sparse_classes_36k_train_019116 | 7,110 | permissive | [
{
"docstring": "Constructor for RepositoryUtil :type config dict",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Creates repositories in a consistent manner for all types :return: a dictionary with repo ID => repo file name mapping",
"name": "create_repo_fi... | 2 | null | Implement the Python class `RepositoryUtil` described below.
Class description:
Implement the RepositoryUtil class.
Method signatures and docstrings:
- def __init__(self, config): Constructor for RepositoryUtil :type config dict
- def create_repo_files(self): Creates repositories in a consistent manner for all types ... | Implement the Python class `RepositoryUtil` described below.
Class description:
Implement the RepositoryUtil class.
Method signatures and docstrings:
- def __init__(self, config): Constructor for RepositoryUtil :type config dict
- def create_repo_files(self): Creates repositories in a consistent manner for all types ... | 23881f23577a65de396238998e8672d6c4c5a250 | <|skeleton|>
class RepositoryUtil:
def __init__(self, config):
"""Constructor for RepositoryUtil :type config dict"""
<|body_0|>
def create_repo_files(self):
"""Creates repositories in a consistent manner for all types :return: a dictionary with repo ID => repo file name mapping"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RepositoryUtil:
def __init__(self, config):
"""Constructor for RepositoryUtil :type config dict"""
repo_file = config['repositoryFile']
repo_rhel_suse = config['configurations']['cluster-env']['repo_suse_rhel_template']
repo_ubuntu = config['configurations']['cluster-env']['rep... | the_stack_v2_python_sparse | ambari-common/src/main/python/resource_management/libraries/functions/repository_util.py | apache/ambari | train | 2,078 | |
f6ad05f46a13c7cd3f9d4295afbc588fe3802b6e | [
"self.__format = '!I'\nself.__prefix_length = struct.calcsize(self.__format)\nself.__max_request_size = max_request_size",
"original_position = None\ntry:\n original_position = input_buffer.tell()\n if num_bytes > self.__prefix_length:\n length, = compat.struct_unpack_unicode(six.ensure_str(self.__fo... | <|body_start_0|>
self.__format = '!I'
self.__prefix_length = struct.calcsize(self.__format)
self.__max_request_size = max_request_size
<|end_body_0|>
<|body_start_1|>
original_position = None
try:
original_position = input_buffer.tell()
if num_bytes > sel... | Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network order that specifies the size of the request in bytes. Those bytes are then read fro... | Int32RequestParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Int32RequestParser:
"""Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network order that specifies the size of the r... | stack_v2_sparse_classes_36k_train_019117 | 30,552 | permissive | [
{
"docstring": "Creates a new instance. @param max_request_size: The maximum number of bytes that can be contained in an individual request.",
"name": "__init__",
"signature": "def __init__(self, max_request_size)"
},
{
"docstring": "Returns the next complete request from 'input_buffer'. If ther... | 2 | null | Implement the Python class `Int32RequestParser` described below.
Class description:
Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network... | Implement the Python class `Int32RequestParser` described below.
Class description:
Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network... | 5099a498edc47ab841965b483c2c32af49eb7dae | <|skeleton|>
class Int32RequestParser:
"""Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network order that specifies the size of the r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Int32RequestParser:
"""Simple abstraction that implements a 'parse_request' that can be used to parse incoming requests that are sent using an integer prefix format. This supports binary protocols where each request is prefixed by a 4 byte integer in network order that specifies the size of the request in byt... | the_stack_v2_python_sparse | scalyr_agent/monitor_utils/server_processors.py | scalyr/scalyr-agent-2 | train | 75 |
8555721f123b1a72ec96c19a099efaed1920814f | [
"self.nstates = nstates\nself.beta = beta\nself.precision = precision\nself.two_stage = two_stage\nself.burnin = True\nself.time = 0\nself.burnin_length = None\nif zetas is None:\n self.zetas = np.zeros(self.nstates)\nelif len(zetas) != self.nstates:\n raise Exception('The length of the bias/estimate (zetas)... | <|body_start_0|>
self.nstates = nstates
self.beta = beta
self.precision = precision
self.two_stage = two_stage
self.burnin = True
self.time = 0
self.burnin_length = None
if zetas is None:
self.zetas = np.zeros(self.nstates)
elif len(zet... | Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling over states and configurations. [1] Z. Tan, "Optimally adjusted mixture sampling ... | SAMSAdaptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SAMSAdaptor:
"""Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling over states and configurations. [1] Z. Tan... | stack_v2_sparse_classes_36k_train_019118 | 11,523 | permissive | [
{
"docstring": "Parameters ---------- nstates: int The number of free energies to infer zeta: numpy array The estimate of the free energy and the current state biasing potential target_weights: numpy array vector of the state probabilities that the sampler should converge to. two_stage: bool whether to perform ... | 3 | stack_v2_sparse_classes_30k_train_005370 | Implement the Python class `SAMSAdaptor` described below.
Class description:
Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling ove... | Implement the Python class `SAMSAdaptor` described below.
Class description:
Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling ove... | d30804beb158960a62f94182c694df6dd9130fb8 | <|skeleton|>
class SAMSAdaptor:
"""Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling over states and configurations. [1] Z. Tan... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SAMSAdaptor:
"""Implements the update scheme for self adjusted mixture sampling as described by Z. Tan in [1]. Can use either the Rao-Blackwellized or binary update schemes. To function, this class must be paired with a method to perform mixture sampling over states and configurations. [1] Z. Tan, "Optimally ... | the_stack_v2_python_sparse | saltswap/sams_adapter.py | Byun-jinyoung/saltswap | train | 0 |
86ef44fdca4a098f36ad5cba29a2886a9cee8e54 | [
"copied = matrix.copy()\nrows = set()\ncolumns = set()\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n rows.add(i)\n columns.add(j)\nfor i in range(len(copied)):\n for j in range(len(copied[0])):\n if i in rows or j in columns:\n ... | <|body_start_0|>
copied = matrix.copy()
rows = set()
columns = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 0:
rows.add(i)
columns.add(j)
for i in range(len(copied)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
<|body_0|>
def setZeroes1(self, matrix):
"""Does not return anything, modifies mat... | stack_v2_sparse_classes_36k_train_019119 | 1,424 | no_license | [
{
"docstring": "Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.",
"name": "setZeroes",
"signature": "def setZeroes(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "Does not return anything, modifies matrix in-place inst... | 2 | stack_v2_sparse_classes_30k_train_017845 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.
- def set... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def setZeroes(self, matrix: List[List[int]]) -> None: Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix.
- def set... | 95a86cbbca28d0c0f6d72d28a2f1cb5a86327934 | <|skeleton|>
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
<|body_0|>
def setZeroes1(self, matrix):
"""Does not return anything, modifies mat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""Purpose: Given an m x n integer matrix, sets its entire row and column to 0's if element is 0. Returns the matrix."""
copied = matrix.copy()
rows = set()
columns = set()
for i in range(len(matrix)):
... | the_stack_v2_python_sparse | setMatrixZeroes.py | tashakim/puzzles_python | train | 8 | |
0e5b547ca093c89e0c5c65b00b444dcc81d6b077 | [
"api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)\nif await api.get_active_dataset_tlvs() is None:\n allowed_channel = await get_allowed_channel(self.hass, otbr_url)\n thread_dataset_channel = None\n thread_dataset_tlv = await async_get_preferred_dataset(self.hass)\n if threa... | <|body_start_0|>
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass), 10)
if await api.get_active_dataset_tlvs() is None:
allowed_channel = await get_allowed_channel(self.hass, otbr_url)
thread_dataset_channel = None
thread_dataset_tlv = await asyn... | Handle a config flow for Open Thread Border Router. | OTBRConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_36k_train_019120 | 4,982 | permissive | [
{
"docstring": "Connect to the OTBR and create or apply a dataset if it doesn't have one.",
"name": "_connect_and_set_dataset",
"signature": "async def _connect_and_set_dataset(self, otbr_url: str) -> None"
},
{
"docstring": "Set up by user.",
"name": "async_step_user",
"signature": "asy... | 3 | stack_v2_sparse_classes_30k_train_015482 | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | Implement the Python class `OTBRConfigFlow` described below.
Class description:
Handle a config flow for Open Thread Border Router.
Method signatures and docstrings:
- async def _connect_and_set_dataset(self, otbr_url: str) -> None: Connect to the OTBR and create or apply a dataset if it doesn't have one.
- async def... | 2e65b77b2b5c17919939481f327963abdfdc53f0 | <|skeleton|>
class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
<|body_0|>
async def async_step_user(self, user_inpu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OTBRConfigFlow:
"""Handle a config flow for Open Thread Border Router."""
async def _connect_and_set_dataset(self, otbr_url: str) -> None:
"""Connect to the OTBR and create or apply a dataset if it doesn't have one."""
api = python_otbr_api.OTBR(otbr_url, async_get_clientsession(self.hass... | the_stack_v2_python_sparse | homeassistant/components/otbr/config_flow.py | konnected-io/home-assistant | train | 24 |
0ea8ac8090ae397b5cfaaab7595b0d30ec78d823 | [
"super().__init__(metadata, **kwargs)\nself.col = col\nbasic_meta = backend_key_to_query(key).copy()\nself.col.delete_many(basic_meta)\nbasic_meta['write_time'] = datetime.now(py_utc)\nbasic_meta['run_start_time'] = datetime.now(py_utc)\nbasic_meta['provides_meta'] = True\nself.run_start = None\nself.basic_md = bas... | <|body_start_0|>
super().__init__(metadata, **kwargs)
self.col = col
basic_meta = backend_key_to_query(key).copy()
self.col.delete_many(basic_meta)
basic_meta['write_time'] = datetime.now(py_utc)
basic_meta['run_start_time'] = datetime.now(py_utc)
basic_meta['prov... | MongoSaver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MongoSaver:
def __init__(self, key: str, metadata: dict, col: collection.Collection, **kwargs):
"""Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belonging to data :param col: collection (NB! pymongo collection object) of mongo instance to write to"""
... | stack_v2_sparse_classes_36k_train_019121 | 14,056 | permissive | [
{
"docstring": "Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belonging to data :param col: collection (NB! pymongo collection object) of mongo instance to write to",
"name": "__init__",
"signature": "def __init__(self, key: str, metadata: dict, col: collection.Collec... | 4 | stack_v2_sparse_classes_30k_train_021170 | Implement the Python class `MongoSaver` described below.
Class description:
Implement the MongoSaver class.
Method signatures and docstrings:
- def __init__(self, key: str, metadata: dict, col: collection.Collection, **kwargs): Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belongin... | Implement the Python class `MongoSaver` described below.
Class description:
Implement the MongoSaver class.
Method signatures and docstrings:
- def __init__(self, key: str, metadata: dict, col: collection.Collection, **kwargs): Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belongin... | a466a94b5dd576cf7eda12ace8760fd60dc3df11 | <|skeleton|>
class MongoSaver:
def __init__(self, key: str, metadata: dict, col: collection.Collection, **kwargs):
"""Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belonging to data :param col: collection (NB! pymongo collection object) of mongo instance to write to"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MongoSaver:
def __init__(self, key: str, metadata: dict, col: collection.Collection, **kwargs):
"""Mongo saver :param key: string of strax.Datakey :param metadata: metadata to save belonging to data :param col: collection (NB! pymongo collection object) of mongo instance to write to"""
super()... | the_stack_v2_python_sparse | strax/storage/mongo.py | AxFoundation/strax | train | 21 | |
0042b76b5952a98b759c5f262c5ba7fc20b09e1e | [
"inventory = Inventory.objects.get(pk=self.kwargs['pk'])\ninitial = {'quantity': inventory.quantity}\nreturn initial",
"context = super(UpdateInventory, self).get_context_data(**kwargs)\ninventory = Inventory.objects.get(pk=self.kwargs['pk'])\ncontext.update({'page_header': 'Update an Inventory Item', 'item': inv... | <|body_start_0|>
inventory = Inventory.objects.get(pk=self.kwargs['pk'])
initial = {'quantity': inventory.quantity}
return initial
<|end_body_0|>
<|body_start_1|>
context = super(UpdateInventory, self).get_context_data(**kwargs)
inventory = Inventory.objects.get(pk=self.kwargs['... | Update an inventory object. | UpdateInventory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateInventory:
"""Update an inventory object."""
def get_initial(self):
"""Get the initial data for the form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get context data."""
<|body_1|>
def form_valid(self, form):
"""Handle a val... | stack_v2_sparse_classes_36k_train_019122 | 5,788 | no_license | [
{
"docstring": "Get the initial data for the form.",
"name": "get_initial",
"signature": "def get_initial(self)"
},
{
"docstring": "Get context data.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Handle a valid update.",
... | 3 | stack_v2_sparse_classes_30k_train_012035 | Implement the Python class `UpdateInventory` described below.
Class description:
Update an inventory object.
Method signatures and docstrings:
- def get_initial(self): Get the initial data for the form.
- def get_context_data(self, **kwargs): Get context data.
- def form_valid(self, form): Handle a valid update. | Implement the Python class `UpdateInventory` described below.
Class description:
Update an inventory object.
Method signatures and docstrings:
- def get_initial(self): Get the initial data for the form.
- def get_context_data(self, **kwargs): Get context data.
- def form_valid(self, form): Handle a valid update.
<|s... | c4b172b284b800a57f02c9a464580a18c76718df | <|skeleton|>
class UpdateInventory:
"""Update an inventory object."""
def get_initial(self):
"""Get the initial data for the form."""
<|body_0|>
def get_context_data(self, **kwargs):
"""Get context data."""
<|body_1|>
def form_valid(self, form):
"""Handle a val... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateInventory:
"""Update an inventory object."""
def get_initial(self):
"""Get the initial data for the form."""
inventory = Inventory.objects.get(pk=self.kwargs['pk'])
initial = {'quantity': inventory.quantity}
return initial
def get_context_data(self, **kwargs):
... | the_stack_v2_python_sparse | merchandise/inventory/views.py | mwm5945/CMPSC-431 | train | 0 |
4dbe354bcbb961bd1170a72e3f0b30afc0d11572 | [
"instance, version = more_data\nif self.INSTANCE is not None and self.INSTANCE != instance:\n raise ValueError('invalid instance {0} for {1}'.format(instance, self))\nelif self.INSTANCE is not None and instance not in (0, 1):\n try:\n min_val, max_val = INSTANCE_EXCEPTIONS[self.type]\n is_ok = m... | <|body_start_0|>
instance, version = more_data
if self.INSTANCE is not None and self.INSTANCE != instance:
raise ValueError('invalid instance {0} for {1}'.format(instance, self))
elif self.INSTANCE is not None and instance not in (0, 1):
try:
min_val, max_... | A Record within a ppt file; has instance and version fields | PptRecord | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PptRecord:
"""A Record within a ppt file; has instance and version fields"""
def finish_constructing(self, more_data):
"""check and save instance and version"""
<|body_0|>
def _type_str(self):
"""helper for __str__, base implementation"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k_train_019123 | 29,559 | permissive | [
{
"docstring": "check and save instance and version",
"name": "finish_constructing",
"signature": "def finish_constructing(self, more_data)"
},
{
"docstring": "helper for __str__, base implementation",
"name": "_type_str",
"signature": "def _type_str(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000584 | Implement the Python class `PptRecord` described below.
Class description:
A Record within a ppt file; has instance and version fields
Method signatures and docstrings:
- def finish_constructing(self, more_data): check and save instance and version
- def _type_str(self): helper for __str__, base implementation | Implement the Python class `PptRecord` described below.
Class description:
A Record within a ppt file; has instance and version fields
Method signatures and docstrings:
- def finish_constructing(self, more_data): check and save instance and version
- def _type_str(self): helper for __str__, base implementation
<|ske... | fb4546ec1be5f46d53856161e46ea53d7b7e532a | <|skeleton|>
class PptRecord:
"""A Record within a ppt file; has instance and version fields"""
def finish_constructing(self, more_data):
"""check and save instance and version"""
<|body_0|>
def _type_str(self):
"""helper for __str__, base implementation"""
<|body_1|>
<|en... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PptRecord:
"""A Record within a ppt file; has instance and version fields"""
def finish_constructing(self, more_data):
"""check and save instance and version"""
instance, version = more_data
if self.INSTANCE is not None and self.INSTANCE != instance:
raise ValueError('... | the_stack_v2_python_sparse | oletools/ppt_record_parser.py | decalage2/oletools | train | 2,601 |
87368b51c1f1784b15294fe42a4709ef0866ee44 | [
"self.verbose = set_or_default(verbose, VERBOSE)\n'If ``True`` return verbose results.'\nself.fatal = set_or_default(fatal, FATAL)\n'If ``True``, die on test failure'\nself.passing = set_or_default(passing, PASSING)\n'If ``True`` attempt to return passing test cases.'\nself.results = {}\n'Dict that represents the r... | <|body_start_0|>
self.verbose = set_or_default(verbose, VERBOSE)
'If ``True`` return verbose results.'
self.fatal = set_or_default(fatal, FATAL)
'If ``True``, die on test failure'
self.passing = set_or_default(passing, PASSING)
'If ``True`` attempt to return passing test ... | DtfResults | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DtfResults:
def __init__(self, verbose=None, fatal=None, passing=None):
"""An interface to capture and report results from DtfCases."""
<|body_0|>
def add(self, name, result, msg):
""":param string name: The name of the test. :param bool result: ``True`` if the test ... | stack_v2_sparse_classes_36k_train_019124 | 4,828 | permissive | [
{
"docstring": "An interface to capture and report results from DtfCases.",
"name": "__init__",
"signature": "def __init__(self, verbose=None, fatal=None, passing=None)"
},
{
"docstring": ":param string name: The name of the test. :param bool result: ``True`` if the test passed, and ``False`` if... | 6 | stack_v2_sparse_classes_30k_train_011928 | Implement the Python class `DtfResults` described below.
Class description:
Implement the DtfResults class.
Method signatures and docstrings:
- def __init__(self, verbose=None, fatal=None, passing=None): An interface to capture and report results from DtfCases.
- def add(self, name, result, msg): :param string name: ... | Implement the Python class `DtfResults` described below.
Class description:
Implement the DtfResults class.
Method signatures and docstrings:
- def __init__(self, verbose=None, fatal=None, passing=None): An interface to capture and report results from DtfCases.
- def add(self, name, result, msg): :param string name: ... | 34bb5b5e0fcc986e923bd20102faeddf96437508 | <|skeleton|>
class DtfResults:
def __init__(self, verbose=None, fatal=None, passing=None):
"""An interface to capture and report results from DtfCases."""
<|body_0|>
def add(self, name, result, msg):
""":param string name: The name of the test. :param bool result: ``True`` if the test ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DtfResults:
def __init__(self, verbose=None, fatal=None, passing=None):
"""An interface to capture and report results from DtfCases."""
self.verbose = set_or_default(verbose, VERBOSE)
'If ``True`` return verbose results.'
self.fatal = set_or_default(fatal, FATAL)
'If ``... | the_stack_v2_python_sparse | dtf/results.py | tychoish/dtf | train | 0 | |
ca3cf6a429f153b11d70c5962487ea774c7b4ec4 | [
"def normal_normal_model():\n loc = ed.norm.rvs(loc=0.0, scale=1.0, name='loc')\n x = ed.norm.rvs(loc=loc, scale=0.5, size=5, name='x')\n return x\nlog_joint = ed.make_log_joint_fn(normal_normal_model)\nx = np.random.normal(size=5)\nloc = 0.3\nvalue = log_joint(loc=loc, x=x)\ntrue_value = np.sum(ed.norm.lo... | <|body_start_0|>
def normal_normal_model():
loc = ed.norm.rvs(loc=0.0, scale=1.0, name='loc')
x = ed.norm.rvs(loc=loc, scale=0.5, size=5, name='x')
return x
log_joint = ed.make_log_joint_fn(normal_normal_model)
x = np.random.normal(size=5)
loc = 0.3
... | ProgramTransformationsTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgramTransformationsTest:
def testMakeLogJointUnconditional(self):
"""Test `make_log_joint` works on unconditional model."""
<|body_0|>
def testMakeLogJointConditional(self):
"""Test `make_log_joint` works on conditional model."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_019125 | 2,566 | permissive | [
{
"docstring": "Test `make_log_joint` works on unconditional model.",
"name": "testMakeLogJointUnconditional",
"signature": "def testMakeLogJointUnconditional(self)"
},
{
"docstring": "Test `make_log_joint` works on conditional model.",
"name": "testMakeLogJointConditional",
"signature":... | 2 | null | Implement the Python class `ProgramTransformationsTest` described below.
Class description:
Implement the ProgramTransformationsTest class.
Method signatures and docstrings:
- def testMakeLogJointUnconditional(self): Test `make_log_joint` works on unconditional model.
- def testMakeLogJointConditional(self): Test `ma... | Implement the Python class `ProgramTransformationsTest` described below.
Class description:
Implement the ProgramTransformationsTest class.
Method signatures and docstrings:
- def testMakeLogJointUnconditional(self): Test `make_log_joint` works on unconditional model.
- def testMakeLogJointConditional(self): Test `ma... | ccdb9bfb11fe713bc449f0e884b405f619f58059 | <|skeleton|>
class ProgramTransformationsTest:
def testMakeLogJointUnconditional(self):
"""Test `make_log_joint` works on unconditional model."""
<|body_0|>
def testMakeLogJointConditional(self):
"""Test `make_log_joint` works on conditional model."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProgramTransformationsTest:
def testMakeLogJointUnconditional(self):
"""Test `make_log_joint` works on unconditional model."""
def normal_normal_model():
loc = ed.norm.rvs(loc=0.0, scale=1.0, name='loc')
x = ed.norm.rvs(loc=loc, scale=0.5, size=5, name='x')
... | the_stack_v2_python_sparse | edward2/numpy/program_transformations_test.py | google/edward2 | train | 710 | |
c633026c2b19ad0ee5bf152374999fc839ac3503 | [
"_query_builder = Configuration.get_base_uri()\n_query_builder += '/signature/themes/list/spinners'\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/json'}\n_request = self.http_client.get(_query_url, headers=_headers)\n_context = self.execute_request(_request)\nself.validate_re... | <|body_start_0|>
_query_builder = Configuration.get_base_uri()
_query_builder += '/signature/themes/list/spinners'
_query_url = APIHelper.clean_url(_query_builder)
_headers = {'accept': 'application/json'}
_request = self.http_client.get(_query_url, headers=_headers)
_con... | A Controller to access Endpoints in the idfy_rest_client API. | ThemesController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThemesController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def themes_list_spinners(self):
"""Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in our sign application Returns: list of ThemesListSpinners... | stack_v2_sparse_classes_36k_train_019126 | 2,851 | permissive | [
{
"docstring": "Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in our sign application Returns: list of ThemesListSpinnersResponse: Response from the API. OK Raises: APIException: When an error occurs while fetching the data from the remote API. This exce... | 2 | stack_v2_sparse_classes_30k_train_001549 | Implement the Python class `ThemesController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def themes_list_spinners(self): Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in... | Implement the Python class `ThemesController` described below.
Class description:
A Controller to access Endpoints in the idfy_rest_client API.
Method signatures and docstrings:
- def themes_list_spinners(self): Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class ThemesController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def themes_list_spinners(self):
"""Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in our sign application Returns: list of ThemesListSpinners... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThemesController:
"""A Controller to access Endpoints in the idfy_rest_client API."""
def themes_list_spinners(self):
"""Does a GET request to /signature/themes/list/spinners. This endpoint lists all the spinners you can use in our sign application Returns: list of ThemesListSpinnersResponse: Res... | the_stack_v2_python_sparse | idfy_rest_client/controllers/themes_controller.py | dealflowteam/Idfy | train | 0 |
b2f58b8890d4474f4ec55612673d0dd3e4cfd885 | [
"cleaned_data = super(RegistrationForm, self).clean()\npassword = cleaned_data.get('password')\npassword_confirmation = cleaned_data.get('password_confirmation')\nif password and password_confirmation:\n if password != password_confirmation:\n self.add_error('password_confirmation', 'Does not match passwo... | <|body_start_0|>
cleaned_data = super(RegistrationForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
if password and password_confirmation:
if password != password_confirmation:
self.ad... | Registration form class. | RegistrationForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Create new user."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cleaned_data = super(RegistrationForm,... | stack_v2_sparse_classes_36k_train_019127 | 1,850 | no_license | [
{
"docstring": "Clean data and add custom validation.",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Create new user.",
"name": "submit",
"signature": "def submit(self)"
}
] | 2 | null | Implement the Python class `RegistrationForm` described below.
Class description:
Registration form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Create new user. | Implement the Python class `RegistrationForm` described below.
Class description:
Registration form class.
Method signatures and docstrings:
- def clean(self): Clean data and add custom validation.
- def submit(self): Create new user.
<|skeleton|>
class RegistrationForm:
"""Registration form class."""
def c... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
<|body_0|>
def submit(self):
"""Create new user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationForm:
"""Registration form class."""
def clean(self):
"""Clean data and add custom validation."""
cleaned_data = super(RegistrationForm, self).clean()
password = cleaned_data.get('password')
password_confirmation = cleaned_data.get('password_confirmation')
... | the_stack_v2_python_sparse | app/authorization/forms/registration.py | vsokoltsov/Interview360Server | train | 2 |
e9c911901c87fcb8c5d5249a47d255643f37677f | [
"self.nums = nums\ni = len(nums) - 1\nj = len(nums) - 1\nif nums == []:\n self.dp = []\nelse:\n '\\n self.dp = [[0 for ind in range(j+1) ] for ind in range(i+1)]\\n self.dp[0][0] = self.nums[0]\\n\\n for ind_x in range(i+1):\\n for ind_y in range(ind_x,j+1):\\... | <|body_start_0|>
self.nums = nums
i = len(nums) - 1
j = len(nums) - 1
if nums == []:
self.dp = []
else:
'\n self.dp = [[0 for ind in range(j+1) ] for ind in range(i+1)]\n self.dp[0][0] = self.nums[0]\n\n for ind_x in range... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums = nums
i = len(nums) - 1
j = len(... | stack_v2_sparse_classes_36k_train_019128 | 2,243 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 507d5d8c904672f994d0418fa96bd42695464d80 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums = nums
i = len(nums) - 1
j = len(nums) - 1
if nums == []:
self.dp = []
else:
'\n self.dp = [[0 for ind in range(j+1) ] for ind in range(i+1)]\n ... | the_stack_v2_python_sparse | coding_100/303_NumArray.py | LEE2020/leetcode | train | 0 | |
8b883f3cb5a9a35bf60c92ea39e1afc33181e7c2 | [
"filter_parser = reqparse.RequestParser(bundle_errors=True)\nfilter_parser.add_argument('page', type=int, default=DEFAULT_PAGE, location='args')\nfilter_parser.add_argument('size', type=int, default=DEFAULT_SITE, location='args')\nfilter_parser_args = filter_parser.parse_args()\nif not filter_parser_args:\n abor... | <|body_start_0|>
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('page', type=int, default=DEFAULT_PAGE, location='args')
filter_parser.add_argument('size', type=int, default=DEFAULT_SITE, location='args')
filter_parser_args = filter_parser.parse_arg... | CalendarsResource | CalendarsResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CalendarsResource:
"""CalendarsResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:8000/calendar -H "Content-Type: applica... | stack_v2_sparse_classes_36k_train_019129 | 8,144 | no_license | [
{
"docstring": "Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Example: curl http://0.0.0.0:8000/calendar -H \"Content-Type: application/json\" -X POST -d ' { \"calendar\": { \"... | 3 | stack_v2_sparse_classes_30k_train_018315 | Implement the Python class `CalendarsResource` described below.
Class description:
CalendarsResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:
- def post(self): Example: curl http://0.0.0.0:8000/calendar -H "... | Implement the Python class `CalendarsResource` described below.
Class description:
CalendarsResource
Method signatures and docstrings:
- def get(self): Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:
- def post(self): Example: curl http://0.0.0.0:8000/calendar -H "... | 0b44d83b95079734ac9aa78bc7af40a0a7530bca | <|skeleton|>
class CalendarsResource:
"""CalendarsResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:"""
<|body_0|>
def post(self):
"""Example: curl http://0.0.0.0:8000/calendar -H "Content-Type: applica... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CalendarsResource:
"""CalendarsResource"""
def get(self):
"""Example: curl http://0.0.0.0:8000/calendar curl http://0.0.0.0:8000/calendar?page=1&size=20 :return:"""
filter_parser = reqparse.RequestParser(bundle_errors=True)
filter_parser.add_argument('page', type=int, default=DEFA... | the_stack_v2_python_sparse | apps/lims/calendar/resource.py | zhanghe06/lims_project | train | 1 |
b840d897bfbf1baf78484625f3f2acec8c080e4a | [
"if n <= 0:\n return\nnumbers = ['0'] * n\nwhile not self.Increment(numbers):\n self.PrintNumber(numbers)",
"isOverFlow = False\ncircle = 0\nlength = len(numbers)\nfor i in range(length - 1, -1, -1):\n nSum = int(numbers[i]) + circle\n if i == length - 1:\n nSum += 1\n if nSum >= 10:\n ... | <|body_start_0|>
if n <= 0:
return
numbers = ['0'] * n
while not self.Increment(numbers):
self.PrintNumber(numbers)
<|end_body_0|>
<|body_start_1|>
isOverFlow = False
circle = 0
length = len(numbers)
for i in range(length - 1, -1, -1):
... | Solution1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution1:
def print1ToMaxOfNDigits(self, n):
"""首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零数字打印"""
<|body_0|>
def Increment(self, numbers):
"""数组表示数字累加1,并判断是否到达了最大n位数""... | stack_v2_sparse_classes_36k_train_019130 | 4,129 | no_license | [
{
"docstring": "首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零数字打印",
"name": "print1ToMaxOfNDigits",
"signature": "def print1ToMaxOfNDigits(self, n)"
},
{
"docstring": "数组表示数字累加1,并判断是否到达了最大n位数",
"n... | 3 | null | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def print1ToMaxOfNDigits(self, n): 首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零... | Implement the Python class `Solution1` described below.
Class description:
Implement the Solution1 class.
Method signatures and docstrings:
- def print1ToMaxOfNDigits(self, n): 首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution1:
def print1ToMaxOfNDigits(self, n):
"""首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零数字打印"""
<|body_0|>
def Increment(self, numbers):
"""数组表示数字累加1,并判断是否到达了最大n位数""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution1:
def print1ToMaxOfNDigits(self, n):
"""首先注意到这是一个【大数问题】,没有指定n的大小,可能非常非常大,数字超过了存储范围,考虑使用字符串和数组存储数字 在本题中主要分为两步: 第一步:用字符数组表示的数字累加1,需要模拟数字的加法,还需要判断是否已经达到最大的n位数:第一位发生进位 第二步:打印字符数组,从第一个非零数字打印"""
if n <= 0:
return
numbers = ['0'] * n
while not self.Increment(numbe... | the_stack_v2_python_sparse | 剑指offer/第一遍/array/36-1.打印1到最大的n位数.py | leilalu/algorithm | train | 0 | |
20ed781c5e5885e92eb6cd7b5d0b18aefefa56a5 | [
"if type(authorization_header) != str or authorization_header is None or authorization_header[0:6] != 'Basic ':\n return None\nelse:\n return authorization_header[6:len(authorization_header)]",
"if type(base64_authorization_header) != str or base64_authorization_header is None:\n return None\ntry:\n r... | <|body_start_0|>
if type(authorization_header) != str or authorization_header is None or authorization_header[0:6] != 'Basic ':
return None
else:
return authorization_header[6:len(authorization_header)]
<|end_body_0|>
<|body_start_1|>
if type(base64_authorization_header)... | for now this class litearlly does nothing except inherits from auth | BasicAuth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasicAuth:
"""for now this class litearlly does nothing except inherits from auth"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Basic - Base64 part"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_he... | stack_v2_sparse_classes_36k_train_019131 | 3,417 | no_license | [
{
"docstring": "Basic - Base64 part",
"name": "extract_base64_authorization_header",
"signature": "def extract_base64_authorization_header(self, authorization_header: str) -> str"
},
{
"docstring": "decode the value of a base64 string that is made by the above function",
"name": "decode_base... | 5 | stack_v2_sparse_classes_30k_train_019162 | Implement the Python class `BasicAuth` described below.
Class description:
for now this class litearlly does nothing except inherits from auth
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Basic - Base64 part
- def decode_base64_authorization_head... | Implement the Python class `BasicAuth` described below.
Class description:
for now this class litearlly does nothing except inherits from auth
Method signatures and docstrings:
- def extract_base64_authorization_header(self, authorization_header: str) -> str: Basic - Base64 part
- def decode_base64_authorization_head... | 2abe59720ba72d44e363b13e56ec9efed0339c33 | <|skeleton|>
class BasicAuth:
"""for now this class litearlly does nothing except inherits from auth"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Basic - Base64 part"""
<|body_0|>
def decode_base64_authorization_header(self, base64_authorization_he... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BasicAuth:
"""for now this class litearlly does nothing except inherits from auth"""
def extract_base64_authorization_header(self, authorization_header: str) -> str:
"""Basic - Base64 part"""
if type(authorization_header) != str or authorization_header is None or authorization_header[0:6]... | the_stack_v2_python_sparse | 0x06-Basic_authentication/api/v1/auth/basic_auth.py | khaldi505/holbertonschool-web_back_end | train | 1 |
904c99628266beb1aaf97143309deea9557cb50d | [
"super(Spaceship, self).__init__(position, load_image_convert_alpha('spaceship-off.png'))\nself.image_on = load_image_convert_alpha('spaceship-on.png')\nself.direction = [0, -1]\nself.is_throttle_on = False\nself.angle = 0\nself.active_missiles = []",
"if self.is_throttle_on:\n new_image, rect = rotate_center(... | <|body_start_0|>
super(Spaceship, self).__init__(position, load_image_convert_alpha('spaceship-off.png'))
self.image_on = load_image_convert_alpha('spaceship-on.png')
self.direction = [0, -1]
self.is_throttle_on = False
self.angle = 0
self.active_missiles = []
<|end_body_... | Spaceship | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spaceship:
def __init__(self, position):
"""initializing an Spaceship object given it's position"""
<|body_0|>
def draw_on(self, screen):
"""Draw the spaceship on the screen"""
<|body_1|>
def move(self):
"""Do one frame's worth of updating for th... | stack_v2_sparse_classes_36k_train_019132 | 23,271 | no_license | [
{
"docstring": "initializing an Spaceship object given it's position",
"name": "__init__",
"signature": "def __init__(self, position)"
},
{
"docstring": "Draw the spaceship on the screen",
"name": "draw_on",
"signature": "def draw_on(self, screen)"
},
{
"docstring": "Do one frame... | 4 | stack_v2_sparse_classes_30k_train_001445 | Implement the Python class `Spaceship` described below.
Class description:
Implement the Spaceship class.
Method signatures and docstrings:
- def __init__(self, position): initializing an Spaceship object given it's position
- def draw_on(self, screen): Draw the spaceship on the screen
- def move(self): Do one frame'... | Implement the Python class `Spaceship` described below.
Class description:
Implement the Spaceship class.
Method signatures and docstrings:
- def __init__(self, position): initializing an Spaceship object given it's position
- def draw_on(self, screen): Draw the spaceship on the screen
- def move(self): Do one frame'... | 4e801ecd4834e4d3b8484e6cf33cf0e1a9197490 | <|skeleton|>
class Spaceship:
def __init__(self, position):
"""initializing an Spaceship object given it's position"""
<|body_0|>
def draw_on(self, screen):
"""Draw the spaceship on the screen"""
<|body_1|>
def move(self):
"""Do one frame's worth of updating for th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Spaceship:
def __init__(self, position):
"""initializing an Spaceship object given it's position"""
super(Spaceship, self).__init__(position, load_image_convert_alpha('spaceship-off.png'))
self.image_on = load_image_convert_alpha('spaceship-on.png')
self.direction = [0, -1]
... | the_stack_v2_python_sparse | pygame-wasm/org.pygame.asteroids.py | pmp-p/pmp-p.github.io | train | 5 | |
bba310e00c1afdffef382cfdc4ce467497ec007c | [
"assert callable(path), 'path must be a function'\nassert callable(acceleration), 'acceleration must be a function'\nsuper(ParameterizedParkController, self).__init__(numpy.zeros((3, 3)), L, is_ned, is_flat)\nself._path = path\nself._acceleration = acceleration\nself._params = None",
"if params is None:\n para... | <|body_start_0|>
assert callable(path), 'path must be a function'
assert callable(acceleration), 'acceleration must be a function'
super(ParameterizedParkController, self).__init__(numpy.zeros((3, 3)), L, is_ned, is_flat)
self._path = path
self._acceleration = acceleration
... | A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure feedback form is achieved. | ParameterizedParkController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterizedParkController:
"""A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure feedback form is achieved."""
def __... | stack_v2_sparse_classes_36k_train_019133 | 19,298 | permissive | [
{
"docstring": "Constructor Arguments: path: function handle, should take a tuple of parameters which will either be set at some point or passed when a command is required. A position and inertial velocity tupled will be handed to it as the first argument from the internal state of the controller, followed by t... | 2 | stack_v2_sparse_classes_30k_train_000063 | Implement the Python class `ParameterizedParkController` described below.
Class description:
A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure fe... | Implement the Python class `ParameterizedParkController` described below.
Class description:
A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure fe... | 6827886916e36432ce1d806f0a78edef6c9270d9 | <|skeleton|>
class ParameterizedParkController:
"""A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure feedback form is achieved."""
def __... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterizedParkController:
"""A park controller which uses a parameterized trajectory In general this will work for feedback linearization cases as well as simple trajectories. By specifying a linearization function which is uniformly zero then the pure feedback form is achieved."""
def __init__(self, ... | the_stack_v2_python_sparse | pybots/src/robot_control/path_following.py | aivian/robots | train | 0 |
c76ce85112c52bafde6e529ee6819b36ee420489 | [
"self.query = query or pywikibot.input('Please enter the search query:')\nif site is None:\n site = pywikibot.Site()\nself.site = site\nself._google_query = None",
"try:\n import google\nexcept ImportError:\n pywikibot.error(\"generator GoogleSearchPageGenerator depends on package 'google'.\\nTo install,... | <|body_start_0|>
self.query = query or pywikibot.input('Please enter the search query:')
if site is None:
site = pywikibot.Site()
self.site = site
self._google_query = None
<|end_body_0|>
<|body_start_1|>
try:
import google
except ImportError:
... | Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and provided by PyPI since 2013. As there are concerns about Google's Terms of Service, this gen... | GoogleSearchPageGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GoogleSearchPageGenerator:
"""Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and provided by PyPI since 2013. As there a... | stack_v2_sparse_classes_36k_train_019134 | 43,909 | permissive | [
{
"docstring": "Initializer. :param site: Site for generator results.",
"name": "__init__",
"signature": "def __init__(self, query: Optional[str]=None, site: OPT_SITE_TYPE=None) -> None"
},
{
"docstring": "Perform a query using python package 'google'. The terms of service as at June 2014 give t... | 3 | null | Implement the Python class `GoogleSearchPageGenerator` described below.
Class description:
Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and ... | Implement the Python class `GoogleSearchPageGenerator` described below.
Class description:
Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and ... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class GoogleSearchPageGenerator:
"""Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and provided by PyPI since 2013. As there a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GoogleSearchPageGenerator:
"""Page generator using Google search results. To use this generator, you need to install the package 'google': :py:obj:`https://pypi.org/project/google` This package has been available since 2010, hosted on GitHub since 2012, and provided by PyPI since 2013. As there are concerns a... | the_stack_v2_python_sparse | pywikibot/pagegenerators/_generators.py | wikimedia/pywikibot | train | 432 |
e976c043f2799808af619251e252c78be2c4ca02 | [
"if root.val == None:\n return None\nself.maxAverage = float('-inf')\nself.maxNode = None\n\ndef helper(node):\n if not node:\n return (0, 0.0)\n leftTotal, leftSum = helper(node.left)\n rightTotal, rightSum = helper(node.right)\n currentTotal = 1 + leftTotal + rightTotal\n currentSum = nod... | <|body_start_0|>
if root.val == None:
return None
self.maxAverage = float('-inf')
self.maxNode = None
def helper(node):
if not node:
return (0, 0.0)
leftTotal, leftSum = helper(node.left)
rightTotal, rightSum = helper(node.... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def MaximumAverageSubtree(self, root):
""">>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20"""
<|body_0|>
def MaximumAverageSubtree2(self, root):
""">>> solution2 = Solution() >>> solution2.... | stack_v2_sparse_classes_36k_train_019135 | 9,088 | no_license | [
{
"docstring": ">>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20",
"name": "MaximumAverageSubtree",
"signature": "def MaximumAverageSubtree(self, root)"
},
{
"docstring": ">>> solution2 = Solution() >>> solution2.MaximumAverageS... | 2 | stack_v2_sparse_classes_30k_train_019169 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MaximumAverageSubtree(self, root): >>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20
- def MaximumAverageSu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def MaximumAverageSubtree(self, root): >>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20
- def MaximumAverageSu... | 898dc6b0d1eadf441ba06c69548a3798bcbaea99 | <|skeleton|>
class Solution:
def MaximumAverageSubtree(self, root):
""">>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20"""
<|body_0|>
def MaximumAverageSubtree2(self, root):
""">>> solution2 = Solution() >>> solution2.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def MaximumAverageSubtree(self, root):
""">>> solution = Solution() >>> solution.MaximumAverageSubtree(Node1) 14 >>> solution.MaximumAverageSubtree(Node11) 20"""
if root.val == None:
return None
self.maxAverage = float('-inf')
self.maxNode = None
... | the_stack_v2_python_sparse | Beginning/subtree_with_max_average.py | workprinond/DS_-_Algo_TechInterview_Practise | train | 0 | |
a6c1d14811b6753f1cfe0be226e1d62c1cb6b47f | [
"res = []\nif not intervals or len(intervals) == 0:\n return res\nintervals.sort(key=lambda x: x.start)\nlow, hi = (intervals[0].start, intervals[0].end)\nfor interval in intervals[1:]:\n if interval.start <= hi:\n if hi <= interval.end:\n hi = interval.end\n else:\n res.append(Int... | <|body_start_0|>
res = []
if not intervals or len(intervals) == 0:
return res
intervals.sort(key=lambda x: x.start)
low, hi = (intervals[0].start, intervals[0].end)
for interval in intervals[1:]:
if interval.start <= hi:
if hi <= interval.e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
"""Using last interval comparison method. :param intervals: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019136 | 1,593 | no_license | [
{
"docstring": ":type intervals: List[Interval] :rtype: List[Interval]",
"name": "merge1",
"signature": "def merge1(self, intervals)"
},
{
"docstring": "Using last interval comparison method. :param intervals: :return:",
"name": "merge",
"signature": "def merge(self, intervals)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020102 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge(self, intervals): Using last interval comparison method. :param intervals: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def merge1(self, intervals): :type intervals: List[Interval] :rtype: List[Interval]
- def merge(self, intervals): Using last interval comparison method. :param intervals: :return... | 11d6bf2ba7b50c07e048df37c4e05c8f46b92241 | <|skeleton|>
class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
<|body_0|>
def merge(self, intervals):
"""Using last interval comparison method. :param intervals: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def merge1(self, intervals):
""":type intervals: List[Interval] :rtype: List[Interval]"""
res = []
if not intervals or len(intervals) == 0:
return res
intervals.sort(key=lambda x: x.start)
low, hi = (intervals[0].start, intervals[0].end)
fo... | the_stack_v2_python_sparse | LeetCodes/facebook/MergeIntervals.py | chutianwen/LeetCodes | train | 0 | |
85e097bf77eb7059717f5b98b090a6f8797cb239 | [
"if not data.get('email'):\n raise ValueError('{\"detail\":\"' + str(_('The mail field can not be empty')) + '\"}')\ntry:\n user = accounts_models.User.objects.get(email=data.get('email'))\nexcept accounts_models.User.DoesNotExist:\n raise ValueError('{\"detail\":\"' + str(_('The mail is not registered in ... | <|body_start_0|>
if not data.get('email'):
raise ValueError('{"detail":"' + str(_('The mail field can not be empty')) + '"}')
try:
user = accounts_models.User.objects.get(email=data.get('email'))
except accounts_models.User.DoesNotExist:
raise ValueError('{"de... | this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request. | RecoverPasswordService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method ve... | stack_v2_sparse_classes_36k_train_019137 | 42,606 | no_license | [
{
"docstring": "this method verifies that the email sent by the user exists in the database, raise a exception if the email does not exist :param data: user's email :type data: dict :return: Model User :raises: ValueError",
"name": "check_email",
"signature": "def check_email(self, data: dict) -> accoun... | 2 | stack_v2_sparse_classes_30k_train_008911 | Implement the Python class `RecoverPasswordService` described below.
Class description:
this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request.
Method signatures and docstrings:
- def check_email(... | Implement the Python class `RecoverPasswordService` described below.
Class description:
this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request.
Method signatures and docstrings:
- def check_email(... | 497b8724d6e02582f28bc9c5a19f93ec21db84d8 | <|skeleton|>
class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method ve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecoverPasswordService:
"""this class controls the validation of the mail at the moment in which the user makes a request to change the password, as well as the code that sends the results of the request."""
def check_email(self, data: dict) -> accounts_models.User:
"""this method verifies that t... | the_stack_v2_python_sparse | accounts/services.py | carlos-o/weedmatchheroku | train | 0 |
14467e6d6b664084df4056c9b1d2deb793d84373 | [
"if len(nums) < 4:\n return False\ns, r = divmod(sum(nums), 4)\nif r != 0:\n return False\n\n@lru_cache(None)\ndef use_to_make(used, n):\n if n == 0:\n yield from [used]\n if used == (1 << len(nums) + 1) - 1:\n yield from []\n for i in range(len(nums)):\n if used & 1 << i:\n ... | <|body_start_0|>
if len(nums) < 4:
return False
s, r = divmod(sum(nums), 4)
if r != 0:
return False
@lru_cache(None)
def use_to_make(used, n):
if n == 0:
yield from [used]
if used == (1 << len(nums) + 1) - 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def makesquare(self, nums: List[int]) -> bool:
"""05/10/2020 08:32"""
<|body_0|>
def makesquare(self, matchsticks: List[int]) -> bool:
"""Bruteforce. Iterate all possible cases. Time limit exceeded. Time complexity: O(n*4^n) Space complexity: O(1)"""
... | stack_v2_sparse_classes_36k_train_019138 | 5,584 | no_license | [
{
"docstring": "05/10/2020 08:32",
"name": "makesquare",
"signature": "def makesquare(self, nums: List[int]) -> bool"
},
{
"docstring": "Bruteforce. Iterate all possible cases. Time limit exceeded. Time complexity: O(n*4^n) Space complexity: O(1)",
"name": "makesquare",
"signature": "def... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makesquare(self, nums: List[int]) -> bool: 05/10/2020 08:32
- def makesquare(self, matchsticks: List[int]) -> bool: Bruteforce. Iterate all possible cases. Time limit exceede... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def makesquare(self, nums: List[int]) -> bool: 05/10/2020 08:32
- def makesquare(self, matchsticks: List[int]) -> bool: Bruteforce. Iterate all possible cases. Time limit exceede... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def makesquare(self, nums: List[int]) -> bool:
"""05/10/2020 08:32"""
<|body_0|>
def makesquare(self, matchsticks: List[int]) -> bool:
"""Bruteforce. Iterate all possible cases. Time limit exceeded. Time complexity: O(n*4^n) Space complexity: O(1)"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def makesquare(self, nums: List[int]) -> bool:
"""05/10/2020 08:32"""
if len(nums) < 4:
return False
s, r = divmod(sum(nums), 4)
if r != 0:
return False
@lru_cache(None)
def use_to_make(used, n):
if n == 0:
... | the_stack_v2_python_sparse | leetcode/solved/473_Matchsticks_to_Square/solution.py | sungminoh/algorithms | train | 0 | |
16cc7584e376ca79edc9f9970a09cfb46c4fe1ec | [
"request = context['request']\nfrom reviewboard.urls import diffviewer_url_names\nmatch = request.resolver_match\nif match.url_name in diffviewer_url_names:\n return 'raw/'\nreturn local_site_reverse('raw-diff', request, kwargs={'review_request_id': context['review_request'].display_id})",
"from reviewboard.ur... | <|body_start_0|>
request = context['request']
from reviewboard.urls import diffviewer_url_names
match = request.resolver_match
if match.url_name in diffviewer_url_names:
return 'raw/'
return local_site_reverse('raw-diff', request, kwargs={'review_request_id': context[... | The action to download a diff. Version Added: 6.0 | DownloadDiffAction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DownloadDiffAction:
"""The action to download a diff. Version Added: 6.0"""
def get_url(self, *, context: Context) -> str:
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: str: The URL to invoke if thi... | stack_v2_sparse_classes_36k_train_019139 | 36,416 | permissive | [
{
"docstring": "Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: str: The URL to invoke if this action is clicked.",
"name": "get_url",
"signature": "def get_url(self, *, context: Context) -> str"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_008758 | Implement the Python class `DownloadDiffAction` described below.
Class description:
The action to download a diff. Version Added: 6.0
Method signatures and docstrings:
- def get_url(self, *, context: Context) -> str: Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs ... | Implement the Python class `DownloadDiffAction` described below.
Class description:
The action to download a diff. Version Added: 6.0
Method signatures and docstrings:
- def get_url(self, *, context: Context) -> str: Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs ... | c3a991f1e9d7682239a1ab0e8661cee6da01d537 | <|skeleton|>
class DownloadDiffAction:
"""The action to download a diff. Version Added: 6.0"""
def get_url(self, *, context: Context) -> str:
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: str: The URL to invoke if thi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DownloadDiffAction:
"""The action to download a diff. Version Added: 6.0"""
def get_url(self, *, context: Context) -> str:
"""Return this action's URL. Args: context (django.template.Context): The collection of key-value pairs from the template. Returns: str: The URL to invoke if this action is c... | the_stack_v2_python_sparse | reviewboard/reviews/actions.py | reviewboard/reviewboard | train | 1,141 |
5a4cfa9c0d80f42dec3f864be95d26f08165ca8c | [
"self.__predict_season = predict_season\nself.__train_seasons = train_seasons\nself.__pca_components = pca_components\nself.__unlikely_z_score = unlikely_z_score\nself.__random_generator = random_generator",
"raw_train_data = WikipediaParser.parse(self.__train_seasons)\ntrain_output = np.array([1.0 if get_is_mol(... | <|body_start_0|>
self.__predict_season = predict_season
self.__train_seasons = train_seasons
self.__pca_components = pca_components
self.__unlikely_z_score = unlikely_z_score
self.__random_generator = random_generator
<|end_body_0|>
<|body_start_1|>
raw_train_data = Wiki... | The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm. | WikipediaExtractor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WikipediaExtractor:
"""The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm."""
def __init__(self, predict_season: int, train_seasons: Set[int], pca_components: int, unlikely_z_score: float, random_generator: Ran... | stack_v2_sparse_classes_36k_train_019140 | 5,120 | no_license | [
{
"docstring": "Constructor of the Wikipedia Extractor. Arguments: predict_season (int): The season for which we make the prediction. train_seasons (Set[int]): The seasons which are used as train data. pca_components (int): The number of PCA components extracted from the job features before LDA is applied. unli... | 5 | stack_v2_sparse_classes_30k_train_006642 | Implement the Python class `WikipediaExtractor` described below.
Class description:
The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm.
Method signatures and docstrings:
- def __init__(self, predict_season: int, train_seasons: Set[int],... | Implement the Python class `WikipediaExtractor` described below.
Class description:
The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm.
Method signatures and docstrings:
- def __init__(self, predict_season: int, train_seasons: Set[int],... | 1676543d484dfde038a7130e44e480aa227b2db4 | <|skeleton|>
class WikipediaExtractor:
"""The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm."""
def __init__(self, predict_season: int, train_seasons: Set[int], pca_components: int, unlikely_z_score: float, random_generator: Ran... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WikipediaExtractor:
"""The Wikipedia Extractor transforms an array of features in a new array of features which can be used by the classification algorithm."""
def __init__(self, predict_season: int, train_seasons: Set[int], pca_components: int, unlikely_z_score: float, random_generator: RandomState):
... | the_stack_v2_python_sparse | moldel/Layers/Wikipedia/WikipediaExtractor.py | Multifacio/Moldel | train | 41 |
3f214bf7e19242bdc070d885246f61f3d9edfc95 | [
"result = []\nnums.sort()\n\ndef backtrack(tmpList, idx):\n newList = [item for item in tmpList]\n result.add(newList)\n for i in range(idx, len(nums)):\n tmpList.append(nums[i])\n backtrack(tmpList, i + 1)\n _ = tmpList.pop()\nbacktrack([], 0)\nreturn result",
"result = [[]]\nfor it... | <|body_start_0|>
result = []
nums.sort()
def backtrack(tmpList, idx):
newList = [item for item in tmpList]
result.add(newList)
for i in range(idx, len(nums)):
tmpList.append(nums[i])
backtrack(tmpList, i + 1)
_ ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def solve2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = []
nums.sort(... | stack_v2_sparse_classes_36k_train_019141 | 1,225 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "subsets",
"signature": "def subsets(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "solve2",
"signature": "def solve2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015701 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def solve2(self, nums): :type nums: List[int] :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subsets(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def solve2(self, nums): :type nums: List[int] :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | a5cb862f0c5a3cfd21468141800568c2dedded0a | <|skeleton|>
class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def solve2(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subsets(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
result = []
nums.sort()
def backtrack(tmpList, idx):
newList = [item for item in tmpList]
result.add(newList)
for i in range(idx, len(nums)):
... | the_stack_v2_python_sparse | python/leetcode/combinatorial/subsets/78_subsets.py | Levintsky/topcoder | train | 0 | |
4b653de11fba1d6aa8bfc0f0e14ea998358939b0 | [
"super(DecodeImage, self).__init__()\nself.to_rgb = to_rgb\nself.with_mixup = with_mixup\nif not isinstance(self.to_rgb, bool):\n raise TypeError('{}: input type is invalid.'.format(self))\nif not isinstance(self.with_mixup, bool):\n raise TypeError('{}: input type is invalid.'.format(self))",
"if 'image' n... | <|body_start_0|>
super(DecodeImage, self).__init__()
self.to_rgb = to_rgb
self.with_mixup = with_mixup
if not isinstance(self.to_rgb, bool):
raise TypeError('{}: input type is invalid.'.format(self))
if not isinstance(self.with_mixup, bool):
raise TypeErro... | DecodeImage | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
<|body_0|>
def __call__(self, sample, con... | stack_v2_sparse_classes_36k_train_019142 | 19,057 | permissive | [
{
"docstring": "Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score",
"name": "__init__",
"signature": "def __init__(self, to_rgb=True, with_mixup=False)"
},
{
"docstring": "load image... | 2 | stack_v2_sparse_classes_30k_train_009226 | Implement the Python class `DecodeImage` described below.
Class description:
Implement the DecodeImage class.
Method signatures and docstrings:
- def __init__(self, to_rgb=True, with_mixup=False): Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether o... | Implement the Python class `DecodeImage` described below.
Class description:
Implement the DecodeImage class.
Method signatures and docstrings:
- def __init__(self, to_rgb=True, with_mixup=False): Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether o... | b8ec015fa9e16c0a879c619ee1f2aab8a393c7bd | <|skeleton|>
class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
<|body_0|>
def __call__(self, sample, con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecodeImage:
def __init__(self, to_rgb=True, with_mixup=False):
"""Transform the image data to numpy format. Args: to_rgb (bool): whether to convert BGR to RGB with_mixup (bool): whether or not to mixup image and gt_bbbox/gt_score"""
super(DecodeImage, self).__init__()
self.to_rgb = to... | the_stack_v2_python_sparse | CV/PaddleReid/reid/data/transform/operators.py | sserdoubleh/Research | train | 10 | |
ed41bfc5515008d62eee2b4e11ec55f39c8710c4 | [
"query = request.GET.get('q')\nsort = request.GET.get('sort', 'name')\nasearch = Platform.objects.filter(id=kwargs['id']).first()\nform = PlatformForm(instance=asearch)\nlist_platform = None\nif query:\n list_platform = Platform.objects.filter(Q(name_platform__icontains=query))\nelse:\n list_platform = Platfo... | <|body_start_0|>
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Platform.objects.filter(id=kwargs['id']).first()
form = PlatformForm(instance=asearch)
list_platform = None
if query:
list_platform = Platform.objects.filter(Q(name_... | Clase para editar las plataformas | PlatformEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = reque... | stack_v2_sparse_classes_36k_train_019143 | 22,221 | no_license | [
{
"docstring": "Método get",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Método post",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009202 | Implement the Python class `PlatformEditView` described below.
Class description:
Clase para editar las plataformas
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post | Implement the Python class `PlatformEditView` described below.
Class description:
Clase para editar las plataformas
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Método get
- def post(self, request, *args, **kwargs): Método post
<|skeleton|>
class PlatformEditView:
"""Clase para ed... | e28e2d968372609ad396c42fb572a00c2410a117 | <|skeleton|>
class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Método post"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlatformEditView:
"""Clase para editar las plataformas"""
def get(self, request, *args, **kwargs):
"""Método get"""
query = request.GET.get('q')
sort = request.GET.get('sort', 'name')
asearch = Platform.objects.filter(id=kwargs['id']).first()
form = PlatformForm(in... | the_stack_v2_python_sparse | list/views.py | damaos/server_list2 | train | 0 |
e968bf3a354ff05f91e04b1d0d7c51c2976b6db7 | [
"len1 = len(text1)\nlen2 = len(text2)\n\ndef lcs(idx1, idx2):\n \"\"\"\n :type word1: str\n :type word2: str\n :rtype: int\n \"\"\"\n if idx1 == len1 or idx2 == len2:\n return 0\n if memo.get((idx1, idx2)) > -1:\n return memo[idx1, idx2]\n answer... | <|body_start_0|>
len1 = len(text1)
len2 = len(text2)
def lcs(idx1, idx2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if idx1 == len1 or idx2 == len2:
return 0
... | Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python online submissions for Longest Common Subsequence. | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python online submissions for Longest Common Su... | stack_v2_sparse_classes_36k_train_019144 | 4,961 | no_license | [
{
"docstring": ":type text1: str :type text2: str :rtype: int",
"name": "longestCommonSubsequence",
"signature": "def longestCommonSubsequence(self, text1, text2)"
},
{
"docstring": ":type text1: str :type text2: str :rtype: int",
"name": "longestCommonSubsequence",
"signature": "def lon... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python o... | Implement the Python class `Solution` described below.
Class description:
Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python o... | 844f502da4d6fb9cd69cf0a1ef71da3385a4d2b4 | <|skeleton|>
class Solution:
"""Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python online submissions for Longest Common Su... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Recursive top-down attempt (dict to memoize) Stats: O(len(text1) * len(text2)) aka O(n * m) time Runtime: 2436 ms, faster than 5.16% of Python online submissions for Longest Common Subsequence. Memory Usage: 151.2 MB, less than 5.04% of Python online submissions for Longest Common Subsequence."""... | the_stack_v2_python_sparse | 1143-longest_common_subsequence.py | stevestar888/leetcode-problems | train | 2 |
72a28a93f91f49f5b7c07f3dbf1cad8712dcae91 | [
"if not root:\n return []\nqueue, ret = ([(0, root)], [])\nwhile queue:\n level, node = queue.pop(0)\n if len(ret) == level:\n ret.append([])\n ret[level].append(node.val)\n if node.left:\n queue.append((level + 1, node.left))\n if node.right:\n queue.append((level + 1, node.r... | <|body_start_0|>
if not root:
return []
queue, ret = ([(0, root)], [])
while queue:
level, node = queue.pop(0)
if len(ret) == level:
ret.append([])
ret[level].append(node.val)
if node.left:
queue.append((... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root: TreeNode) -> list:
"""BFS 最后得到结果翻转一下即可"""
<|body_0|>
def levelOrderBottom_2(self, root: TreeNode) -> list:
"""DFS 最后得到结果翻转一下即可"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return... | stack_v2_sparse_classes_36k_train_019145 | 1,838 | no_license | [
{
"docstring": "BFS 最后得到结果翻转一下即可",
"name": "levelOrderBottom",
"signature": "def levelOrderBottom(self, root: TreeNode) -> list"
},
{
"docstring": "DFS 最后得到结果翻转一下即可",
"name": "levelOrderBottom_2",
"signature": "def levelOrderBottom_2(self, root: TreeNode) -> list"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root: TreeNode) -> list: BFS 最后得到结果翻转一下即可
- def levelOrderBottom_2(self, root: TreeNode) -> list: DFS 最后得到结果翻转一下即可 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrderBottom(self, root: TreeNode) -> list: BFS 最后得到结果翻转一下即可
- def levelOrderBottom_2(self, root: TreeNode) -> list: DFS 最后得到结果翻转一下即可
<|skeleton|>
class Solution:
d... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def levelOrderBottom(self, root: TreeNode) -> list:
"""BFS 最后得到结果翻转一下即可"""
<|body_0|>
def levelOrderBottom_2(self, root: TreeNode) -> list:
"""DFS 最后得到结果翻转一下即可"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def levelOrderBottom(self, root: TreeNode) -> list:
"""BFS 最后得到结果翻转一下即可"""
if not root:
return []
queue, ret = ([(0, root)], [])
while queue:
level, node = queue.pop(0)
if len(ret) == level:
ret.append([])
... | the_stack_v2_python_sparse | algorithm/leetcode/tree/09-二叉树的层次遍历Ⅱ.py | lxconfig/UbuntuCode_bak | train | 0 | |
12065ceb3e8daf3da8681c631420ad0995470215 | [
"self.ssh_client = paramiko.SSHClient()\nself.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nself.ssh_client.connect(config.get_ddve_host(), username=config.get_ddve_username(), password=config.get_ddve_password())\nself.ddve = DDVEClient(self.ssh_client)",
"lines = self.ddve.checkSystemStatus(... | <|body_start_0|>
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh_client.connect(config.get_ddve_host(), username=config.get_ddve_username(), password=config.get_ddve_password())
self.ddve = DDVEClient(self.ssh_client)
... | Maintains the subsystems required for the operations in ddve. | DDVEManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DDVEManager:
"""Maintains the subsystems required for the operations in ddve."""
def __init__(self):
"""Initializes the subsystems required for the operations in ddve."""
<|body_0|>
def clear_results(self):
"""Reset the stats in ddve system. :return: None."""
... | stack_v2_sparse_classes_36k_train_019146 | 2,898 | no_license | [
{
"docstring": "Initializes the subsystems required for the operations in ddve.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Reset the stats in ddve system. :return: None.",
"name": "clear_results",
"signature": "def clear_results(self)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_018899 | Implement the Python class `DDVEManager` described below.
Class description:
Maintains the subsystems required for the operations in ddve.
Method signatures and docstrings:
- def __init__(self): Initializes the subsystems required for the operations in ddve.
- def clear_results(self): Reset the stats in ddve system. ... | Implement the Python class `DDVEManager` described below.
Class description:
Maintains the subsystems required for the operations in ddve.
Method signatures and docstrings:
- def __init__(self): Initializes the subsystems required for the operations in ddve.
- def clear_results(self): Reset the stats in ddve system. ... | d8ee7c1608cad88f7c64410de49a07bf7b621be0 | <|skeleton|>
class DDVEManager:
"""Maintains the subsystems required for the operations in ddve."""
def __init__(self):
"""Initializes the subsystems required for the operations in ddve."""
<|body_0|>
def clear_results(self):
"""Reset the stats in ddve system. :return: None."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DDVEManager:
"""Maintains the subsystems required for the operations in ddve."""
def __init__(self):
"""Initializes the subsystems required for the operations in ddve."""
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
... | the_stack_v2_python_sparse | readop/managers/ddve.py | wma8/SeniorDesign | train | 0 |
22d6dcb228cee966c56580f5b83c4fdbfee308c6 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"decW = tf.expand_dims(s_prev, 1)\ndecW = self.W(decW)\nencU = self.U(hidden_states)\noutV = self.V(tf.nn.tanh(decW + encU))\nweights = tf.nn.softmax(outV, axis... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
decW = tf.expand_dims(s_prev, 1)
decW = self.W(decW)
encU = self.U... | Self Attention Class | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ... | stack_v2_sparse_classes_36k_train_019147 | 1,669 | no_license | [
{
"docstring": "Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ro the encoder hidden states :V - Dense layer units=1 applied to the tanh of the sum... | 2 | null | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention Class
Method signatures and docstrings:
- def __init__(self, units): Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decode... | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention Class
Method signatures and docstrings:
- def __init__(self, units): Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decode... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ro the encode... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | DracoMindz/holbertonschool-machine_learning | train | 2 |
c5e075de3267a6d2978643f4c3bd52778b4433d2 | [
"values = []\n\ndef preorder(root):\n if root is None:\n return\n values.append(root.val)\n preorder(root.left)\n preorder(root.right)\npreorder(root)\nreturn ' '.join(map(str, values))",
"values = collections.deque((int(val) for val in data.split()))\n\ndef build(min_value, max_value):\n if... | <|body_start_0|>
values = []
def preorder(root):
if root is None:
return
values.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return ' '.join(map(str, values))
<|end_body_0|>
<|body_start_1|>
... | 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_019148 | 2,125 | 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:... | 5f98270fbcd2d28d0f2abd344c3348255a12882a | <|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"""
values = []
def preorder(root):
if root is None:
return
values.append(root.val)
preorder(root.left)
preorder(root... | the_stack_v2_python_sparse | 449. Serialize and Deserialize BST.py | lxyshuai/leetcode | train | 0 | |
8de5b5d134d65355fad80f1e19a6cee4e78b4c6a | [
"super().__init__()\nself.n1 = n1\nself.n2 = n2",
"total = 0\nfor i in range(self.n1, self.n2):\n total += i\nwith ThreadSum.lock:\n ThreadSum.total += total"
] | <|body_start_0|>
super().__init__()
self.n1 = n1
self.n2 = n2
<|end_body_0|>
<|body_start_1|>
total = 0
for i in range(self.n1, self.n2):
total += i
with ThreadSum.lock:
ThreadSum.total += total
<|end_body_1|>
| ThreadSum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreadSum:
def __init__(self, n1, n2):
"""Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param n2: int"""
<|body_0|>
def run(self):
"""Overrides run to add iterate over al... | stack_v2_sparse_classes_36k_train_019149 | 2,706 | no_license | [
{
"docstring": "Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param n2: int",
"name": "__init__",
"signature": "def __init__(self, n1, n2)"
},
{
"docstring": "Overrides run to add iterate over all nu... | 2 | null | Implement the Python class `ThreadSum` described below.
Class description:
Implement the ThreadSum class.
Method signatures and docstrings:
- def __init__(self, n1, n2): Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param... | Implement the Python class `ThreadSum` described below.
Class description:
Implement the ThreadSum class.
Method signatures and docstrings:
- def __init__(self, n1, n2): Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param... | 113cee20f8ac8c94b7cd7ffa2bb6e2c0b1478412 | <|skeleton|>
class ThreadSum:
def __init__(self, n1, n2):
"""Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param n2: int"""
<|body_0|>
def run(self):
"""Overrides run to add iterate over al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreadSum:
def __init__(self, n1, n2):
"""Used to calculate the sum of all numbers between n1 and n2 Results are later saved in: - number - thread_count - result - time :param n1: int :param n2: int"""
super().__init__()
self.n1 = n1
self.n2 = n2
def run(self):
"""... | the_stack_v2_python_sparse | 03-threadsync/threadsum.py | mreichl-tgm/sew-4 | train | 0 | |
b3c17aa65ed5963b1062d85cf8ab008b4b87d077 | [
"super(TransformerEncoder, self).__init__()\nself.layers = nn.ModuleList([TransformerSeq2SeqEncoderLayer(d_model=d_model, n_head=n_head, dim_ff=dim_ff, dropout=dropout) for _ in range(num_layers)])\nself.norm = nn.LayerNorm(d_model, eps=1e-06)",
"output = x\nif seq_mask is None:\n seq_mask = x.new_ones(x.size(... | <|body_start_0|>
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList([TransformerSeq2SeqEncoderLayer(d_model=d_model, n_head=n_head, dim_ff=dim_ff, dropout=dropout) for _ in range(num_layers)])
self.norm = nn.LayerNorm(d_model, eps=1e-06)
<|end_body_0|>
<|body_start_1|>
... | transformer的encoder模块,不包含embedding层 | TransformerEncoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerEncoder:
"""transformer的encoder模块,不包含embedding层"""
def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
""":param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param int n_head: 多少个head :param int dim_ff: FFN中间hidden大小 :par... | stack_v2_sparse_classes_36k_train_019150 | 1,498 | permissive | [
{
"docstring": ":param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param int n_head: 多少个head :param int dim_ff: FFN中间hidden大小 :param float dropout: 多大概率drop attention和ffn中间的表示",
"name": "__init__",
"signature": "def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, d... | 2 | null | Implement the Python class `TransformerEncoder` described below.
Class description:
transformer的encoder模块,不包含embedding层
Method signatures and docstrings:
- def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, dropout=0.1): :param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param ... | Implement the Python class `TransformerEncoder` described below.
Class description:
transformer的encoder模块,不包含embedding层
Method signatures and docstrings:
- def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, dropout=0.1): :param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param ... | 148ad1dcb7aa4990ac30d9a62ae8b89b6e706f8c | <|skeleton|>
class TransformerEncoder:
"""transformer的encoder模块,不包含embedding层"""
def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
""":param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param int n_head: 多少个head :param int dim_ff: FFN中间hidden大小 :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerEncoder:
"""transformer的encoder模块,不包含embedding层"""
def __init__(self, num_layers, d_model=512, n_head=8, dim_ff=2048, dropout=0.1):
""":param int num_layers: 多少层Transformer :param int d_model: input和output的大小 :param int n_head: 多少个head :param int dim_ff: FFN中间hidden大小 :param float drop... | the_stack_v2_python_sparse | fastNLP/modules/encoder/transformer.py | irfan11111111/fastNLP | train | 1 |
31be946072912b60be0a97e44e5fcf713a0fcfe5 | [
"self.input_shape = input_shape\nself.output_size = output_size\nself.warmup_epochs = warmup_epochs\nself.regular_epochs = regular_epochs\nself.batch_size = batch_size\nself.checkpoint_path = checkpoint_path\nself.data_util = DataUtil(path_to_train=path_to_train, path_to_test=path_to_test)\nself.image_size = image_... | <|body_start_0|>
self.input_shape = input_shape
self.output_size = output_size
self.warmup_epochs = warmup_epochs
self.regular_epochs = regular_epochs
self.batch_size = batch_size
self.checkpoint_path = checkpoint_path
self.data_util = DataUtil(path_to_train=path_... | Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested | CustomInceptionModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
... | stack_v2_sparse_classes_36k_train_019151 | 7,922 | no_license | [
{
"docstring": "Constructor for the custom InceptionV3 model :param input_shape: input shape for the model :param output_size: output size of the model, number of output classes :param warmup_epochs: number of training epochs used to train only additional layers added :param regular_epochs: number of training e... | 5 | stack_v2_sparse_classes_30k_train_020523 | Implement the Python class `CustomInceptionModel` described below.
Class description:
Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested
Method signatures and docstrings:
- def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_si... | Implement the Python class `CustomInceptionModel` described below.
Class description:
Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested
Method signatures and docstrings:
- def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_si... | a6716e3c393177b188d8ecc4b8351ea2a8ddb08a | <|skeleton|>
class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomInceptionModel:
"""Main class for the InceptionV3 model, having all function that is needed for the model to be trained and tested"""
def __init__(self, input_shape, output_size, warmup_epochs, regular_epochs, batch_size, checkpoint_path, path_to_train, path_to_test, image_size):
"""Constru... | the_stack_v2_python_sparse | inceptionnet/inception_nn_model.py | reinai/ProteinSubcellularLocalization | train | 0 |
6b3b7eed1a30982e3a59498fdb51a54af20a669d | [
"if n == 0:\n return []\ntotal_l = []\ntotal_l.append([None])\ntotal_l.append(['()'])\nfor i in range(2, n + 1):\n l = []\n for j in range(i):\n now_list1 = total_l[j]\n now_list2 = total_l[i - 1 - j]\n print(now_list1, now_list2)\n for k1 in now_list1:\n for k2 in no... | <|body_start_0|>
if n == 0:
return []
total_l = []
total_l.append([None])
total_l.append(['()'])
for i in range(2, n + 1):
l = []
for j in range(i):
now_list1 = total_l[j]
now_list2 = total_l[i - 1 - j]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def _gen(self, left, right, n, result):
"""left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
... | stack_v2_sparse_classes_36k_train_019152 | 3,718 | no_license | [
{
"docstring": ":type n: int :rtype: List[str]",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n)"
},
{
"docstring": "left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列",
"name": "_gen",
"signature": "def _gen(self, left, right, n, result)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016299 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def _gen(self, left, right, n, result): left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n): :type n: int :rtype: List[str]
- def _gen(self, left, right, n, result): left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列
<|skeleton|>
cl... | a32c096e192a89a88457ccc1899be10352bf1edd | <|skeleton|>
class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
<|body_0|>
def _gen(self, left, right, n, result):
"""left: 左括号用了多少个 right:右括号用了多少个 n: 括号对数 result:当前产生的括号序列"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def generateParenthesis(self, n):
""":type n: int :rtype: List[str]"""
if n == 0:
return []
total_l = []
total_l.append([None])
total_l.append(['()'])
for i in range(2, n + 1):
l = []
for j in range(i):
... | the_stack_v2_python_sparse | leetcode/022.括号生成.py | luhao2013/Algorithms | train | 0 | |
bb0a0edc82b3387f1d7c7aac57e8e127f676dc9e | [
"super(FullyConnected, self).__init__()\nlayers = []\nfor i, item in enumerate(list_nodes):\n if i == 0:\n continue\n if isinstance(item, int):\n layers.append(tensorflow.keras.layers.Dense(units=item, kernel_initializer=initializer_w, bias_initializer='zeros'))\n elif callable(item):\n ... | <|body_start_0|>
super(FullyConnected, self).__init__()
layers = []
for i, item in enumerate(list_nodes):
if i == 0:
continue
if isinstance(item, int):
layers.append(tensorflow.keras.layers.Dense(units=item, kernel_initializer=initializer_w... | Neural network class. | FullyConnected | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyConnected:
"""Neural network class."""
def __init__(self):
"""Initialize the layers of the NN."""
<|body_0|>
def call(self, x):
"""Propagate x through the network."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(FullyConnected, self).... | stack_v2_sparse_classes_36k_train_019153 | 6,175 | permissive | [
{
"docstring": "Initialize the layers of the NN.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Propagate x through the network.",
"name": "call",
"signature": "def call(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001217 | Implement the Python class `FullyConnected` described below.
Class description:
Neural network class.
Method signatures and docstrings:
- def __init__(self): Initialize the layers of the NN.
- def call(self, x): Propagate x through the network. | Implement the Python class `FullyConnected` described below.
Class description:
Neural network class.
Method signatures and docstrings:
- def __init__(self): Initialize the layers of the NN.
- def call(self, x): Propagate x through the network.
<|skeleton|>
class FullyConnected:
"""Neural network class."""
... | bc75fc8ad1a98125c73bdc24a4d934b2f930c249 | <|skeleton|>
class FullyConnected:
"""Neural network class."""
def __init__(self):
"""Initialize the layers of the NN."""
<|body_0|>
def call(self, x):
"""Propagate x through the network."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FullyConnected:
"""Neural network class."""
def __init__(self):
"""Initialize the layers of the NN."""
super(FullyConnected, self).__init__()
layers = []
for i, item in enumerate(list_nodes):
if i == 0:
continue
if isinstance(item, i... | the_stack_v2_python_sparse | fairlearn/adversarial/_tensorflow_engine.py | fairlearn/fairlearn | train | 1,551 |
72de027ad380186edcd59b98e76f4f1eb3effbe9 | [
"self.action_n = env.action_space.n\nself.obs_low = env.observation_space.low\nself.obs_scale = env.observation_space.high - env.observation_space.low\nself.encoder = GridCoder(dim_size_arr, self.obs_low, self.obs_scale)\nself.w = np.zeros((self.encoder.state_num, self.action_n))\nself.c = np.zeros_like(self.w)\nse... | <|body_start_0|>
self.action_n = env.action_space.n
self.obs_low = env.observation_space.low
self.obs_scale = env.observation_space.high - env.observation_space.low
self.encoder = GridCoder(dim_size_arr, self.obs_low, self.obs_scale)
self.w = np.zeros((self.encoder.state_num, sel... | 网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据 | SARSAAgent_grid | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SARSAAgent_grid:
"""网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据"""
def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001):
"""学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率"""
<|body_0|>
def decide... | stack_v2_sparse_classes_36k_train_019154 | 22,277 | no_license | [
{
"docstring": "学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率",
"name": "__init__",
"signature": "def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001)"
},
{
"docstring": "决策函数 observation 状态观测值 (位置 速度 时间)",
"name"... | 3 | stack_v2_sparse_classes_30k_train_000979 | Implement the Python class `SARSAAgent_grid` described below.
Class description:
网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据
Method signatures and docstrings:
- def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001): 学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习... | Implement the Python class `SARSAAgent_grid` described below.
Class description:
网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据
Method signatures and docstrings:
- def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001): 学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习... | e6526e9e38fcb5be91b46cb40715c15242198a0b | <|skeleton|>
class SARSAAgent_grid:
"""网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据"""
def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001):
"""学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率"""
<|body_0|>
def decide... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SARSAAgent_grid:
"""网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据"""
def __init__(self, env, dim_size_arr=[50, 50], gamma=1.0, learning_rate=0.03, epsilon=0.001):
"""学习函数 env 环境 dim_size_arr 各个维度上的网格数量 gamma 收益衰减速率 learning_rate 学习速率 epsilon 执行探索策略概率"""
self.action_n = env.action_space.n
... | the_stack_v2_python_sparse | mountain_car/function_approx.py | lwzswufe/gym_learning | train | 0 |
20dd0bc859c17a8325bf80a746cd9baf1a80bdd4 | [
"if not nums:\n return None\nmax_idx = 0\nmax = nums[0]\nfor idx, i in enumerate(nums):\n if i > max:\n max = i\n max_idx = idx\nroot = TreeNode(max)\nroot.left = self.constructMaximumBinaryTree(nums[0:max_idx])\nroot.right = self.constructMaximumBinaryTree(nums[max_idx + 1:])\nreturn root",
"... | <|body_start_0|>
if not nums:
return None
max_idx = 0
max = nums[0]
for idx, i in enumerate(nums):
if i > max:
max = i
max_idx = idx
root = TreeNode(max)
root.left = self.constructMaximumBinaryTree(nums[0:max_idx])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
"""Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)"""
<|body_0|>
def constructMaximumBinaryTree2(self, nums: List[int]) -> TreeNode:
"""Time complexity : O(n)"""
<|b... | stack_v2_sparse_classes_36k_train_019155 | 1,152 | no_license | [
{
"docstring": "Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)",
"name": "constructMaximumBinaryTree",
"signature": "def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode"
},
{
"docstring": "Time complexity : O(n)",
"name": "constructMaximumBinaryTree2",
"si... | 2 | stack_v2_sparse_classes_30k_train_012367 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)
- def constructMaximumBinaryTree2(self, nums: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)
- def constructMaximumBinaryTree2(self, nums: ... | d99eb75a74e38c91effda81cfc7341679422f005 | <|skeleton|>
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
"""Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)"""
<|body_0|>
def constructMaximumBinaryTree2(self, nums: List[int]) -> TreeNode:
"""Time complexity : O(n)"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
"""Time complexity : O(n^2). 一般情况下 O(nlogn) Space complexity : O(n)"""
if not nums:
return None
max_idx = 0
max = nums[0]
for idx, i in enumerate(nums):
if i > max:
... | the_stack_v2_python_sparse | Python/Maximum_Binary_Tree.py | mt3925/leetcode | train | 0 | |
3f7101cf9b3c58ed40f59fe85cf9c05554881cdc | [
"self.line = line\nself.column = column\nself.source = source",
"if not self.line or not self.column:\n return 'EmptyMetadata'\nreturn str(self.line) + ':' + str(self.column)"
] | <|body_start_0|>
self.line = line
self.column = column
self.source = source
<|end_body_0|>
<|body_start_1|>
if not self.line or not self.column:
return 'EmptyMetadata'
return str(self.line) + ':' + str(self.column)
<|end_body_1|>
| A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whose metadata this is. Attributes: line (int) : The line number of the metadata. c... | NodeMetadata | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeMetadata:
"""A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whose metadata this is. Attributes: line (i... | stack_v2_sparse_classes_36k_train_019156 | 5,942 | no_license | [
{
"docstring": "Set position.",
"name": "__init__",
"signature": "def __init__(self, line: int=None, column: int=None, source: str='')"
},
{
"docstring": "Return the string representation of the metadata.",
"name": "__repr__",
"signature": "def __repr__(self) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_013026 | Implement the Python class `NodeMetadata` described below.
Class description:
A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whos... | Implement the Python class `NodeMetadata` described below.
Class description:
A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whos... | 001ad94aad755c11df7cf6ef8f7f0f828a5ac90e | <|skeleton|>
class NodeMetadata:
"""A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whose metadata this is. Attributes: line (i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeMetadata:
"""A NodeMetadata class, representing info on the source code. Args: line (int) : The line number of the metadata being initialised. column (int) : The column number of the metadata being initialised. source (str) : The source code of node whose metadata this is. Attributes: line (int) : The lin... | the_stack_v2_python_sparse | typt/node.py | BPHarris/typt | train | 0 |
e2063b4154f217d2ff5041f56af8865f22ccaa65 | [
"challenges: List[Dict[str, Any]] = []\nchallenges = TurboChallenges.Table(self, challenges)\nUtility.WriteFile(self, f'{self.eXAssets}/turboChallenges.json', challenges)\nlog.info(f'Compiled {len(challenges):,} Tomogunchi Turbo Challenges')",
"table: List[Dict[str, Any]] = Utility.ReadCSV(self, f'{self.iXAssets}... | <|body_start_0|>
challenges: List[Dict[str, Any]] = []
challenges = TurboChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXAssets}/turboChallenges.json', challenges)
log.info(f'Compiled {len(challenges):,} Tomogunchi Turbo Challenges')
<|end_body_0|>
<|body_start_1|>
... | Tomogunchi Turbo Challenges XAssets. | TurboChallenges | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TurboChallenges:
"""Tomogunchi Turbo Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Tomogunchi Turbo Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the mp/petwatc... | stack_v2_sparse_classes_36k_train_019157 | 13,794 | permissive | [
{
"docstring": "Compile the Tomogunchi Turbo Challenges XAssets.",
"name": "Compile",
"signature": "def Compile(self: Any) -> None"
},
{
"docstring": "Compile the mp/petwatchturbotable.csv XAsset.",
"name": "Table",
"signature": "def Table(self: Any, challenges: List[Dict[str, Any]]) -> ... | 2 | stack_v2_sparse_classes_30k_train_002135 | Implement the Python class `TurboChallenges` described below.
Class description:
Tomogunchi Turbo Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Tomogunchi Turbo Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: C... | Implement the Python class `TurboChallenges` described below.
Class description:
Tomogunchi Turbo Challenges XAssets.
Method signatures and docstrings:
- def Compile(self: Any) -> None: Compile the Tomogunchi Turbo Challenges XAssets.
- def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]: C... | 82d3198a64eb2905e96dd536ce2f0acb52f9ce77 | <|skeleton|>
class TurboChallenges:
"""Tomogunchi Turbo Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Tomogunchi Turbo Challenges XAssets."""
<|body_0|>
def Table(self: Any, challenges: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Compile the mp/petwatc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TurboChallenges:
"""Tomogunchi Turbo Challenges XAssets."""
def Compile(self: Any) -> None:
"""Compile the Tomogunchi Turbo Challenges XAssets."""
challenges: List[Dict[str, Any]] = []
challenges = TurboChallenges.Table(self, challenges)
Utility.WriteFile(self, f'{self.eXA... | the_stack_v2_python_sparse | ModernWarfare/XAssets/challenges.py | dbuentello/Hyde | train | 0 |
980de806b394bb46849606d7e27fdf360354e87e | [
"super().setUpTestData()\ncompanies = [Company(name=f'Company {idx}', description='Some company') for idx in range(3)]\nCompany.objects.bulk_create(companies)\ncontacts = []\nfor cmp in Company.objects.all():\n contacts += [Contact(company=cmp, name=f'My name {idx}') for idx in range(3)]\nContact.objects.bulk_cr... | <|body_start_0|>
super().setUpTestData()
companies = [Company(name=f'Company {idx}', description='Some company') for idx in range(3)]
Company.objects.bulk_create(companies)
contacts = []
for cmp in Company.objects.all():
contacts += [Contact(company=cmp, name=f'My nam... | Tests for the Contact models | ContactTest | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactTest:
"""Tests for the Contact models"""
def setUpTestData(cls):
"""Perform init for this test class"""
<|body_0|>
def test_list(self):
"""Test company list API endpoint"""
<|body_1|>
def test_create(self):
"""Test that we can create a... | stack_v2_sparse_classes_36k_train_019158 | 19,439 | permissive | [
{
"docstring": "Perform init for this test class",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Test company list API endpoint",
"name": "test_list",
"signature": "def test_list(self)"
},
{
"docstring": "Test that we can create a new Contact o... | 5 | stack_v2_sparse_classes_30k_train_007060 | Implement the Python class `ContactTest` described below.
Class description:
Tests for the Contact models
Method signatures and docstrings:
- def setUpTestData(cls): Perform init for this test class
- def test_list(self): Test company list API endpoint
- def test_create(self): Test that we can create a new Contact ob... | Implement the Python class `ContactTest` described below.
Class description:
Tests for the Contact models
Method signatures and docstrings:
- def setUpTestData(cls): Perform init for this test class
- def test_list(self): Test company list API endpoint
- def test_create(self): Test that we can create a new Contact ob... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class ContactTest:
"""Tests for the Contact models"""
def setUpTestData(cls):
"""Perform init for this test class"""
<|body_0|>
def test_list(self):
"""Test company list API endpoint"""
<|body_1|>
def test_create(self):
"""Test that we can create a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactTest:
"""Tests for the Contact models"""
def setUpTestData(cls):
"""Perform init for this test class"""
super().setUpTestData()
companies = [Company(name=f'Company {idx}', description='Some company') for idx in range(3)]
Company.objects.bulk_create(companies)
... | the_stack_v2_python_sparse | InvenTree/company/test_api.py | inventree/InvenTree | train | 3,077 |
9d6980b1e79a659a7ec7e4029d485eb5ee8f5a38 | [
"self.filterLineEdit = filterLineEdit\nself.filterableListWidget = filterableListWidget\nif multiSelection:\n self.filterableListWidget.setSelectionMode(QAbstractItemView.MultiSelection)\nself.filterLineEdit.textEdited.connect(self.on_filterLineEdit_textEdited)",
"matchFilterList = self.filterableListWidget.fi... | <|body_start_0|>
self.filterLineEdit = filterLineEdit
self.filterableListWidget = filterableListWidget
if multiSelection:
self.filterableListWidget.setSelectionMode(QAbstractItemView.MultiSelection)
self.filterLineEdit.textEdited.connect(self.on_filterLineEdit_textEdited)
<|e... | This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state). | FilterableWidget | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterableWidget:
"""This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state)."""
def __init__(self, filterLineEdit, filterableListWidget, multiSelection=Fals... | stack_v2_sparse_classes_36k_train_019159 | 2,403 | no_license | [
{
"docstring": "Initialize the FilterableWidget with `filterLineEdit` (`QtGui.QLineEdit`) as source for the filter, `filterableListWidget` (`QtGui.QListWidget`) as the widget to filter items. If `multiSelection` is True, set the selection mode of `filterableListWidget` to `QAbstractItemView.MultiSelection`.",
... | 2 | null | Implement the Python class `FilterableWidget` described below.
Class description:
This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state).
Method signatures and docstrings:
- def __in... | Implement the Python class `FilterableWidget` described below.
Class description:
This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state).
Method signatures and docstrings:
- def __in... | f404ddc941836c87fd3f889f80ee5fe065887a3f | <|skeleton|>
class FilterableWidget:
"""This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state)."""
def __init__(self, filterLineEdit, filterableListWidget, multiSelection=Fals... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilterableWidget:
"""This class manages the filtering of a QListWidget. When the user enters text in the provided QLineEdit, QListWidget entries not matching this text are hidden (but keep their selection state)."""
def __init__(self, filterLineEdit, filterableListWidget, multiSelection=False):
"... | the_stack_v2_python_sparse | obslight/ObsLightGui/FilterableWidget.py | ronan22/obs-light | train | 0 |
e3876a5cd38e7fac9a759dccb6292b624bba5118 | [
"extra_options = kwargs.pop('extra', 0)\nsuper(AddMcqForm, self).__init__(*args, **kwargs)\nself.fields['total_options'].initial = extra_options\nfor index in range(int(extra_options)):\n self.fields['option_{index}'.format(index=index)] = forms.CharField()",
"question = self.cleaned_data['question']\nif quest... | <|body_start_0|>
extra_options = kwargs.pop('extra', 0)
super(AddMcqForm, self).__init__(*args, **kwargs)
self.fields['total_options'].initial = extra_options
for index in range(int(extra_options)):
self.fields['option_{index}'.format(index=index)] = forms.CharField()
<|end_b... | Add Question forms | AddMcqForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddMcqForm:
"""Add Question forms"""
def __init__(self, *args, **kwargs):
"""Validation"""
<|body_0|>
def clean_question(self):
"""validation"""
<|body_1|>
def clean_total_options(self):
"""validation"""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_019160 | 8,285 | no_license | [
{
"docstring": "Validation",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "validation",
"name": "clean_question",
"signature": "def clean_question(self)"
},
{
"docstring": "validation",
"name": "clean_total_options",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_002073 | Implement the Python class `AddMcqForm` described below.
Class description:
Add Question forms
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Validation
- def clean_question(self): validation
- def clean_total_options(self): validation | Implement the Python class `AddMcqForm` described below.
Class description:
Add Question forms
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Validation
- def clean_question(self): validation
- def clean_total_options(self): validation
<|skeleton|>
class AddMcqForm:
"""Add Question form... | 65d9aa549a0d76f58cb89cac5da4a3085a2efd97 | <|skeleton|>
class AddMcqForm:
"""Add Question forms"""
def __init__(self, *args, **kwargs):
"""Validation"""
<|body_0|>
def clean_question(self):
"""validation"""
<|body_1|>
def clean_total_options(self):
"""validation"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddMcqForm:
"""Add Question forms"""
def __init__(self, *args, **kwargs):
"""Validation"""
extra_options = kwargs.pop('extra', 0)
super(AddMcqForm, self).__init__(*args, **kwargs)
self.fields['total_options'].initial = extra_options
for index in range(int(extra_opt... | the_stack_v2_python_sparse | nitortest/forms.py | ManishSinghFartyal/InternalGit | train | 0 |
c5723fe650d16ea99f6fbcfcd76cfadc7ae756aa | [
"slot_indices = assignable_indices(slot, n_req_slot)\nif slot_indices:\n return random.choice(slot_indices)\nelse:\n return None",
"slot_indices = assignable_indices(slot, n_req_slot)\nif slot_indices:\n return slot_indices[0]\nelse:\n return None",
"if mode == 'path':\n ent = path_based_entropy(... | <|body_start_0|>
slot_indices = assignable_indices(slot, n_req_slot)
if slot_indices:
return random.choice(slot_indices)
else:
return None
<|end_body_0|>
<|body_start_1|>
slot_indices = assignable_indices(slot, n_req_slot)
if slot_indices:
ret... | Spectrum Assignment Class | SpectrumAssignment | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpectrumAssignment:
"""Spectrum Assignment Class"""
def random(slot: bitarray, n_req_slot: int) -> int:
"""Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of required slots. Returns: int: index"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_019161 | 2,129 | no_license | [
{
"docstring": "Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of required slots. Returns: int: index",
"name": "random",
"signature": "def random(slot: bitarray, n_req_slot: int) -> int"
},
{
"docstring": "First-fit algorithm sear... | 3 | null | Implement the Python class `SpectrumAssignment` described below.
Class description:
Spectrum Assignment Class
Method signatures and docstrings:
- def random(slot: bitarray, n_req_slot: int) -> int: Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of requi... | Implement the Python class `SpectrumAssignment` described below.
Class description:
Spectrum Assignment Class
Method signatures and docstrings:
- def random(slot: bitarray, n_req_slot: int) -> int: Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of requi... | 4b82c519742fa47b1537204780174cdb0c2f4ae0 | <|skeleton|>
class SpectrumAssignment:
"""Spectrum Assignment Class"""
def random(slot: bitarray, n_req_slot: int) -> int:
"""Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of required slots. Returns: int: index"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpectrumAssignment:
"""Spectrum Assignment Class"""
def random(slot: bitarray, n_req_slot: int) -> int:
"""Random algorithm searches assignable indices Args: slot (bitarray): slot bitarray. n_req_slot (int): the number of required slots. Returns: int: index"""
slot_indices = assignable_in... | the_stack_v2_python_sparse | rsarl/algorithms/sa.py | Krasjet-Yu/rsa-rl | train | 0 |
a459aaa5f210c6c375af119962c81f02506212c4 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.androidManagedAppProtection'.casefold():\n ... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | Policy used to configure detailed management settings targeted to specific security groups | TargetedManagedAppProtection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TargetedManagedAppProtection:
"""Policy used to configure detailed management settings targeted to specific security groups"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppProtection:
"""Creates a new instance of the appropriate class... | stack_v2_sparse_classes_36k_train_019162 | 4,121 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: TargetedManagedAppProtection",
"name": "create_from_discriminator_value",
"signature": "def create_from_disc... | 3 | stack_v2_sparse_classes_30k_train_018455 | Implement the Python class `TargetedManagedAppProtection` described below.
Class description:
Policy used to configure detailed management settings targeted to specific security groups
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppPr... | Implement the Python class `TargetedManagedAppProtection` described below.
Class description:
Policy used to configure detailed management settings targeted to specific security groups
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppPr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TargetedManagedAppProtection:
"""Policy used to configure detailed management settings targeted to specific security groups"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppProtection:
"""Creates a new instance of the appropriate class... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TargetedManagedAppProtection:
"""Policy used to configure detailed management settings targeted to specific security groups"""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TargetedManagedAppProtection:
"""Creates a new instance of the appropriate class based on dis... | the_stack_v2_python_sparse | msgraph/generated/models/targeted_managed_app_protection.py | microsoftgraph/msgraph-sdk-python | train | 135 |
06f176236317003a788e97a3c12681d66656ed60 | [
"if self.action == 'list':\n return BaseInterviewSerializer\nelse:\n return InterviewSerializer",
"current_user = self.request.user\nparams = self.kwargs\ncompany = get_object_or_404(Company, pk=params['company_pk'])\nqueryset = Interview.objects.filter(Q(candidate=current_user) | Q(interviewees__in=[curren... | <|body_start_0|>
if self.action == 'list':
return BaseInterviewSerializer
else:
return InterviewSerializer
<|end_body_0|>
<|body_start_1|>
current_user = self.request.user
params = self.kwargs
company = get_object_or_404(Company, pk=params['company_pk'])
... | View class for Interviews. | InterviewViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InterviewViewSet:
"""View class for Interviews."""
def get_serializer_class(self):
"""Get serializer class base on action."""
<|body_0|>
def get_queryset(self):
"""Return interviews where current user is participated."""
<|body_1|>
def create(self, r... | stack_v2_sparse_classes_36k_train_019163 | 3,897 | no_license | [
{
"docstring": "Get serializer class base on action.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Return interviews where current user is participated.",
"name": "get_queryset",
"signature": "def get_queryset(self)"
},
{
"docs... | 4 | stack_v2_sparse_classes_30k_train_000739 | Implement the Python class `InterviewViewSet` described below.
Class description:
View class for Interviews.
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer class base on action.
- def get_queryset(self): Return interviews where current user is participated.
- def create(self, reque... | Implement the Python class `InterviewViewSet` described below.
Class description:
View class for Interviews.
Method signatures and docstrings:
- def get_serializer_class(self): Get serializer class base on action.
- def get_queryset(self): Return interviews where current user is participated.
- def create(self, reque... | 252b0ebd77eefbcc945a0efc3068cc3421f46d5f | <|skeleton|>
class InterviewViewSet:
"""View class for Interviews."""
def get_serializer_class(self):
"""Get serializer class base on action."""
<|body_0|>
def get_queryset(self):
"""Return interviews where current user is participated."""
<|body_1|>
def create(self, r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InterviewViewSet:
"""View class for Interviews."""
def get_serializer_class(self):
"""Get serializer class base on action."""
if self.action == 'list':
return BaseInterviewSerializer
else:
return InterviewSerializer
def get_queryset(self):
"""R... | the_stack_v2_python_sparse | app/interviews/views.py | vsokoltsov/Interview360Server | train | 2 |
5b504a632dcca32b1e6a9ba504ed1454c62e56e4 | [
"obj1 = objectify.fromstring(expected)\nexpected = etree.tostring(obj1)\nobj2 = objectify.fromstring(actual)\nactual = etree.tostring(obj2)\nunittest.TestCase().assertEqual(expected, actual)",
"expected = expected.encode('utf-8')\nactual = actual.encode('utf-8')\nparser = etree.XMLParser(encoding='utf-8')\nobj1 =... | <|body_start_0|>
obj1 = objectify.fromstring(expected)
expected = etree.tostring(obj1)
obj2 = objectify.fromstring(actual)
actual = etree.tostring(obj2)
unittest.TestCase().assertEqual(expected, actual)
<|end_body_0|>
<|body_start_1|>
expected = expected.encode('utf-8')
... | XmlUtilities | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
<|body_0|>
def assert_xml_equal_utf_8(expected, actual):
"""This method ensures the two strings... | stack_v2_sparse_classes_36k_train_019164 | 1,227 | permissive | [
{
"docstring": "Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:",
"name": "assert_xml_equal",
"signature": "def assert_xml_equal(expected, actual)"
},
{
"docstring": "This method ensures the two strings are both in utf encoding for ... | 2 | stack_v2_sparse_classes_30k_train_008849 | Implement the Python class `XmlUtilities` described below.
Class description:
Implement the XmlUtilities class.
Method signatures and docstrings:
- def assert_xml_equal(expected, actual): Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:
- def assert_xml_e... | Implement the Python class `XmlUtilities` described below.
Class description:
Implement the XmlUtilities class.
Method signatures and docstrings:
- def assert_xml_equal(expected, actual): Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:
- def assert_xml_e... | 8420d9d4b800223bff6a648015679684f5aba38c | <|skeleton|>
class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
<|body_0|>
def assert_xml_equal_utf_8(expected, actual):
"""This method ensures the two strings... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XmlUtilities:
def assert_xml_equal(expected, actual):
"""Given two strings of xml this method normalises them and asserts they are equal :param expected: :param actual:"""
obj1 = objectify.fromstring(expected)
expected = etree.tostring(obj1)
obj2 = objectify.fromstring(actual)
... | the_stack_v2_python_sparse | common/utilities/xml_utilities.py | nhsconnect/integration-adaptors | train | 15 | |
162d0fdc1f6466634341acc039c5baca02ec03f3 | [
"if isinstance(size, int):\n self.size = size\nelif isinstance(size, collections.abc.Iterable) and len(size) == 3:\n if type(size) == list:\n size = tuple(size)\n self.size = size\nelse:\n raise ValueError('Unknown inputs for size: {}'.format(size))\nself.order = order\nsuper().__init__()",
"im... | <|body_start_0|>
if isinstance(size, int):
self.size = size
elif isinstance(size, collections.abc.Iterable) and len(size) == 3:
if type(size) == list:
size = tuple(size)
self.size = size
else:
raise ValueError('Unknown inputs for si... | Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order | Resize3D | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resize3D:
"""Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order"""
def __init__(self, size, order=1):
"""resize"""
<|body_0|>
def __call__(self, img, label=None):
"""Args: img (numpy ndarray): Image to be scaled. lab... | stack_v2_sparse_classes_36k_train_019165 | 34,927 | permissive | [
{
"docstring": "resize",
"name": "__init__",
"signature": "def __init__(self, size, order=1)"
},
{
"docstring": "Args: img (numpy ndarray): Image to be scaled. label (numpy ndarray) : Label to be scaled Returns: numpy ndarray: Rescaled image. numpy ndarray: Rescaled label.",
"name": "__call_... | 2 | stack_v2_sparse_classes_30k_train_008950 | Implement the Python class `Resize3D` described below.
Class description:
Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order
Method signatures and docstrings:
- def __init__(self, size, order=1): resize
- def __call__(self, img, label=None): Args: img (numpy ndarray): Im... | Implement the Python class `Resize3D` described below.
Class description:
Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order
Method signatures and docstrings:
- def __init__(self, size, order=1): resize
- def __call__(self, img, label=None): Args: img (numpy ndarray): Im... | 2c8c35a8949fef74599f5ec557d340a14415f20d | <|skeleton|>
class Resize3D:
"""Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order"""
def __init__(self, size, order=1):
"""resize"""
<|body_0|>
def __call__(self, img, label=None):
"""Args: img (numpy ndarray): Image to be scaled. lab... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resize3D:
"""Resize the input numpy ndarray to the given size. Args: size order (int, optional): Desired order"""
def __init__(self, size, order=1):
"""resize"""
if isinstance(size, int):
self.size = size
elif isinstance(size, collections.abc.Iterable) and len(size) ==... | the_stack_v2_python_sparse | contrib/MedicalSeg/medicalseg/transforms/transform.py | PaddlePaddle/PaddleSeg | train | 8,531 |
da05afb86cc0bfbb42716aadfce37f6dd4fec943 | [
"self.harris_save_file_last_letter = ord('b')\nself.matching_save_file_last_letter = ord('b')\nself.RANSAC_matching_save_file_last_letter = ord('b')\nself.image_stitch_save_file_last_letter = ord('b')",
"harris_save_file_name_1 = '1' + chr(self.harris_save_file_last_letter) + '.png'\nself.harris_save_file_last_le... | <|body_start_0|>
self.harris_save_file_last_letter = ord('b')
self.matching_save_file_last_letter = ord('b')
self.RANSAC_matching_save_file_last_letter = ord('b')
self.image_stitch_save_file_last_letter = ord('b')
<|end_body_0|>
<|body_start_1|>
harris_save_file_name_1 = '1' + c... | this class manages the file names for all saving files | fname_manager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class fname_manager:
"""this class manages the file names for all saving files"""
def __init__(self):
"""constructor"""
<|body_0|>
def get_2_harris_output_filenames(self):
""":return: return 2 file names for harris corner output"""
<|body_1|>
def get_match... | stack_v2_sparse_classes_36k_train_019166 | 1,961 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ":return: return 2 file names for harris corner output",
"name": "get_2_harris_output_filenames",
"signature": "def get_2_harris_output_filenames(self)"
},
{
"docstring": ":retur... | 5 | stack_v2_sparse_classes_30k_train_018266 | Implement the Python class `fname_manager` described below.
Class description:
this class manages the file names for all saving files
Method signatures and docstrings:
- def __init__(self): constructor
- def get_2_harris_output_filenames(self): :return: return 2 file names for harris corner output
- def get_matching_... | Implement the Python class `fname_manager` described below.
Class description:
this class manages the file names for all saving files
Method signatures and docstrings:
- def __init__(self): constructor
- def get_2_harris_output_filenames(self): :return: return 2 file names for harris corner output
- def get_matching_... | a0b687e4c3b793edd48f22102a5a4affa32c5193 | <|skeleton|>
class fname_manager:
"""this class manages the file names for all saving files"""
def __init__(self):
"""constructor"""
<|body_0|>
def get_2_harris_output_filenames(self):
""":return: return 2 file names for harris corner output"""
<|body_1|>
def get_match... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class fname_manager:
"""this class manages the file names for all saving files"""
def __init__(self):
"""constructor"""
self.harris_save_file_last_letter = ord('b')
self.matching_save_file_last_letter = ord('b')
self.RANSAC_matching_save_file_last_letter = ord('b')
self.... | the_stack_v2_python_sparse | project/src/filename_manager.py | Yixuan-Lee/COMP6341-winter-2020 | train | 1 |
6529ae34c6e4f4b4a668b827257e32a3d0b0f5d9 | [
"from reduction.histCompat.Fit1DFunction import Fit1DFunction\nfit = Fit1DFunction(functor, minimizer=self.minimizer, plotter=self.plotter)\nreturn fit(histogram, boxConstraints)",
"self.minimizer = minimizer\nself.plotter = plotter\nreturn"
] | <|body_start_0|>
from reduction.histCompat.Fit1DFunction import Fit1DFunction
fit = Fit1DFunction(functor, minimizer=self.minimizer, plotter=self.plotter)
return fit(histogram, boxConstraints)
<|end_body_0|>
<|body_start_1|>
self.minimizer = minimizer
self.plotter = plotter
... | 1D function fitter use DE algorithm | DifferentialEvolution1DFunctionFitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DifferentialEvolution1DFunctionFitter:
"""1D function fitter use DE algorithm"""
def __call__(self, histogram, functor, boxConstraints):
"""__call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x) data curve functor: the function to fit, for example de... | stack_v2_sparse_classes_36k_train_019167 | 1,798 | no_license | [
{
"docstring": "__call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x) data curve functor: the function to fit, for example def f(x, a, b, c): return a * exp( - ((x-b)/c)**2 ) boxConstraints: constraints of parameters defined as a box",
"name": "__call__",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_018998 | Implement the Python class `DifferentialEvolution1DFunctionFitter` described below.
Class description:
1D function fitter use DE algorithm
Method signatures and docstrings:
- def __call__(self, histogram, functor, boxConstraints): __call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x... | Implement the Python class `DifferentialEvolution1DFunctionFitter` described below.
Class description:
1D function fitter use DE algorithm
Method signatures and docstrings:
- def __call__(self, histogram, functor, boxConstraints): __call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x... | 7ba4ce07a5a4645942192b4b81f7afcae505db90 | <|skeleton|>
class DifferentialEvolution1DFunctionFitter:
"""1D function fitter use DE algorithm"""
def __call__(self, histogram, functor, boxConstraints):
"""__call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x) data curve functor: the function to fit, for example de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DifferentialEvolution1DFunctionFitter:
"""1D function fitter use DE algorithm"""
def __call__(self, histogram, functor, boxConstraints):
"""__call__( histogram, functor, boxConstraints ): fit histogram to functor histogram: y(x) data curve functor: the function to fit, for example def f(x, a, b, ... | the_stack_v2_python_sparse | histogrammode/reduction/core/DifferentialEvolution1DFunctionFitter.py | danse-inelastic/DrChops | train | 0 |
c26126fa97cad9221caabf8de6d185d2fa76ebe0 | [
"self.rootWin = Tk()\nself.rootWin.title('First Canvas example')\nself.canvas = Canvas(self.rootWin, bg='yellow', width=500, height=500, bd=0)\nself.canvas.grid(row=1, column=1)\nself.canvas.config(scrollregion=self.canvas.bbox(ALL))\nself.ballList = []\nnextBall = self.canvas.create_oval(20, 40, 40, 60, fill='red'... | <|body_start_0|>
self.rootWin = Tk()
self.rootWin.title('First Canvas example')
self.canvas = Canvas(self.rootWin, bg='yellow', width=500, height=500, bd=0)
self.canvas.grid(row=1, column=1)
self.canvas.config(scrollregion=self.canvas.bbox(ALL))
self.ballList = []
... | Creates a canvas and draws three balls on it. It then moves the balls dynamically | CanvasGUI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanvasGUI:
"""Creates a canvas and draws three balls on it. It then moves the balls dynamically"""
def __init__(self):
"""Create the canvas widget and the objects to place in it"""
<|body_0|>
def go(self):
"""Takes no inputs, and runs its own loop for the GUI. Th... | stack_v2_sparse_classes_36k_train_019168 | 2,813 | no_license | [
{
"docstring": "Create the canvas widget and the objects to place in it",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Takes no inputs, and runs its own loop for the GUI. This is so we can move the balls without waiting for some user input.",
"name": "go",
"si... | 3 | stack_v2_sparse_classes_30k_train_014917 | Implement the Python class `CanvasGUI` described below.
Class description:
Creates a canvas and draws three balls on it. It then moves the balls dynamically
Method signatures and docstrings:
- def __init__(self): Create the canvas widget and the objects to place in it
- def go(self): Takes no inputs, and runs its own... | Implement the Python class `CanvasGUI` described below.
Class description:
Creates a canvas and draws three balls on it. It then moves the balls dynamically
Method signatures and docstrings:
- def __init__(self): Create the canvas widget and the objects to place in it
- def go(self): Takes no inputs, and runs its own... | 02d761c9636176aa1fe986d29f1f2b36818b0ab0 | <|skeleton|>
class CanvasGUI:
"""Creates a canvas and draws three balls on it. It then moves the balls dynamically"""
def __init__(self):
"""Create the canvas widget and the objects to place in it"""
<|body_0|>
def go(self):
"""Takes no inputs, and runs its own loop for the GUI. Th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanvasGUI:
"""Creates a canvas and draws three balls on it. It then moves the balls dynamically"""
def __init__(self):
"""Create the canvas widget and the objects to place in it"""
self.rootWin = Tk()
self.rootWin.title('First Canvas example')
self.canvas = Canvas(self.roo... | the_stack_v2_python_sparse | PycharmProjects/scratch/whatever.py | grahamrichard/COMP-123-fall-16 | train | 0 |
0892b008407ff1075405284fe0c9cbf9562e9757 | [
"if len(self.datasets) == 1:\n return next(iter(self.datasets.values()))\nelse:\n raise ValueError(f'Expected a single dataset, found {len(self.datasets)}')",
"if len(self.models) == 1:\n return next(iter(self.models.values()))\nelse:\n raise ValueError(f'Expected a single model, found {len(self.model... | <|body_start_0|>
if len(self.datasets) == 1:
return next(iter(self.datasets.values()))
else:
raise ValueError(f'Expected a single dataset, found {len(self.datasets)}')
<|end_body_0|>
<|body_start_1|>
if len(self.models) == 1:
return next(iter(self.models.valu... | Container to record the state of each step of the optimization process. | Record | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Record:
"""Container to record the state of each step of the optimization process."""
def dataset(self) -> Dataset:
"""The dataset when there is just one dataset."""
<|body_0|>
def model(self) -> TrainableProbabilisticModel:
"""The model when there is just one da... | stack_v2_sparse_classes_36k_train_019169 | 46,356 | permissive | [
{
"docstring": "The dataset when there is just one dataset.",
"name": "dataset",
"signature": "def dataset(self) -> Dataset"
},
{
"docstring": "The model when there is just one dataset.",
"name": "model",
"signature": "def model(self) -> TrainableProbabilisticModel"
},
{
"docstri... | 3 | null | Implement the Python class `Record` described below.
Class description:
Container to record the state of each step of the optimization process.
Method signatures and docstrings:
- def dataset(self) -> Dataset: The dataset when there is just one dataset.
- def model(self) -> TrainableProbabilisticModel: The model when... | Implement the Python class `Record` described below.
Class description:
Container to record the state of each step of the optimization process.
Method signatures and docstrings:
- def dataset(self) -> Dataset: The dataset when there is just one dataset.
- def model(self) -> TrainableProbabilisticModel: The model when... | 56101c092f28ed87398c4cd63fdece2f16909451 | <|skeleton|>
class Record:
"""Container to record the state of each step of the optimization process."""
def dataset(self) -> Dataset:
"""The dataset when there is just one dataset."""
<|body_0|>
def model(self) -> TrainableProbabilisticModel:
"""The model when there is just one da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Record:
"""Container to record the state of each step of the optimization process."""
def dataset(self) -> Dataset:
"""The dataset when there is just one dataset."""
if len(self.datasets) == 1:
return next(iter(self.datasets.values()))
else:
raise ValueErro... | the_stack_v2_python_sparse | trieste/bayesian_optimizer.py | secondmind-labs/trieste | train | 190 |
1785389d5818d508743bd63d5053077ab499dba3 | [
"super(TransformerSeqClassificationModel, self).__init__()\nself.padding_idx = padding_idx\nself.embedder = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)\nself.layer_norm = nn.LayerNorm(normalized_shape=emb_dim, epsilon=epsilon)\nself.dropout = nn.Dropout(p=dropout_rate)\nself.transformer_encoder = Tra... | <|body_start_0|>
super(TransformerSeqClassificationModel, self).__init__()
self.padding_idx = padding_idx
self.embedder = nn.Embedding(vocab_size, emb_dim, padding_idx=padding_idx)
self.layer_norm = nn.LayerNorm(normalized_shape=emb_dim, epsilon=epsilon)
self.dropout = nn.Dropout... | Transformer model for seq classification task | TransformerSeqClassificationModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransformerSeqClassificationModel:
"""Transformer model for seq classification task"""
def __init__(self, vocab_size, num_class, emb_dim=512, hidden_size=512, head_num=4, layer_num=4, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""Init model Args: vocab_size (int): vocab size. n... | stack_v2_sparse_classes_36k_train_019170 | 10,112 | permissive | [
{
"docstring": "Init model Args: vocab_size (int): vocab size. num_class (int): num classes. emb_dim (int, optional): embeding dimension. Defaults to 512. hidden_size (int, optional): hidden size. Defaults to 512. head_num (int, optional): head_num. Defaults to 4. layer_num (int, optional): layer num. Defaults ... | 4 | stack_v2_sparse_classes_30k_val_000292 | Implement the Python class `TransformerSeqClassificationModel` described below.
Class description:
Transformer model for seq classification task
Method signatures and docstrings:
- def __init__(self, vocab_size, num_class, emb_dim=512, hidden_size=512, head_num=4, layer_num=4, padding_idx=0, epsilon=1e-05, dropout_ra... | Implement the Python class `TransformerSeqClassificationModel` described below.
Class description:
Transformer model for seq classification task
Method signatures and docstrings:
- def __init__(self, vocab_size, num_class, emb_dim=512, hidden_size=512, head_num=4, layer_num=4, padding_idx=0, epsilon=1e-05, dropout_ra... | 1c84ea6d51625d2d66b3eef1d9a7cc9a87c99e0e | <|skeleton|>
class TransformerSeqClassificationModel:
"""Transformer model for seq classification task"""
def __init__(self, vocab_size, num_class, emb_dim=512, hidden_size=512, head_num=4, layer_num=4, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""Init model Args: vocab_size (int): vocab size. n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransformerSeqClassificationModel:
"""Transformer model for seq classification task"""
def __init__(self, vocab_size, num_class, emb_dim=512, hidden_size=512, head_num=4, layer_num=4, padding_idx=0, epsilon=1e-05, dropout_rate=0.1):
"""Init model Args: vocab_size (int): vocab size. num_class (int... | the_stack_v2_python_sparse | apps/pretrained_protein/tape_dynamic/protein_sequence_model_dynamic.py | RuikangSun/PaddleHelix | train | 0 |
e6d24767d4558091ea1840e522e53448065babce | [
"self.cncHost = UTIL.SYS.s_configuration.CNC_HOST\nself.connected = False\nself.cncPort = UTIL.SYS.s_configuration.CNC_SERVER_PORT\nself.connected2 = False\nself.cncPort2 = UTIL.SYS.s_configuration.CNC_SERVER_PORT2",
"LOG_INFO('EGSE interface server configuration', 'CNC')\nLOG('CNC host = ' + self.cncHost, 'CNC')... | <|body_start_0|>
self.cncHost = UTIL.SYS.s_configuration.CNC_HOST
self.connected = False
self.cncPort = UTIL.SYS.s_configuration.CNC_SERVER_PORT
self.connected2 = False
self.cncPort2 = UTIL.SYS.s_configuration.CNC_SERVER_PORT2
<|end_body_0|>
<|body_start_1|>
LOG_INFO('EG... | CNC Client Configuration (on CCS side) | CNCclientConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNCclientConfiguration:
"""CNC Client Configuration (on CCS side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the server configuration attributes"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_019171 | 5,792 | permissive | [
{
"docstring": "Initialise the connection relevant informations",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dumps the status of the server configuration attributes",
"name": "dump",
"signature": "def dump(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003689 | Implement the Python class `CNCclientConfiguration` described below.
Class description:
CNC Client Configuration (on CCS side)
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the server configuration attributes | Implement the Python class `CNCclientConfiguration` described below.
Class description:
CNC Client Configuration (on CCS side)
Method signatures and docstrings:
- def __init__(self): Initialise the connection relevant informations
- def dump(self): Dumps the status of the server configuration attributes
<|skeleton|>... | c94415e9d85519f345fc56938198ac2537c0c6d0 | <|skeleton|>
class CNCclientConfiguration:
"""CNC Client Configuration (on CCS side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
<|body_0|>
def dump(self):
"""Dumps the status of the server configuration attributes"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNCclientConfiguration:
"""CNC Client Configuration (on CCS side)"""
def __init__(self):
"""Initialise the connection relevant informations"""
self.cncHost = UTIL.SYS.s_configuration.CNC_HOST
self.connected = False
self.cncPort = UTIL.SYS.s_configuration.CNC_SERVER_PORT
... | the_stack_v2_python_sparse | EGSE/IF.py | khawatkom/SpacePyLibrary | train | 1 |
abc86ccbc829fc2b532808fa8a960687b71edc95 | [
"self.size = size\nself.arr = []\nself.cap = 0\nself.total = 0",
"if self.cap < self.size:\n self.arr.append(val)\n self.total += val\n self.cap += 1\n return self.total / float(self.cap)\nelse:\n x = self.arr.pop(0)\n self.arr.append(val)\n self.total = self.total - x + val\n return self.... | <|body_start_0|>
self.size = size
self.arr = []
self.cap = 0
self.total = 0
<|end_body_0|>
<|body_start_1|>
if self.cap < self.size:
self.arr.append(val)
self.total += val
self.cap += 1
return self.total / float(self.cap)
e... | 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.arr = [... | stack_v2_sparse_classes_36k_train_019172 | 851 | 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:
... | 20623defecf65cbc35b194d8b60d8b211816ee4f | <|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.arr = []
self.cap = 0
self.total = 0
def next(self, val):
""":type val: int :rtype: float"""
if self.cap < self.size:
... | the_stack_v2_python_sparse | in_Python/0346 Moving Average from Data Stream.py | YangLiyli131/Leetcode2020 | train | 0 | |
1c84273a119cb53f83c6811b624b69c15f2c244f | [
"category_Q = Q()\nif category:\n category_Q = Q(category=category)\nname_Q = Q()\nif name:\n name_Q = Q(name__contains=name)\nstart = page * self.page_size\nend = start + self.page_size\nreturn Clothing.objects.filter(category_Q, name_Q).filter(is_active=True)[start:end]",
"category = request.REQUEST.get('... | <|body_start_0|>
category_Q = Q()
if category:
category_Q = Q(category=category)
name_Q = Q()
if name:
name_Q = Q(name__contains=name)
start = page * self.page_size
end = start + self.page_size
return Clothing.objects.filter(category_Q, nam... | Search clothing | ClothingSearchView | [
"Unlicense"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClothingSearchView:
"""Search clothing"""
def search(self, category, name, page):
"""Search clothings"""
<|body_0|>
def get_ajax(self, request, *args, **kwargs):
"""Do ajax search"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
category_Q = Q()
... | stack_v2_sparse_classes_36k_train_019173 | 4,207 | permissive | [
{
"docstring": "Search clothings",
"name": "search",
"signature": "def search(self, category, name, page)"
},
{
"docstring": "Do ajax search",
"name": "get_ajax",
"signature": "def get_ajax(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005720 | Implement the Python class `ClothingSearchView` described below.
Class description:
Search clothing
Method signatures and docstrings:
- def search(self, category, name, page): Search clothings
- def get_ajax(self, request, *args, **kwargs): Do ajax search | Implement the Python class `ClothingSearchView` described below.
Class description:
Search clothing
Method signatures and docstrings:
- def search(self, category, name, page): Search clothings
- def get_ajax(self, request, *args, **kwargs): Do ajax search
<|skeleton|>
class ClothingSearchView:
"""Search clothing... | 0ea016745d92054bd4df8d934c1b67fd61b6f845 | <|skeleton|>
class ClothingSearchView:
"""Search clothing"""
def search(self, category, name, page):
"""Search clothings"""
<|body_0|>
def get_ajax(self, request, *args, **kwargs):
"""Do ajax search"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClothingSearchView:
"""Search clothing"""
def search(self, category, name, page):
"""Search clothings"""
category_Q = Q()
if category:
category_Q = Q(category=category)
name_Q = Q()
if name:
name_Q = Q(name__contains=name)
start = pa... | the_stack_v2_python_sparse | clothings/views.py | ygrass/handsome | train | 0 |
04a34c84740a8a5decb59b20f51a85a769e0bd71 | [
"self.root = root\nself.a = Label(self.root, text='Altura: ')\nself.a.grid(row=0, sticky=E)\nself.l = Label(self.root, text='Largura: ')\nself.l.grid(row=1, sticky=E)\nself.e1 = Entry(self.root)\nself.e2 = Entry(self.root)\nself.e1.grid(row=0, column=1)\nself.e2.grid(row=1, column=1)\nself.p = Checkbutton(self.root... | <|body_start_0|>
self.root = root
self.a = Label(self.root, text='Altura: ')
self.a.grid(row=0, sticky=E)
self.l = Label(self.root, text='Largura: ')
self.l.grid(row=1, sticky=E)
self.e1 = Entry(self.root)
self.e2 = Entry(self.root)
self.e1.grid(row=0, col... | Imagem | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Imagem:
def __init__(self, root):
"""Método construtor da classe imagem"""
<|body_0|>
def zoomIn(self):
"""Dá um zoom na imagem"""
<|body_1|>
def zoomOut(self):
"""Se afasta da imagem"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_019174 | 2,699 | no_license | [
{
"docstring": "Método construtor da classe imagem",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": "Dá um zoom na imagem",
"name": "zoomIn",
"signature": "def zoomIn(self)"
},
{
"docstring": "Se afasta da imagem",
"name": "zoomOut",
"signat... | 3 | null | Implement the Python class `Imagem` described below.
Class description:
Implement the Imagem class.
Method signatures and docstrings:
- def __init__(self, root): Método construtor da classe imagem
- def zoomIn(self): Dá um zoom na imagem
- def zoomOut(self): Se afasta da imagem | Implement the Python class `Imagem` described below.
Class description:
Implement the Imagem class.
Method signatures and docstrings:
- def __init__(self, root): Método construtor da classe imagem
- def zoomIn(self): Dá um zoom na imagem
- def zoomOut(self): Se afasta da imagem
<|skeleton|>
class Imagem:
def __... | 9fbf2f25e3e6fce1f1582af0bd6bc7dbc5b9f588 | <|skeleton|>
class Imagem:
def __init__(self, root):
"""Método construtor da classe imagem"""
<|body_0|>
def zoomIn(self):
"""Dá um zoom na imagem"""
<|body_1|>
def zoomOut(self):
"""Se afasta da imagem"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Imagem:
def __init__(self, root):
"""Método construtor da classe imagem"""
self.root = root
self.a = Label(self.root, text='Altura: ')
self.a.grid(row=0, sticky=E)
self.l = Label(self.root, text='Largura: ')
self.l.grid(row=1, sticky=E)
self.e1 = Entry(s... | the_stack_v2_python_sparse | Aulas Python/Conteúdo das Aulas/102/grid.py | luizdefranca/Curso-Python-IgnoranciaZero | train | 1 | |
0da69d1b5c0eb8a67dd58216aa04d99b24337bf9 | [
"if path in self.saved_dicts:\n id_dict, name_dict = self.saved_dicts[path]\nelse:\n id_dict, name_dict = self.construct_dicts(path, ch_name_dict)\n self.saved_dicts[path] = (id_dict, name_dict)\nreturn id_dict",
"if path in self.saved_dicts:\n id_dict, name_dict = self.saved_dicts[path]\nelse:\n i... | <|body_start_0|>
if path in self.saved_dicts:
id_dict, name_dict = self.saved_dicts[path]
else:
id_dict, name_dict = self.construct_dicts(path, ch_name_dict)
self.saved_dicts[path] = (id_dict, name_dict)
return id_dict
<|end_body_0|>
<|body_start_1|>
... | Class to load xml packet dictionaries | PktXmlLoader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PktXmlLoader:
"""Class to load xml packet dictionaries"""
def get_id_dict(self, path, ch_name_dict):
"""Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally computed for the given path or will construct new dictionarie... | stack_v2_sparse_classes_36k_train_019175 | 4,809 | permissive | [
{
"docstring": "Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally computed for the given path or will construct new dictionaries if the path has never been passed to the get_id_dict or the get_name_dict functions. Args: path (string): Path to ... | 3 | stack_v2_sparse_classes_30k_train_000995 | Implement the Python class `PktXmlLoader` described below.
Class description:
Class to load xml packet dictionaries
Method signatures and docstrings:
- def get_id_dict(self, path, ch_name_dict): Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally comp... | Implement the Python class `PktXmlLoader` described below.
Class description:
Class to load xml packet dictionaries
Method signatures and docstrings:
- def get_id_dict(self, path, ch_name_dict): Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally comp... | aa663303327587146390dde67b83b9bf4e916d54 | <|skeleton|>
class PktXmlLoader:
"""Class to load xml packet dictionaries"""
def get_id_dict(self, path, ch_name_dict):
"""Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally computed for the given path or will construct new dictionarie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PktXmlLoader:
"""Class to load xml packet dictionaries"""
def get_id_dict(self, path, ch_name_dict):
"""Returns the python dictionary keyed by ids for the given path This function will return the same dictionary originally computed for the given path or will construct new dictionaries if the path... | the_stack_v2_python_sparse | Gds/src/fprime_gds/common/loaders/pkt_xml_loader.py | suriyaa/fprime | train | 1 |
46bb0e75a2642b857c6fcf738230900d93dafce1 | [
"super().__init__(func=func, interval=interval)\nself.filename = filename\nself.times: List[float] = []\nself.data: List[Any] = []",
"self.times.append(t)\nif self._num_args == 1:\n self.data.append(self._callback(field))\nelse:\n self.data.append(self._callback(field, t))",
"super().finalize(info)\nif se... | <|body_start_0|>
super().__init__(func=func, interval=interval)
self.filename = filename
self.times: List[float] = []
self.data: List[Any] = []
<|end_body_0|>
<|body_start_1|>
self.times.append(t)
if self._num_args == 1:
self.data.append(self._callback(field)... | Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.data.var()} data_tracker = DataTracker(get_statistics, interval=10) Adding :co... | DataTracker | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTracker:
"""Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.data.var()} data_tracker = DataTracker(... | stack_v2_sparse_classes_36k_train_019176 | 37,567 | permissive | [
{
"docstring": "Args: func: The function to call periodically. The function signature should be `(state)` or `(state, time)`, where `state` contains the current state as an instance of :class:`~pde.fields.FieldBase` and `time` is a float value indicating the current time. Note that only a view of the state is s... | 5 | stack_v2_sparse_classes_30k_train_003942 | Implement the Python class `DataTracker` described below.
Class description:
Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.... | Implement the Python class `DataTracker` described below.
Class description:
Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.... | d9c931a8361eaf27bc3766daba26edc11756b5f5 | <|skeleton|>
class DataTracker:
"""Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.data.var()} data_tracker = DataTracker(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataTracker:
"""Tracker storing custom data obtained by calling a function Example: The data tracker can be used to gather statistics during the run .. code-block:: python def get_statistics(state, time): return {"mean": state.data.mean(), "variance": state.data.var()} data_tracker = DataTracker(get_statistic... | the_stack_v2_python_sparse | pde/trackers/trackers.py | zwicker-group/py-pde | train | 327 |
4cd41b1ecae528006805dd0c1a03e641ab5d8d14 | [
"self.post_parser = reqparse.RequestParser()\nself.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')\nself.post_parser.add_argument('Name', type=str, required=True, help='No object Name provided', location='json')\nsuper(Objects, self).__init__()",
"try:\n A... | <|body_start_0|>
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')
self.post_parser.add_argument('Name', type=str, required=True, help='No object Name provided', location='json')
super(O... | Objects | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche tous les objects de la base d'authorization ainsi que les regles associees"""
<|body_1|>
def post(self):
"""ajoute ... | stack_v2_sparse_classes_36k_train_019177 | 1,595 | no_license | [
{
"docstring": "Constructeur: liste les champs attendus dans le corps HTML",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "affiche tous les objects de la base d'authorization ainsi que les regles associees",
"name": "get",
"signature": "def get(self)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_006706 | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche tous les objects de la base d'authorization ainsi que les regles associees
-... | Implement the Python class `Objects` described below.
Class description:
Implement the Objects class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche tous les objects de la base d'authorization ainsi que les regles associees
-... | 8f107644a74fe46827ec5ed53d0457022bd1608b | <|skeleton|>
class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche tous les objects de la base d'authorization ainsi que les regles associees"""
<|body_1|>
def post(self):
"""ajoute ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Objects:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Id', type=int, required=True, help='No object Id provided', location='json')
self.post_parser.add_argument('N... | the_stack_v2_python_sparse | authapp/view_objects.py | ldurandadomia/Flask-Restful | train | 0 | |
e37c7a2b403a5ea08a4c4dca7671bbb891921288 | [
"super(Attention, self).__init__()\nself.self = SelfAttention(hidden_size, num_attention_heads, attention_dropout_ratio)\nself.output = SelfOutput(hidden_size, hidden_dropout_ratio)",
"attention_output = self.self(input_tensor, attention_mask)\nself_output = self.output(attention_output, input_tensor)\nreturn sel... | <|body_start_0|>
super(Attention, self).__init__()
self.self = SelfAttention(hidden_size, num_attention_heads, attention_dropout_ratio)
self.output = SelfOutput(hidden_size, hidden_dropout_ratio)
<|end_body_0|>
<|body_start_1|>
attention_output = self.self(input_tensor, attention_mask)
... | Attention | Attention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, input_tensor, attention_mask):
"""Attention block"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k_train_019178 | 12,741 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio)"
},
{
"docstring": "Attention block",
"name": "forward",
"signature": "def forward(self, input_tensor, attention_mask)"
... | 2 | null | Implement the Python class `Attention` described below.
Class description:
Attention
Method signatures and docstrings:
- def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio): Initialization
- def forward(self, input_tensor, attention_mask): Attention block | Implement the Python class `Attention` described below.
Class description:
Attention
Method signatures and docstrings:
- def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio): Initialization
- def forward(self, input_tensor, attention_mask): Attention block
<|skeleton|>
... | e6ab0261eb719c21806bbadfd94001ecfe27de45 | <|skeleton|>
class Attention:
"""Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
<|body_0|>
def forward(self, input_tensor, attention_mask):
"""Attention block"""
<|body_1|>
<|end_skelet... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""Attention"""
def __init__(self, hidden_size, num_attention_heads, attention_dropout_ratio, hidden_dropout_ratio):
"""Initialization"""
super(Attention, self).__init__()
self.self = SelfAttention(hidden_size, num_attention_heads, attention_dropout_ratio)
self.... | the_stack_v2_python_sparse | apps/drug_target_interaction/moltrans_dti/double_towers.py | PaddlePaddle/PaddleHelix | train | 771 |
a52197b59eda44c3b937a925affb83433f628d98 | [
"super().__init__()\nKp = diagonalize_gain(to_tensor(Kp))\nKd = diagonalize_gain(to_tensor(Kd))\nassert Kp.shape == torch.Size([6, 6])\nassert Kd.shape == torch.Size([6, 6])\nself.Kp = torch.nn.Parameter(Kp)\nself.Kd = torch.nn.Parameter(Kd)",
"ee_pose_err = (ee_pose_current.inv() * ee_pose_desired).as_twist()\ne... | <|body_start_0|>
super().__init__()
Kp = diagonalize_gain(to_tensor(Kp))
Kd = diagonalize_gain(to_tensor(Kd))
assert Kp.shape == torch.Size([6, 6])
assert Kd.shape == torch.Size([6, 6])
self.Kp = torch.nn.Parameter(Kp)
self.Kd = torch.nn.Parameter(Kd)
<|end_body_0... | PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6) | CartesianSpacePD | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-... | stack_v2_sparse_classes_36k_train_019179 | 9,060 | permissive | [
{
"docstring": "Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix Kd: D gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal matrix",
"name": "__init__",
"signature": "def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor)"
},
{
"docs... | 2 | stack_v2_sparse_classes_30k_train_008608 | Implement the Python class `CartesianSpacePD` described below.
Class description:
PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)
Method signatures and docstrings:
- def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor): Args: Kp: P ga... | Implement the Python class `CartesianSpacePD` described below.
Class description:
PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)
Method signatures and docstrings:
- def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor): Args: Kp: P ga... | 1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18 | <|skeleton|>
class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CartesianSpacePD:
"""PD feedback control in Cartesian space Module parameters: - Kp: P gain matrix of shape (6, 6) - Kd: D gain matrix of shape (6, 6)"""
def __init__(self, Kp: torch.Tensor, Kd: torch.Tensor):
"""Args: Kp: P gain matrix of shape (6, 6) or shape (6,) representing a 6-by-6 diagonal... | the_stack_v2_python_sparse | polymetis/python/torchcontrol/modules/feedback.py | facebookresearch/polymetis | train | 44 |
f168b53ce6f63da62f68753b3d1077739c775b81 | [
"LOG.info('initializing histogram')\nself.timestr = None\nself.x = robjects.FloatVector(inputlist)",
"directory = outdir + '/histogram/'\nLOG.info('checking if directory exists')\nif not os.path.exists(directory):\n LOG.info('%s does not exist so create directory', directory)\n os.makedirs(directory)\nretur... | <|body_start_0|>
LOG.info('initializing histogram')
self.timestr = None
self.x = robjects.FloatVector(inputlist)
<|end_body_0|>
<|body_start_1|>
directory = outdir + '/histogram/'
LOG.info('checking if directory exists')
if not os.path.exists(directory):
LOG.... | Histogram class to plot Histograms | Histogram | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
<|body_0|>
def _check_dir(self, outdir):
"""Will check that outputdir exists"""
<|body_1|>
def _create_file(self, outdir):
... | stack_v2_sparse_classes_36k_train_019180 | 1,673 | no_license | [
{
"docstring": "constructor takes the data to plot",
"name": "__init__",
"signature": "def __init__(self, inputlist)"
},
{
"docstring": "Will check that outputdir exists",
"name": "_check_dir",
"signature": "def _check_dir(self, outdir)"
},
{
"docstring": "Will create file with s... | 4 | null | Implement the Python class `Histogram` described below.
Class description:
Histogram class to plot Histograms
Method signatures and docstrings:
- def __init__(self, inputlist): constructor takes the data to plot
- def _check_dir(self, outdir): Will check that outputdir exists
- def _create_file(self, outdir): Will cr... | Implement the Python class `Histogram` described below.
Class description:
Histogram class to plot Histograms
Method signatures and docstrings:
- def __init__(self, inputlist): constructor takes the data to plot
- def _check_dir(self, outdir): Will check that outputdir exists
- def _create_file(self, outdir): Will cr... | 73beebe994a7eb69985d5b56d677796e0c225cd6 | <|skeleton|>
class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
<|body_0|>
def _check_dir(self, outdir):
"""Will check that outputdir exists"""
<|body_1|>
def _create_file(self, outdir):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Histogram:
"""Histogram class to plot Histograms"""
def __init__(self, inputlist):
"""constructor takes the data to plot"""
LOG.info('initializing histogram')
self.timestr = None
self.x = robjects.FloatVector(inputlist)
def _check_dir(self, outdir):
"""Will ch... | the_stack_v2_python_sparse | core/plots/histogram.py | chesarin/master-thesis | train | 3 |
840a46b5e789e0cd2bcda6c99c65dd0ce47f7f84 | [
"def _genbst(start, end):\n if start <= end:\n index = (start + end + 1) // 2\n root = TreeNode(nums[index])\n root.left = _genbst(start, index - 1)\n root.right = _genbst(index + 1, end)\n return root\nreturn _genbst(0, len(nums) - 1)",
"if nums:\n index = len(nums) // 2\... | <|body_start_0|>
def _genbst(start, end):
if start <= end:
index = (start + end + 1) // 2
root = TreeNode(nums[index])
root.left = _genbst(start, index - 1)
root.right = _genbst(index + 1, end)
return root
return... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def sortedArrayToBST1(self, nums: List[int]) -> TreeNode:
"""recursive :param nums: :return:"""
<|body_0|>
def sortedArrayToBST2(self, nums: List[int]) -> TreeNode:
"""recursive :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_019181 | 1,160 | no_license | [
{
"docstring": "recursive :param nums: :return:",
"name": "sortedArrayToBST1",
"signature": "def sortedArrayToBST1(self, nums: List[int]) -> TreeNode"
},
{
"docstring": "recursive :param nums: :return:",
"name": "sortedArrayToBST2",
"signature": "def sortedArrayToBST2(self, nums: List[in... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST1(self, nums: List[int]) -> TreeNode: recursive :param nums: :return:
- def sortedArrayToBST2(self, nums: List[int]) -> TreeNode: recursive :param nums: :retu... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def sortedArrayToBST1(self, nums: List[int]) -> TreeNode: recursive :param nums: :return:
- def sortedArrayToBST2(self, nums: List[int]) -> TreeNode: recursive :param nums: :retu... | 25f2795b6e7f9f68833f2fddc6cc4f4d977121a6 | <|skeleton|>
class Solution:
def sortedArrayToBST1(self, nums: List[int]) -> TreeNode:
"""recursive :param nums: :return:"""
<|body_0|>
def sortedArrayToBST2(self, nums: List[int]) -> TreeNode:
"""recursive :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def sortedArrayToBST1(self, nums: List[int]) -> TreeNode:
"""recursive :param nums: :return:"""
def _genbst(start, end):
if start <= end:
index = (start + end + 1) // 2
root = TreeNode(nums[index])
root.left = _genbst(start,... | the_stack_v2_python_sparse | 108.py | Darkxiete/leetcode_python | train | 0 | |
4618a62b365614fd068a7c6554cc54e70e2671ed | [
"obj = serializer.save(init_user=self.request.user)\nif obj.instance_type.name.lower() == 'experiment':\n r = redis.StrictRedis(host='localhost', port=6379, db=3)\n channel = '{}'.format(obj.object_id)\n r.publish(channel, json.dumps({'comment': serializer.data, 'action': 'update'}))",
"id = instance.id\... | <|body_start_0|>
obj = serializer.save(init_user=self.request.user)
if obj.instance_type.name.lower() == 'experiment':
r = redis.StrictRedis(host='localhost', port=6379, db=3)
channel = '{}'.format(obj.object_id)
r.publish(channel, json.dumps({'comment': serializer.da... | CommentDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentDetailView:
def perform_update(self, serializer):
"""Update a comment instance and publish a message to Redis."""
<|body_0|>
def perform_destroy(self, instance):
"""Delete a comment instance and publish a message to Redis."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k_train_019182 | 2,850 | no_license | [
{
"docstring": "Update a comment instance and publish a message to Redis.",
"name": "perform_update",
"signature": "def perform_update(self, serializer)"
},
{
"docstring": "Delete a comment instance and publish a message to Redis.",
"name": "perform_destroy",
"signature": "def perform_de... | 2 | null | Implement the Python class `CommentDetailView` described below.
Class description:
Implement the CommentDetailView class.
Method signatures and docstrings:
- def perform_update(self, serializer): Update a comment instance and publish a message to Redis.
- def perform_destroy(self, instance): Delete a comment instance... | Implement the Python class `CommentDetailView` described below.
Class description:
Implement the CommentDetailView class.
Method signatures and docstrings:
- def perform_update(self, serializer): Update a comment instance and publish a message to Redis.
- def perform_destroy(self, instance): Delete a comment instance... | d03ab9dff8333ce51943404d1cb4ef10f20371b5 | <|skeleton|>
class CommentDetailView:
def perform_update(self, serializer):
"""Update a comment instance and publish a message to Redis."""
<|body_0|>
def perform_destroy(self, instance):
"""Delete a comment instance and publish a message to Redis."""
<|body_1|>
<|end_skeleton... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentDetailView:
def perform_update(self, serializer):
"""Update a comment instance and publish a message to Redis."""
obj = serializer.save(init_user=self.request.user)
if obj.instance_type.name.lower() == 'experiment':
r = redis.StrictRedis(host='localhost', port=6379, ... | the_stack_v2_python_sparse | apps/comments/api/views.py | labrepo/LabRepo | train | 1 | |
1c57739dd3b589adda0cdb9c1f55a9ab4ad87373 | [
"n1_dic = {}\nn2_dic = {}\nres = []\nfor n1 in nums1:\n n1_dic[n1] = n1_dic.get(n1, 0) + 1\nfor n2 in nums2:\n n2_dic[n2] = n2_dic.get(n2, 0) + 1\nfor n, c in n1_dic.items():\n if n2_dic.get(n) == c:\n res += [n] * c\n elif n in n2_dic:\n res += [n] * min(c, n2_dic.get(n))\nreturn res",
... | <|body_start_0|>
n1_dic = {}
n2_dic = {}
res = []
for n1 in nums1:
n1_dic[n1] = n1_dic.get(n1, 0) + 1
for n2 in nums2:
n2_dic[n2] = n2_dic.get(n2, 0) + 1
for n, c in n1_dic.items():
if n2_dic.get(n) == c:
res += [n] * c
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
<|body_0|>
def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""先排序,再用双指针法,空间复杂度为O(1)"""
<|body_... | stack_v2_sparse_classes_36k_train_019183 | 3,351 | no_license | [
{
"docstring": "借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值",
"name": "intersect",
"signature": "def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]"
},
{
"docstring": "先排序,再用双指针法,空间复杂度为O(1)",
"name": "intersect1",
"signature": "def intersect1(self, nums1: Li... | 3 | stack_v2_sparse_classes_30k_train_001146 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值
- def intersect1(self, nums1: List[int], nums2: List... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: 借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值
- def intersect1(self, nums1: List[int], nums2: List... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
<|body_0|>
def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""先排序,再用双指针法,空间复杂度为O(1)"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""借用两个字典,用于计数,然后找到共同的数,1、如果计数相等,则乘以计数,2、如果不相等,则乘以两个字典的最小值"""
n1_dic = {}
n2_dic = {}
res = []
for n1 in nums1:
n1_dic[n1] = n1_dic.get(n1, 0) + 1
for n2 in nums2:
... | the_stack_v2_python_sparse | 算法/Week_02/350. 两个数组的交集 II.py | RichieSong/algorithm | train | 0 | |
8221e0d4d952aa7fe98ede580172dfef7f89c456 | [
"super(CNN, self).__init__()\nself.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(... | <|body_start_0|>
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_si... | CNN. | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels... | stack_v2_sparse_classes_36k_train_019184 | 6,668 | no_license | [
{
"docstring": "CNN Builder.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Perform forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009747 | Implement the Python class `CNN` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward. | Implement the Python class `CNN` described below.
Class description:
CNN.
Method signatures and docstrings:
- def __init__(self): CNN Builder.
- def forward(self, x): Perform forward.
<|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, ... | c41fee1dd4d86f152748590887f7e4d0a95c89c8 | <|skeleton|>
class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
<|body_0|>
def forward(self, x):
"""Perform forward."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CNN:
"""CNN."""
def __init__(self):
"""CNN Builder."""
super(CNN, self).__init__()
self.conv_layer = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(in_channels=32, out_channels=64, kernel_size... | the_stack_v2_python_sparse | core/cifar10_net.py | zero-one-loss/scd_github | train | 1 |
39e73bc4d2ffffc77bff21c3a650b157be472d67 | [
"super(DecoderBlock, self).__init__()\nself.mha1 = MultiHeadAttention(dm, h)\nself.mha2 = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(units=dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\ns... | <|body_start_0|>
super(DecoderBlock, self).__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(units=hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(units=dm)
self.layernorm1... | Class Decoder Block | DecoderBlock | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DecoderBlock:
"""Class Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets t... | stack_v2_sparse_classes_36k_train_019185 | 3,106 | permissive | [
{
"docstring": "Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets the following public instance attributes: mha1 - the first MultiHeadAttention layer mha2 - the second Mult... | 2 | null | Implement the Python class `DecoderBlock` described below.
Class description:
Class Decoder Block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the ... | Implement the Python class `DecoderBlock` described below.
Class description:
Class Decoder Block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the ... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class DecoderBlock:
"""Class Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DecoderBlock:
"""Class Decoder Block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""Constructor Class constructor dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layer drop_rate - the dropout rate Sets the following ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/8-transformer_decoder_block.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
c0fe732d4db0ead1857c99d89e678602c7a718ea | [
"self.subject_name = 'client'\nSubject.__init__(self, profile, self.subject_name)\nself.api_base_url = self.profile.platform_url + '/api/v1/client'",
"url = self.api_base_url\nparams = {'size': page_size, 'page': page_number}\ntry:\n raw_response = self.request_handler.make_request(ApiRequestHandler.GET, url, ... | <|body_start_0|>
self.subject_name = 'client'
Subject.__init__(self, profile, self.subject_name)
self.api_base_url = self.profile.platform_url + '/api/v1/client'
<|end_body_0|>
<|body_start_1|>
url = self.api_base_url
params = {'size': page_size, 'page': page_number}
try... | Clients class | Clients | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clients:
"""Clients class"""
def __init__(self, profile):
"""Initialization of Clients object. :param profile: Profile Object :type profile: _profile"""
<|body_0|>
def get_clients(self, page_size=500, page_number=0):
"""Gets all clients associated with the API ke... | stack_v2_sparse_classes_36k_train_019186 | 3,806 | permissive | [
{
"docstring": "Initialization of Clients object. :param profile: Profile Object :type profile: _profile",
"name": "__init__",
"signature": "def __init__(self, profile)"
},
{
"docstring": "Gets all clients associated with the API key. :param page_size: Number of results to be returned on each pa... | 4 | stack_v2_sparse_classes_30k_train_013680 | Implement the Python class `Clients` described below.
Class description:
Clients class
Method signatures and docstrings:
- def __init__(self, profile): Initialization of Clients object. :param profile: Profile Object :type profile: _profile
- def get_clients(self, page_size=500, page_number=0): Gets all clients assoc... | Implement the Python class `Clients` described below.
Class description:
Clients class
Method signatures and docstrings:
- def __init__(self, profile): Initialization of Clients object. :param profile: Profile Object :type profile: _profile
- def get_clients(self, page_size=500, page_number=0): Gets all clients assoc... | 1564cd93505a4d4ccd546f68310e0a09f888e590 | <|skeleton|>
class Clients:
"""Clients class"""
def __init__(self, profile):
"""Initialization of Clients object. :param profile: Profile Object :type profile: _profile"""
<|body_0|>
def get_clients(self, page_size=500, page_number=0):
"""Gets all clients associated with the API ke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Clients:
"""Clients class"""
def __init__(self, profile):
"""Initialization of Clients object. :param profile: Profile Object :type profile: _profile"""
self.subject_name = 'client'
Subject.__init__(self, profile, self.subject_name)
self.api_base_url = self.profile.platfor... | the_stack_v2_python_sparse | lib/risksense_api/__subject/__clients/__clients.py | mtornga/risksense_tools | train | 0 |
4fc4856bd518d015beba38b5cd56b3de92114860 | [
"self.students = []\nself.grades = {}\nself.isSorted = True",
"if student in self.students:\n raise ValueError('Duplicate student')\nself.students.append(student)\nself.grades[student.getIdNum()] = []\nself.isSorted = False",
"try:\n self.grades[student.getIdNum()].append(grade)\nexcept:\n raise ValueE... | <|body_start_0|>
self.students = []
self.grades = {}
self.isSorted = True
<|end_body_0|>
<|body_start_1|>
if student in self.students:
raise ValueError('Duplicate student')
self.students.append(student)
self.grades[student.getIdNum()] = []
self.isSort... | A mapping from students to a list of grades | Grades | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Create empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade book"""
<|body_1|>
def addGrade(self... | stack_v2_sparse_classes_36k_train_019187 | 6,394 | no_license | [
{
"docstring": "Create empty grade book",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Assumes: student is of type Student Add student to the grade book",
"name": "addStudent",
"signature": "def addStudent(self, student)"
},
{
"docstring": "Assumes: gr... | 5 | stack_v2_sparse_classes_30k_val_000477 | Implement the Python class `Grades` described below.
Class description:
A mapping from students to a list of grades
Method signatures and docstrings:
- def __init__(self): Create empty grade book
- def addStudent(self, student): Assumes: student is of type Student Add student to the grade book
- def addGrade(self, st... | Implement the Python class `Grades` described below.
Class description:
A mapping from students to a list of grades
Method signatures and docstrings:
- def __init__(self): Create empty grade book
- def addStudent(self, student): Assumes: student is of type Student Add student to the grade book
- def addGrade(self, st... | 4e8727154a24c7a1d05361a559a997c8d076480d | <|skeleton|>
class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Create empty grade book"""
<|body_0|>
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade book"""
<|body_1|>
def addGrade(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grades:
"""A mapping from students to a list of grades"""
def __init__(self):
"""Create empty grade book"""
self.students = []
self.grades = {}
self.isSorted = True
def addStudent(self, student):
"""Assumes: student is of type Student Add student to the grade ... | the_stack_v2_python_sparse | 01_MIT_Learning/week_5/lectures_and_examples/Section 2/sec_2_generators_grade.py | daftstar/learn_python | train | 0 |
a00a189af9bd5f696170ffaae34b5c2cb8d58bee | [
"attr = handler_input.attributes_manager.session_attributes\nattr['prompt_func'] = prompt\nreturn",
"attr = handler_input.attributes_manager.session_attributes\nspeech_tags = ['<speak>', '</speak>']\nfor tag in speech_tags:\n prompt = prompt.replace(tag, '')\nattr['prompt_ms'] = prompt",
"attr = handler_inpu... | <|body_start_0|>
attr = handler_input.attributes_manager.session_attributes
attr['prompt_func'] = prompt
return
<|end_body_0|>
<|body_start_1|>
attr = handler_input.attributes_manager.session_attributes
speech_tags = ['<speak>', '</speak>']
for tag in speech_tags:
... | LastPrompt | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LastPrompt:
def save_last_prompt_func(handler_input, prompt: object):
"""Saves the last prompt as a function to call."""
<|body_0|>
def save_last_prompt_str(handler_input, prompt: str):
"""Saves the last prompt as a string to return."""
<|body_1|>
def ge... | stack_v2_sparse_classes_36k_train_019188 | 3,105 | permissive | [
{
"docstring": "Saves the last prompt as a function to call.",
"name": "save_last_prompt_func",
"signature": "def save_last_prompt_func(handler_input, prompt: object)"
},
{
"docstring": "Saves the last prompt as a string to return.",
"name": "save_last_prompt_str",
"signature": "def save... | 3 | stack_v2_sparse_classes_30k_train_002493 | Implement the Python class `LastPrompt` described below.
Class description:
Implement the LastPrompt class.
Method signatures and docstrings:
- def save_last_prompt_func(handler_input, prompt: object): Saves the last prompt as a function to call.
- def save_last_prompt_str(handler_input, prompt: str): Saves the last ... | Implement the Python class `LastPrompt` described below.
Class description:
Implement the LastPrompt class.
Method signatures and docstrings:
- def save_last_prompt_func(handler_input, prompt: object): Saves the last prompt as a function to call.
- def save_last_prompt_str(handler_input, prompt: str): Saves the last ... | 1072dea1a5be0b339211ff39db6a89a90aca64c1 | <|skeleton|>
class LastPrompt:
def save_last_prompt_func(handler_input, prompt: object):
"""Saves the last prompt as a function to call."""
<|body_0|>
def save_last_prompt_str(handler_input, prompt: str):
"""Saves the last prompt as a string to return."""
<|body_1|>
def ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LastPrompt:
def save_last_prompt_func(handler_input, prompt: object):
"""Saves the last prompt as a function to call."""
attr = handler_input.attributes_manager.session_attributes
attr['prompt_func'] = prompt
return
def save_last_prompt_str(handler_input, prompt: str):
... | the_stack_v2_python_sparse | 1_code/aux_utils/last_prompt.py | jaimiles23/Multiplication-Medley | train | 0 | |
f6cda4f9804794a28e450e91eb2592ee58c66a19 | [
"rng = np.random.default_rng(seed)\nalpha = rng.normal(loc=0, scale=alpha_scale)\nbeta = rng.normal(loc=beta_loc, scale=beta_scale, size=k)\nx_scales = rng.lognormal(mean=0, sigma=rho, size=(1, k))\nx = rng.normal(loc=0, scale=x_scales, size=(n, k))\nmu = alpha + x @ beta\nprob = 1.0 / (1.0 + np.exp(-mu, where=np.a... | <|body_start_0|>
rng = np.random.default_rng(seed)
alpha = rng.normal(loc=0, scale=alpha_scale)
beta = rng.normal(loc=beta_loc, scale=beta_scale, size=k)
x_scales = rng.lognormal(mean=0, sigma=rho, size=(1, k))
x = rng.normal(loc=0, scale=x_scales, size=(n, k))
mu = alpha... | Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x_scales ~ exp(normal(0, rho)) in R^k for i in 0 .. n-1 X_i ~ normal(0, x_scales) in R... | LogisticRegression | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogisticRegression:
"""Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x_scales ~ exp(normal(0, rho)) in R^k fo... | stack_v2_sparse_classes_36k_train_019189 | 4,155 | permissive | [
{
"docstring": "See the class documentation for an explanation of the other parameters. :param train_frac: fraction of data to be used for training (default 0.5)",
"name": "generate_data",
"signature": "def generate_data(seed: int, n: int=2000, k: int=10, alpha_scale: float=10, beta_scale: float=2.5, be... | 2 | null | Implement the Python class `LogisticRegression` described below.
Class description:
Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x... | Implement the Python class `LogisticRegression` described below.
Class description:
Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x... | d69c652fc882ba50f56eb0cfaa3097d3ede295f9 | <|skeleton|>
class LogisticRegression:
"""Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x_scales ~ exp(normal(0, rho)) in R^k fo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogisticRegression:
"""Bayesian Logistic Regression Hyper Parameters: n - number of items k - number of features alpha_scale, beta_scale, beta_loc, rho -- all values in R Model: alpha ~ Normal(0, alpha_scale) in R beta ~ Normal(beta_loc, beta_scale) in R^k x_scales ~ exp(normal(0, rho)) in R^k for i in 0 .. n... | the_stack_v2_python_sparse | pplbench/models/logistic_regression.py | rambam613/pplbench | train | 0 |
166ec3655758b400ee613143fbaa993f18c28acf | [
"self._label_df = label_df\nself._image_col = image_col\nself._label_col = label_col\nself._output_df_cols = output_df_cols\nself._labelled_images = None\nself._logger = logging.get_logger(__name__)\nself._logger.info('label_df: %d image_col: %s label_col: %s output_df_cols: %s', len(self._label_df), self._image_co... | <|body_start_0|>
self._label_df = label_df
self._image_col = image_col
self._label_col = label_col
self._output_df_cols = output_df_cols
self._labelled_images = None
self._logger = logging.get_logger(__name__)
self._logger.info('label_df: %d image_col: %s label_co... | It generates Siamese input tuples. | TupleGeneration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TupleGeneration:
"""It generates Siamese input tuples."""
def __init__(self, label_df, image_col, label_col, output_df_cols):
"""It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- It contains the input names and labels. image_col {string}... | stack_v2_sparse_classes_36k_train_019190 | 6,055 | no_license | [
{
"docstring": "It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- It contains the input names and labels. image_col {string} -- The image column name in the dataframe. label_col {string} -- The label column name in the dataframe. output_df_cols {(string, string, st... | 5 | stack_v2_sparse_classes_30k_train_013866 | Implement the Python class `TupleGeneration` described below.
Class description:
It generates Siamese input tuples.
Method signatures and docstrings:
- def __init__(self, label_df, image_col, label_col, output_df_cols): It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- I... | Implement the Python class `TupleGeneration` described below.
Class description:
It generates Siamese input tuples.
Method signatures and docstrings:
- def __init__(self, label_df, image_col, label_col, output_df_cols): It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- I... | 08b697bc88667c1ded4d8fc8a102cf7432e31596 | <|skeleton|>
class TupleGeneration:
"""It generates Siamese input tuples."""
def __init__(self, label_df, image_col, label_col, output_df_cols):
"""It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- It contains the input names and labels. image_col {string}... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TupleGeneration:
"""It generates Siamese input tuples."""
def __init__(self, label_df, image_col, label_col, output_df_cols):
"""It initializes the required and optional parameters. Arguments: label_df {A Pandas DataFrame} -- It contains the input names and labels. image_col {string} -- The image... | the_stack_v2_python_sparse | siamese/tuple.py | NareshPS/humpback-whale | train | 1 |
bdb210b1303b303efd6de218f1d4371053ace5e8 | [
"super(Image, self).__init__(data=data, database=database, id=id)\nself.dataset = dataset\nself.rejected = False\nif self.dataset:\n if self.dataset.database and (not self.database):\n self.database = self.dataset.database\n self.dataset.images.add(self)\n self._data.setdefault('dataset', self.datas... | <|body_start_0|>
super(Image, self).__init__(data=data, database=database, id=id)
self.dataset = dataset
self.rejected = False
if self.dataset:
if self.dataset.database and (not self.database):
self.database = self.dataset.database
self.dataset.ima... | Class corresponding to the images table in the database | Image | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Image:
"""Class corresponding to the images table in the database"""
def __init__(self, data=None, dataset=None, database=None, id=None):
"""If id is supplied, the data and image arguments are ignored."""
<|body_0|>
def id(self):
"""Add or obtain an id to/from th... | stack_v2_sparse_classes_36k_train_019191 | 16,395 | permissive | [
{
"docstring": "If id is supplied, the data and image arguments are ignored.",
"name": "__init__",
"signature": "def __init__(self, data=None, dataset=None, database=None, id=None)"
},
{
"docstring": "Add or obtain an id to/from the table If the ID does not exist the image is inserted into the d... | 3 | null | Implement the Python class `Image` described below.
Class description:
Class corresponding to the images table in the database
Method signatures and docstrings:
- def __init__(self, data=None, dataset=None, database=None, id=None): If id is supplied, the data and image arguments are ignored.
- def id(self): Add or ob... | Implement the Python class `Image` described below.
Class description:
Class corresponding to the images table in the database
Method signatures and docstrings:
- def __init__(self, data=None, dataset=None, database=None, id=None): If id is supplied, the data and image arguments are ignored.
- def id(self): Add or ob... | dc6d4aaebc9b3f8068a11479d0ecc67f7ba7222a | <|skeleton|>
class Image:
"""Class corresponding to the images table in the database"""
def __init__(self, data=None, dataset=None, database=None, id=None):
"""If id is supplied, the data and image arguments are ignored."""
<|body_0|>
def id(self):
"""Add or obtain an id to/from th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Image:
"""Class corresponding to the images table in the database"""
def __init__(self, data=None, dataset=None, database=None, id=None):
"""If id is supplied, the data and image arguments are ignored."""
super(Image, self).__init__(data=data, database=database, id=id)
self.datase... | the_stack_v2_python_sparse | tkp/db/orm.py | transientskp/tkp | train | 14 |
9021a0a10da337fe392bc249c7fe8b26c4c04a62 | [
"instance = Brand.objects.all()\nserializer = BrandsSimpleSerializer(instance, many=True)\nreturn Response(serializer.data)",
"if pk:\n instance = GoodsCategory.objects.filter(parent_id=pk)\nelse:\n instance = GoodsCategory.objects.filter(parent=None)\nserializer = GoodsCategoriesSerializer(instance, many=T... | <|body_start_0|>
instance = Brand.objects.all()
serializer = BrandsSimpleSerializer(instance, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
if pk:
instance = GoodsCategory.objects.filter(parent_id=pk)
else:
instance = GoodsCa... | SPU视图集 | SPUSViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
<|body_0|>
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回父类, 再次请求返回二级和三级"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
instance = Brand.objects.all()
... | stack_v2_sparse_classes_36k_train_019192 | 2,399 | permissive | [
{
"docstring": "返回简单的商品品牌",
"name": "brands_simple",
"signature": "def brands_simple(self, request)"
},
{
"docstring": "返回商品分类,第一次返回父类, 再次请求返回二级和三级",
"name": "channel_categories",
"signature": "def channel_categories(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007055 | Implement the Python class `SPUSViewSet` described below.
Class description:
SPU视图集
Method signatures and docstrings:
- def brands_simple(self, request): 返回简单的商品品牌
- def channel_categories(self, request, pk=None): 返回商品分类,第一次返回父类, 再次请求返回二级和三级 | Implement the Python class `SPUSViewSet` described below.
Class description:
SPU视图集
Method signatures and docstrings:
- def brands_simple(self, request): 返回简单的商品品牌
- def channel_categories(self, request, pk=None): 返回商品分类,第一次返回父类, 再次请求返回二级和三级
<|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(sel... | d3ce2185ec3c68325e8becddce07d0a9da144325 | <|skeleton|>
class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
<|body_0|>
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回父类, 再次请求返回二级和三级"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SPUSViewSet:
"""SPU视图集"""
def brands_simple(self, request):
"""返回简单的商品品牌"""
instance = Brand.objects.all()
serializer = BrandsSimpleSerializer(instance, many=True)
return Response(serializer.data)
def channel_categories(self, request, pk=None):
"""返回商品分类,第一次返回... | the_stack_v2_python_sparse | meiduo_mall/meiduo_mall/apps/meiduo_admin/views/spus.py | qls7/dianshanghoutai | train | 0 |
5174394153a798634a1773ecb7760e645fcbd8ee | [
"self.target = target\nself.ports = ports\nself.scan_type = scan_type\nself.timeout = kwargs.get('to')\nself.threads = kwargs.get('th')\nself.output_to_file = kwargs.get('o')\nself.save_to_database = kwargs.get('db')\nself.sound = kwargs.get('s')\nself.knock = kwargs.get('knock')\nself.joke = kwargs.get('joke')",
... | <|body_start_0|>
self.target = target
self.ports = ports
self.scan_type = scan_type
self.timeout = kwargs.get('to')
self.threads = kwargs.get('th')
self.output_to_file = kwargs.get('o')
self.save_to_database = kwargs.get('db')
self.sound = kwargs.get('s')
... | UserInputModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserInputModel:
def __init__(self, target: str, ports: [int], scan_type: str, **kwargs):
"""Constructor check if the user input is valid and set default settings if none are given by the user"""
<|body_0|>
def check_ip(userinput):
"""Check if a valid ip address has b... | stack_v2_sparse_classes_36k_train_019193 | 3,846 | no_license | [
{
"docstring": "Constructor check if the user input is valid and set default settings if none are given by the user",
"name": "__init__",
"signature": "def __init__(self, target: str, ports: [int], scan_type: str, **kwargs)"
},
{
"docstring": "Check if a valid ip address has been given",
"na... | 4 | stack_v2_sparse_classes_30k_train_012060 | Implement the Python class `UserInputModel` described below.
Class description:
Implement the UserInputModel class.
Method signatures and docstrings:
- def __init__(self, target: str, ports: [int], scan_type: str, **kwargs): Constructor check if the user input is valid and set default settings if none are given by th... | Implement the Python class `UserInputModel` described below.
Class description:
Implement the UserInputModel class.
Method signatures and docstrings:
- def __init__(self, target: str, ports: [int], scan_type: str, **kwargs): Constructor check if the user input is valid and set default settings if none are given by th... | 77e3108a9ee40c2375f27041bcd8dcae072a1e64 | <|skeleton|>
class UserInputModel:
def __init__(self, target: str, ports: [int], scan_type: str, **kwargs):
"""Constructor check if the user input is valid and set default settings if none are given by the user"""
<|body_0|>
def check_ip(userinput):
"""Check if a valid ip address has b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserInputModel:
def __init__(self, target: str, ports: [int], scan_type: str, **kwargs):
"""Constructor check if the user input is valid and set default settings if none are given by the user"""
self.target = target
self.ports = ports
self.scan_type = scan_type
self.tim... | the_stack_v2_python_sparse | model/user_input_model.py | loran-code/port_scanner | train | 0 | |
833716797f678f63fa8928fcf84e27d209a85b55 | [
"self._pokemon = pokemon\nself._opponent_pokemon = opponent_pokemon\nself._is_run_successful = None",
"if self._is_run_successful is None:\n F = (self._pokemon.stats[StatEnum.SPEED] * 128 / self._opponent_pokemon.stats[StatEnum.SPEED] + 30) % 256\n self._is_run_successful = F > random.randint(0, 255)\nretur... | <|body_start_0|>
self._pokemon = pokemon
self._opponent_pokemon = opponent_pokemon
self._is_run_successful = None
<|end_body_0|>
<|body_start_1|>
if self._is_run_successful is None:
F = (self._pokemon.stats[StatEnum.SPEED] * 128 / self._opponent_pokemon.stats[StatEnum.SPEED]... | Represents the attempt to run from a battle. | RunActionModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunActionModel:
"""Represents the attempt to run from a battle."""
def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None:
"""Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon."""
<|bod... | stack_v2_sparse_classes_36k_train_019194 | 1,022 | no_license | [
{
"docstring": "Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon.",
"name": "__init__",
"signature": "def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None"
},
{
"docstring": "Determine whether the pokem... | 2 | stack_v2_sparse_classes_30k_test_000571 | Implement the Python class `RunActionModel` described below.
Class description:
Represents the attempt to run from a battle.
Method signatures and docstrings:
- def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None: Create a new run action. :param pokemon: The pokemon trying to escape. :pa... | Implement the Python class `RunActionModel` described below.
Class description:
Represents the attempt to run from a battle.
Method signatures and docstrings:
- def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None: Create a new run action. :param pokemon: The pokemon trying to escape. :pa... | dfff995e3e50a8cfa56af73d93de82c427bfa2f5 | <|skeleton|>
class RunActionModel:
"""Represents the attempt to run from a battle."""
def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None:
"""Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunActionModel:
"""Represents the attempt to run from a battle."""
def __init__(self, pokemon: PokemonModel, opponent_pokemon: PokemonModel) -> None:
"""Create a new run action. :param pokemon: The pokemon trying to escape. :param opponent_pokemon: The other pokemon."""
self._pokemon = po... | the_stack_v2_python_sparse | src/models/battle/run_action_model.py | J-GG/Pymon | train | 0 |
e007d6c77071f56197af91fcaebf6256d188ed94 | [
"self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)\nself.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)\nself.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train)",
"STE = tfds.deprecated.text.SubwordTex... | <|body_start_0|>
self.data_train = tfds.load('ted_hrlr_translate/pt_to_en', split='train', as_supervised=True)
self.data_valid = tfds.load('ted_hrlr_translate/pt_to_en', split='validation', as_supervised=True)
self.tokenizer_pt, self.tokenizer_en = self.tokenize_dataset(self.data_train)
<|end_bo... | loads and preps a dataset for machine translation | Dataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self):
"""creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt t... | stack_v2_sparse_classes_36k_train_019195 | 2,046 | no_license | [
{
"docstring": "creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt to_en tf.data.Dataset validate split, loaded as_supervided tokenizer_pt is the Portuguese tokenizer c... | 2 | stack_v2_sparse_classes_30k_train_003186 | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self): creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervid... | Implement the Python class `Dataset` described below.
Class description:
loads and preps a dataset for machine translation
Method signatures and docstrings:
- def __init__(self): creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervid... | 5114f884241b3406940b00450d8c71f55d5d6a70 | <|skeleton|>
class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self):
"""creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Dataset:
"""loads and preps a dataset for machine translation"""
def __init__(self):
"""creates the instance attributes: data_train, which contains the ted_hrlr_translate/pt_to en tf.data.Dataset train split, loaded as_supervided data_valid, which contains the ted_hrlr_translate/pt to_en tf.data.... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/0-dataset.py | icculp/holbertonschool-machine_learning | train | 0 |
e1361be19a1ce745ffb7488cd3e846d1679103cf | [
"if isinstance(X, CommutativeRing):\n X = AffineScheme(X)\nif isinstance(Y, CommutativeRing):\n Y = AffineScheme(Y)\nif is_AffineScheme(base):\n base_spec = base\n base_ring = base.coordinate_ring()\nelif isinstance(base, CommutativeRing):\n base_spec = AffineScheme(base)\n base_ring = base\nelse:... | <|body_start_0|>
if isinstance(X, CommutativeRing):
X = AffineScheme(X)
if isinstance(Y, CommutativeRing):
Y = AffineScheme(Y)
if is_AffineScheme(base):
base_spec = base
base_ring = base.coordinate_ring()
elif isinstance(base, CommutativeRi... | Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom(A2) True The Hom-sets are identical if the domains and codomains are identical:: sage... | SchemeHomsetFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchemeHomsetFactory:
"""Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom(A2) True The Hom-sets are identical if... | stack_v2_sparse_classes_36k_train_019196 | 19,052 | no_license | [
{
"docstring": "Create a key that uniquely determines the Hom-set. INPUT: - ``X`` -- a scheme. The domain of the morphisms. - ``Y`` -- a scheme. The codomain of the morphisms. - ``category`` -- a category for the Hom-sets (default: schemes over given base). - ``base`` -- a scheme or a ring. The base scheme of d... | 2 | stack_v2_sparse_classes_30k_train_005226 | Implement the Python class `SchemeHomsetFactory` described below.
Class description:
Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom... | Implement the Python class `SchemeHomsetFactory` described below.
Class description:
Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class SchemeHomsetFactory:
"""Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom(A2) True The Hom-sets are identical if... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SchemeHomsetFactory:
"""Factory for Hom-sets of schemes. EXAMPLES:: sage: A2 = AffineSpace(QQ,2) sage: A3 = AffineSpace(QQ,3) sage: Hom = A3.Hom(A2) The Hom-sets are uniquely determined by domain and codomain:: sage: Hom is copy(Hom) True sage: Hom is A3.Hom(A2) True The Hom-sets are identical if the domains ... | the_stack_v2_python_sparse | sage/src/sage/schemes/generic/homset.py | bopopescu/geosci | train | 0 |
77ea59edc75bc37bbb84ebc9e8b4a6a458150b94 | [
"name = read_unicode_string(fp)\nclassID = read_length_and_key(fp)\ntypeID = read_length_and_key(fp)\nenum = read_length_and_key(fp)\nreturn cls(name, classID, typeID, enum)",
"written = write_unicode_string(fp, self.name)\nwritten += write_length_and_key(fp, self.classID)\nwritten += write_length_and_key(fp, sel... | <|body_start_0|>
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
typeID = read_length_and_key(fp)
enum = read_length_and_key(fp)
return cls(name, classID, typeID, enum)
<|end_body_0|>
<|body_start_1|>
written = write_unicode_string(fp, self.name)
... | Enumerated reference structure. .. py:attribute:: value | EnumeratedReference | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp... | stack_v2_sparse_classes_36k_train_019197 | 19,890 | permissive | [
{
"docstring": "Read the element from a file-like object. :param fp: file-like object",
"name": "read",
"signature": "def read(cls, fp)"
},
{
"docstring": "Write the element to a file-like object. :param fp: file-like object",
"name": "write",
"signature": "def write(self, fp)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020352 | Implement the Python class `EnumeratedReference` described below.
Class description:
Enumerated reference structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-l... | Implement the Python class `EnumeratedReference` described below.
Class description:
Enumerated reference structure. .. py:attribute:: value
Method signatures and docstrings:
- def read(cls, fp): Read the element from a file-like object. :param fp: file-like object
- def write(self, fp): Write the element to a file-l... | 0e3ac5b64061c7eb87c6eeacce4b9792d1f479b5 | <|skeleton|>
class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
<|body_0|>
def write(self, fp):
"""Write the element to a file-like object. :param fp... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EnumeratedReference:
"""Enumerated reference structure. .. py:attribute:: value"""
def read(cls, fp):
"""Read the element from a file-like object. :param fp: file-like object"""
name = read_unicode_string(fp)
classID = read_length_and_key(fp)
typeID = read_length_and_key(f... | the_stack_v2_python_sparse | psd_tools/psd/descriptor.py | sfneal/psd-tools3 | train | 30 |
544c10643bdcebd2dc744863b20c45806962afe7 | [
"while p != self.id[p]:\n p = self.id[p]\nreturn p",
"pRoot = self.find(p)\nqRoot = self.find(q)\nif pRoot == qRoot:\n return\nself.id[pRoot] = qRoot\nself.count -= 1"
] | <|body_start_0|>
while p != self.id[p]:
p = self.id[p]
return p
<|end_body_0|>
<|body_start_1|>
pRoot = self.find(p)
qRoot = self.find(q)
if pRoot == qRoot:
return
self.id[pRoot] = qRoot
self.count -= 1
<|end_body_1|>
| QuickUnion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuickUnion:
def find(self, p):
"""获取所属集合"""
<|body_0|>
def union(self, p, q):
"""连接两个集合"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while p != self.id[p]:
p = self.id[p]
return p
<|end_body_0|>
<|body_start_1|>
pRoot... | stack_v2_sparse_classes_36k_train_019198 | 984 | no_license | [
{
"docstring": "获取所属集合",
"name": "find",
"signature": "def find(self, p)"
},
{
"docstring": "连接两个集合",
"name": "union",
"signature": "def union(self, p, q)"
}
] | 2 | null | Implement the Python class `QuickUnion` described below.
Class description:
Implement the QuickUnion class.
Method signatures and docstrings:
- def find(self, p): 获取所属集合
- def union(self, p, q): 连接两个集合 | Implement the Python class `QuickUnion` described below.
Class description:
Implement the QuickUnion class.
Method signatures and docstrings:
- def find(self, p): 获取所属集合
- def union(self, p, q): 连接两个集合
<|skeleton|>
class QuickUnion:
def find(self, p):
"""获取所属集合"""
<|body_0|>
def union(self,... | 44ae15211514dbc982c668522320389fc90c5c9c | <|skeleton|>
class QuickUnion:
def find(self, p):
"""获取所属集合"""
<|body_0|>
def union(self, p, q):
"""连接两个集合"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QuickUnion:
def find(self, p):
"""获取所属集合"""
while p != self.id[p]:
p = self.id[p]
return p
def union(self, p, q):
"""连接两个集合"""
pRoot = self.find(p)
qRoot = self.find(q)
if pRoot == qRoot:
return
self.id[pRoot] = qRoot... | the_stack_v2_python_sparse | python/algorithms算法/fundamentals/uf_quickunion.py | ZhangShuaiyi/myTest | train | 0 | |
8af38bc258b027642cf1db7d75621e7c25c195eb | [
"self.model = RandomForestClassifier(bootstrap=True, criterion='gini', min_samples_split=2, max_features='auto', min_samples_leaf=1, n_estimators=1000)\nself.X = X\nself.Y = Y",
"if params is None:\n params = [{'n_estimators': [100, 200, 500, 1000], 'criterion': ['entropy'], 'max_features': ['sqrt', 'auto'], '... | <|body_start_0|>
self.model = RandomForestClassifier(bootstrap=True, criterion='gini', min_samples_split=2, max_features='auto', min_samples_leaf=1, n_estimators=1000)
self.X = X
self.Y = Y
<|end_body_0|>
<|body_start_1|>
if params is None:
params = [{'n_estimators': [100, 2... | Random forest classifier | RFClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RFClassifier:
"""Random forest classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
<|body_0|>
def tune_and_eval(self, results_file, params=None, feature_names=None, njobs=50, kfold=10):
""":param results_file: :param params: :param feature_names: :p... | stack_v2_sparse_classes_36k_train_019199 | 10,404 | permissive | [
{
"docstring": ":param X: :param Y:",
"name": "__init__",
"signature": "def __init__(self, X, Y)"
},
{
"docstring": ":param results_file: :param params: :param feature_names: :param njobs: :param kfold: :return:",
"name": "tune_and_eval",
"signature": "def tune_and_eval(self, results_fil... | 4 | stack_v2_sparse_classes_30k_train_014583 | Implement the Python class `RFClassifier` described below.
Class description:
Random forest classifier
Method signatures and docstrings:
- def __init__(self, X, Y): :param X: :param Y:
- def tune_and_eval(self, results_file, params=None, feature_names=None, njobs=50, kfold=10): :param results_file: :param params: :pa... | Implement the Python class `RFClassifier` described below.
Class description:
Random forest classifier
Method signatures and docstrings:
- def __init__(self, X, Y): :param X: :param Y:
- def tune_and_eval(self, results_file, params=None, feature_names=None, njobs=50, kfold=10): :param results_file: :param params: :pa... | 127177deb630ad66520a2fdae1793417cd77ee99 | <|skeleton|>
class RFClassifier:
"""Random forest classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
<|body_0|>
def tune_and_eval(self, results_file, params=None, feature_names=None, njobs=50, kfold=10):
""":param results_file: :param params: :param feature_names: :p... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RFClassifier:
"""Random forest classifier"""
def __init__(self, X, Y):
""":param X: :param Y:"""
self.model = RandomForestClassifier(bootstrap=True, criterion='gini', min_samples_split=2, max_features='auto', min_samples_leaf=1, n_estimators=1000)
self.X = X
self.Y = Y
... | the_stack_v2_python_sparse | classifier/classical_classifiers.py | seedpcseed/DiTaxa | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.