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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a00f75e9ae7be39009c29062d6bd5bcbec3a5191 | [
"super(LoadDimensionOperator, self).__init__(*args, **kwargs)\nself.redshift_conn_id = redshift_conn_id\nself.table = table\nself.sql_stmt = sql_stmt\nself.truncate = truncate\nself.create_table_stmt = create_table_stmt",
"redshift = PostgresHook(self.redshift_conn_id)\nif self.create_table_stmt:\n self.log.in... | <|body_start_0|>
super(LoadDimensionOperator, self).__init__(*args, **kwargs)
self.redshift_conn_id = redshift_conn_id
self.table = table
self.sql_stmt = sql_stmt
self.truncate = truncate
self.create_table_stmt = create_table_stmt
<|end_body_0|>
<|body_start_1|>
... | An airflow custom operator which loads the dimension table from the staged tables. | LoadDimensionOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LoadDimensionOperator:
"""An airflow custom operator which loads the dimension table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, truncate=True, create_table_stmt=None, *args, **kwargs):
"""LoadDimensionOperator Constructor to initialize object. Pa... | stack_v2_sparse_classes_36k_train_033500 | 2,484 | no_license | [
{
"docstring": "LoadDimensionOperator Constructor to initialize object. Parameters ---------- redshift_conn_id : str redshift connection id used by the Postgresql hook table : str The dimension table sql_stmt : str SQL statement which specifies how to load fact table from the staged tables truncate : bool, opti... | 2 | stack_v2_sparse_classes_30k_train_008075 | Implement the Python class `LoadDimensionOperator` described below.
Class description:
An airflow custom operator which loads the dimension table from the staged tables.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id, table, sql_stmt, truncate=True, create_table_stmt=None, *args, **kwargs): L... | Implement the Python class `LoadDimensionOperator` described below.
Class description:
An airflow custom operator which loads the dimension table from the staged tables.
Method signatures and docstrings:
- def __init__(self, redshift_conn_id, table, sql_stmt, truncate=True, create_table_stmt=None, *args, **kwargs): L... | c061dbede550e18111de346e58dfb5f258e4c63f | <|skeleton|>
class LoadDimensionOperator:
"""An airflow custom operator which loads the dimension table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, truncate=True, create_table_stmt=None, *args, **kwargs):
"""LoadDimensionOperator Constructor to initialize object. Pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LoadDimensionOperator:
"""An airflow custom operator which loads the dimension table from the staged tables."""
def __init__(self, redshift_conn_id, table, sql_stmt, truncate=True, create_table_stmt=None, *args, **kwargs):
"""LoadDimensionOperator Constructor to initialize object. Parameters ----... | the_stack_v2_python_sparse | Projects/project5-Data Pipelines with Airflow/plugins/operators/load_dimension.py | MyDataDevOps/DataEngineeringNanoDegree | train | 0 |
631518bd38ecc4c7606aff24e3224c65b3a42830 | [
"super(BaseBlock, self).__init__()\npaddings = [(kernel_size - 1) // 2 for kernel_size in kernel_sizes]\nself.use_bottleneck = use_bottleneck\nif use_bottleneck:\n self.conv_layers_1 = nn.ModuleList([nn.Conv1d(in_channels=in_channels, out_channels=bottleneck_channel, kernel_size=1) for bottleneck_channel in bott... | <|body_start_0|>
super(BaseBlock, self).__init__()
paddings = [(kernel_size - 1) // 2 for kernel_size in kernel_sizes]
self.use_bottleneck = use_bottleneck
if use_bottleneck:
self.conv_layers_1 = nn.ModuleList([nn.Conv1d(in_channels=in_channels, out_channels=bottleneck_channe... | BaseBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseBlock:
def __init__(self, in_channels, kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck=True):
"""Initializes the class BaseBlock which is the parent class to all blocks. :param in_channels: Number of input channel. :param kernel_sizes: list of kernel sizes, one entry... | stack_v2_sparse_classes_36k_train_033501 | 2,874 | no_license | [
{
"docstring": "Initializes the class BaseBlock which is the parent class to all blocks. :param in_channels: Number of input channel. :param kernel_sizes: list of kernel sizes, one entry per scale. :param channel_sizes: number of output channel, one entry per scale. :param bottleneck_channels: number of output ... | 2 | stack_v2_sparse_classes_30k_train_003047 | Implement the Python class `BaseBlock` described below.
Class description:
Implement the BaseBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck=True): Initializes the class BaseBlock which is the parent class to all blocks.... | Implement the Python class `BaseBlock` described below.
Class description:
Implement the BaseBlock class.
Method signatures and docstrings:
- def __init__(self, in_channels, kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck=True): Initializes the class BaseBlock which is the parent class to all blocks.... | 76c4537d605bdf6f46586aa245c8bdec64fc4ec1 | <|skeleton|>
class BaseBlock:
def __init__(self, in_channels, kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck=True):
"""Initializes the class BaseBlock which is the parent class to all blocks. :param in_channels: Number of input channel. :param kernel_sizes: list of kernel sizes, one entry... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseBlock:
def __init__(self, in_channels, kernel_sizes, channel_sizes, bottleneck_channels, use_bottleneck=True):
"""Initializes the class BaseBlock which is the parent class to all blocks. :param in_channels: Number of input channel. :param kernel_sizes: list of kernel sizes, one entry per scale. :p... | the_stack_v2_python_sparse | blocks/base_block.py | aosbro/audio-super-resolution | train | 0 | |
38f8e29a92f6de499c2c4f02f17b895e26eb9c09 | [
"self.__grRep = grRep\nself.__grVal = grVal\nself.__stRep = stRep",
"st = self.__stRep.find(stId)\nif st == None:\n raise StudentNotFoundException()\ngr = Grade(st, disc, grade)\nself.__grVal.validate(gr)\nself.__grRep.store(gr)\nreturn gr",
"st = self.__stRep.find(stId)\nif st == None:\n raise StudentNot... | <|body_start_0|>
self.__grRep = grRep
self.__grVal = grVal
self.__stRep = stRep
<|end_body_0|>
<|body_start_1|>
st = self.__stRep.find(stId)
if st == None:
raise StudentNotFoundException()
gr = Grade(st, disc, grade)
self.__grVal.validate(gr)
... | GradingService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradingService:
def __init__(self, grRep, grVal, stRep):
"""Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository"""
<|body_0|>
def assign(self, stId, disc, grade):
"""Assign a grade for a student at a given discipline stID String, id of... | stack_v2_sparse_classes_36k_train_033502 | 9,981 | no_license | [
{
"docstring": "Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository",
"name": "__init__",
"signature": "def __init__(self, grRep, grVal, stRep)"
},
{
"docstring": "Assign a grade for a student at a given discipline stID String, id of the student disc String, disci... | 4 | null | Implement the Python class `GradingService` described below.
Class description:
Implement the GradingService class.
Method signatures and docstrings:
- def __init__(self, grRep, grVal, stRep): Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository
- def assign(self, stId, disc, grade): As... | Implement the Python class `GradingService` described below.
Class description:
Implement the GradingService class.
Method signatures and docstrings:
- def __init__(self, grRep, grVal, stRep): Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository
- def assign(self, stId, disc, grade): As... | 47d71b894d6fb81907256bb0f439f048e65a089a | <|skeleton|>
class GradingService:
def __init__(self, grRep, grVal, stRep):
"""Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository"""
<|body_0|>
def assign(self, stId, disc, grade):
"""Assign a grade for a student at a given discipline stID String, id of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GradingService:
def __init__(self, grRep, grVal, stRep):
"""Initialise grRep - GradeRepository grVal - GradeValidator stRep - StudentRepository"""
self.__grRep = grRep
self.__grVal = grVal
self.__stRep = stRep
def assign(self, stId, disc, grade):
"""Assign a grade ... | the_stack_v2_python_sparse | Semester1/Fundamentals of Programming/exemple/StudentGradeDTO/services/services.py | bogdansimion31/University | train | 0 | |
68db201fc0705dac946a6572e1998719fc8cd49d | [
"self.name = 'Zusatzdaten'\nTemplateFunction.__init__(self, task_config, general_config)\nif self.name in self.task_config['ausgefuehrte_funktionen'] and self.task_config['resume']:\n self.logger.info('Funktion ' + self.name + ' wird ausgelassen.')\nelse:\n self.logger.info('Funktion ' + self.name + ' wird au... | <|body_start_0|>
self.name = 'Zusatzdaten'
TemplateFunction.__init__(self, task_config, general_config)
if self.name in self.task_config['ausgefuehrte_funktionen'] and self.task_config['resume']:
self.logger.info('Funktion ' + self.name + ' wird ausgelassen.')
else:
... | Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]`` | Zusatzdaten | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Zusatzdaten:
"""Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]``"""
def __init__(self, task_config, general_... | stack_v2_sparse_classes_36k_train_033503 | 2,477 | no_license | [
{
"docstring": "Constructor :param task_config: Vom Usecase initialisierte task_config (Dictionary)",
"name": "__init__",
"signature": "def __init__(self, task_config, general_config)"
},
{
"docstring": "Führt den eigentlichen Funktionsablauf aus. Weil shutil.copytree einen Fehler zurückgibt, we... | 2 | stack_v2_sparse_classes_30k_train_007062 | Implement the Python class `Zusatzdaten` described below.
Class description:
Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]``
Method s... | Implement the Python class `Zusatzdaten` described below.
Class description:
Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]``
Method s... | 65c1cdc83a40a0343800a839c6f3cbe61ec37abc | <|skeleton|>
class Zusatzdaten:
"""Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]``"""
def __init__(self, task_config, general_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Zusatzdaten:
"""Kopiert ein allfällig vorhandenes Zusatzdaten-Verzeichnis auf den Freigabeshare. Dort wird es zusätzlich in einen neuen Ordner mit Zeitstands-Angabe kopiert. Die Angaben sind in task_config abgelegt: - ``task_config["zusatzdaten"]``"""
def __init__(self, task_config, general_config):
... | the_stack_v2_python_sparse | src/iLader/functions/Zusatzdaten.py | AGIBE/iLader | train | 0 |
863777be6a8136dd8144abda04eea8a9265533b8 | [
"if not data:\n data = []\nif not opt or len(opt) != 2:\n opt = (1, 1)\nif len(data) < opt[1]:\n data.extend([0 for _ in range(opt[1] - len(data))])\nreturn b''.join((SMPayloadTypeINT.encode(d, opt[0]) for d in data))",
"if not opt or len(opt) != 2:\n opt = (1, 1)\nif len(payload) < opt[0] * opt[1]:\n... | <|body_start_0|>
if not data:
data = []
if not opt or len(opt) != 2:
opt = (1, 1)
if len(data) < opt[1]:
data.extend([0 for _ in range(opt[1] - len(data))])
return b''.join((SMPayloadTypeINT.encode(d, opt[0]) for d in data))
<|end_body_0|>
<|body_star... | List of integer | SMPayloadTypeINTLIST | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\... | stack_v2_sparse_classes_36k_train_033504 | 14,049 | permissive | [
{
"docstring": "Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\\\x02\\\\x05' >>> SMPayloadTypeINTLIST.encode([1], opt=(1, 2)) # zero padding b'\\\\x01\\\\... | 2 | stack_v2_sparse_classes_30k_val_000457 | Implement the Python class `SMPayloadTypeINTLIST` described below.
Class description:
List of integer
Method signatures and docstrings:
- def encode(data, opt=None): Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>>... | Implement the Python class `SMPayloadTypeINTLIST` described below.
Class description:
List of integer
Method signatures and docstrings:
- def encode(data, opt=None): Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>>... | cf20b363ed3d7bcb75101b17870e876a857ecd66 | <|skeleton|>
class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMPayloadTypeINTLIST:
"""List of integer"""
def encode(data, opt=None):
"""Encode integer list into binary string. :param data: the list to encode :param opt: the encoding option: (integer size, size of the array) :Example: >>> SMPayloadTypeINTLIST.encode([2, 5], opt=(1, 2)) b'\\x02\\x05' >>> SMP... | the_stack_v2_python_sparse | smserver/smutils/smpacket/smencoder.py | Moutix/stepmania-server | train | 4 |
7440e2ba36343186bf83d171d6a27428a081ceb8 | [
"self.kVal = k\nself.heapList = []\nfor num in nums:\n self.add(num)",
"import heapq\nif len(self.heapList) < self.kVal:\n heapq.heappush(self.heapList, val)\nelif val > self.heapList[0]:\n heapq.heappop(self.heapList)\n heapq.heappush(self.heapList, val)\nreturn self.heapList[0]"
] | <|body_start_0|>
self.kVal = k
self.heapList = []
for num in nums:
self.add(num)
<|end_body_0|>
<|body_start_1|>
import heapq
if len(self.heapList) < self.kVal:
heapq.heappush(self.heapList, val)
elif val > self.heapList[0]:
heapq.heap... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.kVal = k
self.heapList = []
for num i... | stack_v2_sparse_classes_36k_train_033505 | 811 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | null | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 234fd3d0e3b09b1bf64e840274b064d0303187e9 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.kVal = k
self.heapList = []
for num in nums:
self.add(num)
def add(self, val):
""":type val: int :rtype: int"""
import heapq
if len(self.heapList) < s... | the_stack_v2_python_sparse | Heap/KthLargestStream.py | vikrant1998/Python-World | train | 0 | |
f1744c1f2f2a0a699275c43486f67a41867c3ddf | [
"dp = [0] * (len(s) + 1)\nstack = []\nres = 0\nfor i, c in enumerate(s):\n if c == '(':\n stack.append(i)\n elif stack:\n pre = stack.pop()\n dp[i + 1] = dp[pre] + 2 + dp[i]\n res = max(res, dp[i + 1])\nreturn res",
"stack = [-1]\nres = 0\nfor i, c in enumerate(s):\n if c == '... | <|body_start_0|>
dp = [0] * (len(s) + 1)
stack = []
res = 0
for i, c in enumerate(s):
if c == '(':
stack.append(i)
elif stack:
pre = stack.pop()
dp[i + 1] = dp[pre] + 2 + dp[i]
res = max(res, dp[i + 1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestValidParentheses1(self, s: str) -> int:
"""思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3."""
<|body_0|>
def longestValidParentheses2(self, s: str) -> int:
"""思路:栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 计算当前i与栈顶元素的距离... | stack_v2_sparse_classes_36k_train_033506 | 1,891 | no_license | [
{
"docstring": "思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的\"(\",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3.",
"name": "longestValidParentheses1",
"signature": "def longestValidParentheses1(self, s: str) -> int"
},
{
"docstring": "思路:栈 1. 栈用来存每一个没有匹配到的\"(\",如果匹配到了就弹出栈 2. 计算当前i与栈顶元素的距离,计算距离最大值",
"nam... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses1(self, s: str) -> int: 思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3.
- def longestValidParentheses2(self, s: str)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestValidParentheses1(self, s: str) -> int: 思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3.
- def longestValidParentheses2(self, s: str)... | e43ee86c5a8cdb808da09b4b6138e10275abadb5 | <|skeleton|>
class Solution:
def longestValidParentheses1(self, s: str) -> int:
"""思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3."""
<|body_0|>
def longestValidParentheses2(self, s: str) -> int:
"""思路:栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 计算当前i与栈顶元素的距离... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestValidParentheses1(self, s: str) -> int:
"""思路:动态规划法+栈 1. 栈用来存每一个没有匹配到的"(",如果匹配到了就弹出栈 2. 动态规划数组用来存储当前字符结尾的字符串,能够成的最大有小括号的长度 3."""
dp = [0] * (len(s) + 1)
stack = []
res = 0
for i, c in enumerate(s):
if c == '(':
stack.appe... | the_stack_v2_python_sparse | LeetCode/动态规划法(dp)/32. 最长有效括号.py | yiming1012/MyLeetCode | train | 2 | |
8ce267f8fa803237e168c068c01fb1538a10e3ca | [
"result = []\n\ndef dfs(root):\n if root == None:\n result.append('null')\n return\n result.append(str(root.val))\n dfs(root.left)\n dfs(root.right)\ndfs(root)\nreturn ','.join(result)",
"array = data.split(',')\n\ndef dfs(array):\n if len(array) == 0:\n return None\n first ... | <|body_start_0|>
result = []
def dfs(root):
if root == None:
result.append('null')
return
result.append(str(root.val))
dfs(root.left)
dfs(root.right)
dfs(root)
return ','.join(result)
<|end_body_0|>
<|body_... | Codec | [
"MIT"
] | 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_033507 | 1,061 | permissive | [
{
"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 | stack_v2_sparse_classes_30k_train_014128 | 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:... | 2faa46323df991a12014021b49d568387a882233 | <|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"""
result = []
def dfs(root):
if root == None:
result.append('null')
return
result.append(str(root.val))
dfs(roo... | the_stack_v2_python_sparse | python-leetcode/297.py | MDGSF/JustCoding | train | 15 | |
539df74661d7365d751f87b8d4ecb71daf943b17 | [
"memo = {}\n\ndef dfs(k, n):\n if (k, n) in memo:\n return memo[k, n]\n if k == 1:\n memo[k, n] = n\n return n\n if n <= 1:\n memo[k, n] = n\n return n\n memo[k, n] = float('inf')\n for i in range(1, n):\n a = dfs(k - 1, i) + 1\n b = dfs(k, n - 1 - i) ... | <|body_start_0|>
memo = {}
def dfs(k, n):
if (k, n) in memo:
return memo[k, n]
if k == 1:
memo[k, n] = n
return n
if n <= 1:
memo[k, n] = n
return n
memo[k, n] = float('inf')
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def superEggDrop(self, K, N):
""":type K: int :type N: int :rtype: int"""
<|body_0|>
def superEggDrop_1(self, K, N):
""":type K: int :type N: int :rtype: int"""
<|body_1|>
def superEggDrop_2(self, K, N):
""":type K: int :type N: int :rt... | stack_v2_sparse_classes_36k_train_033508 | 4,940 | no_license | [
{
"docstring": ":type K: int :type N: int :rtype: int",
"name": "superEggDrop",
"signature": "def superEggDrop(self, K, N)"
},
{
"docstring": ":type K: int :type N: int :rtype: int",
"name": "superEggDrop_1",
"signature": "def superEggDrop_1(self, K, N)"
},
{
"docstring": ":type ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def superEggDrop(self, K, N): :type K: int :type N: int :rtype: int
- def superEggDrop_1(self, K, N): :type K: int :type N: int :rtype: int
- def superEggDrop_2(self, K, N): :typ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def superEggDrop(self, K, N): :type K: int :type N: int :rtype: int
- def superEggDrop_1(self, K, N): :type K: int :type N: int :rtype: int
- def superEggDrop_2(self, K, N): :typ... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def superEggDrop(self, K, N):
""":type K: int :type N: int :rtype: int"""
<|body_0|>
def superEggDrop_1(self, K, N):
""":type K: int :type N: int :rtype: int"""
<|body_1|>
def superEggDrop_2(self, K, N):
""":type K: int :type N: int :rt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def superEggDrop(self, K, N):
""":type K: int :type N: int :rtype: int"""
memo = {}
def dfs(k, n):
if (k, n) in memo:
return memo[k, n]
if k == 1:
memo[k, n] = n
return n
if n <= 1:
... | the_stack_v2_python_sparse | SuperEggDrop_HARD_891.py | 953250587/leetcode-python | train | 2 | |
6f629d586d089cff54e3944f26e4febdf32fd2e5 | [
"super().__init__(coordinator=coordinator)\nself.entity_description = description\nself._attr_unique_id = f'{domain}_{description.key}'\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, domain)}, name=domain, entry_type=DeviceEntryType.SERVICE)\nself._domain = domain",
"if self.coordinator.data is None:\... | <|body_start_0|>
super().__init__(coordinator=coordinator)
self.entity_description = description
self._attr_unique_id = f'{domain}_{description.key}'
self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, domain)}, name=domain, entry_type=DeviceEntryType.SERVICE)
self._domain ... | Implementation of a WHOIS sensor. | WhoisSensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WhoisSensorEntity:
"""Implementation of a WHOIS sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> datetime | ... | stack_v2_sparse_classes_36k_train_033509 | 7,153 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "native_value",
"... | 3 | stack_v2_sparse_classes_30k_train_007913 | Implement the Python class `WhoisSensorEntity` described below.
Class description:
Implementation of a WHOIS sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None: Initialize the sensor.
- def n... | Implement the Python class `WhoisSensorEntity` described below.
Class description:
Implementation of a WHOIS sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None: Initialize the sensor.
- def n... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class WhoisSensorEntity:
"""Implementation of a WHOIS sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None:
"""Initialize the sensor."""
<|body_0|>
def native_value(self) -> datetime | ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WhoisSensorEntity:
"""Implementation of a WHOIS sensor."""
def __init__(self, coordinator: DataUpdateCoordinator[Domain | None], description: WhoisSensorEntityDescription, domain: str) -> None:
"""Initialize the sensor."""
super().__init__(coordinator=coordinator)
self.entity_desc... | the_stack_v2_python_sparse | homeassistant/components/whois/sensor.py | home-assistant/core | train | 35,501 |
3e9c95926a8df140f0c444f9722f7ee5dc46c66b | [
"count = 0\ni = 0\nwhile i < len(nums):\n if nums[i] == 0:\n nums.pop(i)\n count += 1\n else:\n i += 1\nfor i in range(count):\n nums.append(0)",
"count = 0\nfor j in range(len(nums)):\n if nums[j] != 0:\n nums[j - count] = nums[j]\n else:\n count += 1\nfor i in r... | <|body_start_0|>
count = 0
i = 0
while i < len(nums):
if nums[i] == 0:
nums.pop(i)
count += 1
else:
i += 1
for i in range(count):
nums.append(0)
<|end_body_0|>
<|body_start_1|>
count = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_033510 | 911 | no_license | [
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes2",
"signature": "def moveZeroes2(self, nums: List[int]) -> None"
},
{
"docstring": "Do not return anything, modify nums in-place instead.",
"name": "moveZeroes",
"signature": "def moveZeroes(self,... | 2 | stack_v2_sparse_classes_30k_train_012290 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, mod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def moveZeroes2(self, nums: List[int]) -> None: Do not return anything, modify nums in-place instead.
- def moveZeroes(self, nums: List[int]) -> None: Do not return anything, mod... | 3fe8c2298a52a15fadec0693e00445d875c4b6ea | <|skeleton|>
class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_0|>
def moveZeroes(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def moveZeroes2(self, nums: List[int]) -> None:
"""Do not return anything, modify nums in-place instead."""
count = 0
i = 0
while i < len(nums):
if nums[i] == 0:
nums.pop(i)
count += 1
else:
i += ... | the_stack_v2_python_sparse | Move Zeroes.py | huiyi999/leetcode_python | train | 0 | |
aac21bc6b82fbcf733a4267f46594a48050beb09 | [
"super(SimpleTagger, self).__init__()\nself.rnn2seqencoder = rnn2seqencoder\nself.encoding_dim = encoding_dim\nself.datasets_manager = datasets_manager\nself.label_namespace = datasets_manager.label_namespaces[0]\nself.device = device\nself.num_labels = self.datasets_manager.num_labels[self.label_namespace]\nself.l... | <|body_start_0|>
super(SimpleTagger, self).__init__()
self.rnn2seqencoder = rnn2seqencoder
self.encoding_dim = encoding_dim
self.datasets_manager = datasets_manager
self.label_namespace = datasets_manager.label_namespaces[0]
self.device = device
self.num_labels = ... | PyTorch module for Neural Parscit | SimpleTagger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleTagger:
"""PyTorch module for Neural Parscit"""
def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encoding_dim: int, datasets_manager: DatasetsManager, device: torch.device=torch.device('cpu'), label_namespace: str='seq_label'):
"""Parameters ---------- rnn2seqencoder : Lstm2... | stack_v2_sparse_classes_36k_train_033511 | 4,673 | permissive | [
{
"docstring": "Parameters ---------- rnn2seqencoder : Lstm2SeqEncoder Lstm2SeqEncoder that encodes a set of instances to a sequence of hidden states encoding_dim : int Hidden dimension of the lstm2seq encoder",
"name": "__init__",
"signature": "def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encodi... | 2 | stack_v2_sparse_classes_30k_train_012839 | Implement the Python class `SimpleTagger` described below.
Class description:
PyTorch module for Neural Parscit
Method signatures and docstrings:
- def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encoding_dim: int, datasets_manager: DatasetsManager, device: torch.device=torch.device('cpu'), label_namespace: str='... | Implement the Python class `SimpleTagger` described below.
Class description:
PyTorch module for Neural Parscit
Method signatures and docstrings:
- def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encoding_dim: int, datasets_manager: DatasetsManager, device: torch.device=torch.device('cpu'), label_namespace: str='... | 1c061b99a35a9d8b565d9762aaaf5db979b50112 | <|skeleton|>
class SimpleTagger:
"""PyTorch module for Neural Parscit"""
def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encoding_dim: int, datasets_manager: DatasetsManager, device: torch.device=torch.device('cpu'), label_namespace: str='seq_label'):
"""Parameters ---------- rnn2seqencoder : Lstm2... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleTagger:
"""PyTorch module for Neural Parscit"""
def __init__(self, rnn2seqencoder: Lstm2SeqEncoder, encoding_dim: int, datasets_manager: DatasetsManager, device: torch.device=torch.device('cpu'), label_namespace: str='seq_label'):
"""Parameters ---------- rnn2seqencoder : Lstm2SeqEncoder Ls... | the_stack_v2_python_sparse | sciwing/models/simple_tagger.py | abhinavkashyap/sciwing | train | 58 |
18ce7032bfad47c2578f59cb438859d9c6120add | [
"n = len(nums)\nfor i in range(n + 1):\n if i not in nums:\n return i",
"n = len(nums)\nsetNums = set(nums)\nfor i in range(n + 1):\n if i not in setNums:\n return i",
"expectSum = len(nums) * (len(nums) + 1) // 2\nrealSum = sum(nums)\nreturn expectSum - realSum",
"missing = len(nums)\nfor... | <|body_start_0|>
n = len(nums)
for i in range(n + 1):
if i not in nums:
return i
<|end_body_0|>
<|body_start_1|>
n = len(nums)
setNums = set(nums)
for i in range(n + 1):
if i not in setNums:
return i
<|end_body_1|>
<|body_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def missingNumberSum(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_36k_train_033512 | 1,405 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberBruteforce",
"signature": "def missingNumberBruteforce(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "missingNumberHashSet",
"signature": "def missingNumberHashSet(self, nums)"
},
... | 5 | stack_v2_sparse_classes_30k_train_016665 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumberBruteforce(self, nums): :type nums: List[int] :rtype: int
- def missingNumberHashSet(self, nums): :type nums: List[int] :rtype: int
- def missingNumberSum(self, ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def missingNumberBruteforce(self, nums): :type nums: List[int] :rtype: int
- def missingNumberHashSet(self, nums): :type nums: List[int] :rtype: int
- def missingNumberSum(self, ... | a13e7faaf55cd68249267e46a91e93c97e3190c2 | <|skeleton|>
class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def missingNumberSum(self, nums):
""":type nums: List[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def missingNumberBruteforce(self, nums):
""":type nums: List[int] :rtype: int"""
n = len(nums)
for i in range(n + 1):
if i not in nums:
return i
def missingNumberHashSet(self, nums):
""":type nums: List[int] :rtype: int"""
n = ... | the_stack_v2_python_sparse | LeetCode/Array/268.py | xiaojkql/Algorithm-Data-Structure | train | 1 | |
ba9e6a60a395a9118514acefe21a1a677c0c9edd | [
"Message.__init__(self)\nself.passport = command.arguments[0]\nself.friendly_name = unquote(command.arguments[1])\nself.parse(command.payload)",
"message = Message.__str__(self)\ncommand = 'MSG %s %s %u\\r\\n' % (self.passport, quote(self.friendly_name), len(message))\nreturn command + message",
"message = Mess... | <|body_start_0|>
Message.__init__(self)
self.passport = command.arguments[0]
self.friendly_name = unquote(command.arguments[1])
self.parse(command.payload)
<|end_body_0|>
<|body_start_1|>
message = Message.__str__(self)
command = 'MSG %s %s %u\r\n' % (self.passport, quot... | Incoming Message abstraction | IncomingMessage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IncomingMessage:
"""Incoming Message abstraction"""
def __init__(self, command):
"""Initializer @param command: the MSG command received from the server @type command: L{command.Command}"""
<|body_0|>
def __str__(self):
"""Represents the message the representatio... | stack_v2_sparse_classes_36k_train_033513 | 6,280 | no_license | [
{
"docstring": "Initializer @param command: the MSG command received from the server @type command: L{command.Command}",
"name": "__init__",
"signature": "def __init__(self, command)"
},
{
"docstring": "Represents the message the representation looks like this :: MSG sender-passport sender-frien... | 3 | stack_v2_sparse_classes_30k_train_007009 | Implement the Python class `IncomingMessage` described below.
Class description:
Incoming Message abstraction
Method signatures and docstrings:
- def __init__(self, command): Initializer @param command: the MSG command received from the server @type command: L{command.Command}
- def __str__(self): Represents the mess... | Implement the Python class `IncomingMessage` described below.
Class description:
Incoming Message abstraction
Method signatures and docstrings:
- def __init__(self, command): Initializer @param command: the MSG command received from the server @type command: L{command.Command}
- def __str__(self): Represents the mess... | 16043edb5070b0755ed79b0aa02cba399d3d839d | <|skeleton|>
class IncomingMessage:
"""Incoming Message abstraction"""
def __init__(self, command):
"""Initializer @param command: the MSG command received from the server @type command: L{command.Command}"""
<|body_0|>
def __str__(self):
"""Represents the message the representatio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IncomingMessage:
"""Incoming Message abstraction"""
def __init__(self, command):
"""Initializer @param command: the MSG command received from the server @type command: L{command.Command}"""
Message.__init__(self)
self.passport = command.arguments[0]
self.friendly_name = un... | the_stack_v2_python_sparse | pymsn.rewrite/pymsn.rewrite/pymsn/msnp/message.py | Zacchy/nickcheng-python | train | 0 |
6b2c4143a80df5931e14f92675e9c4bdb2ab2741 | [
"super(Attention, self).__init__()\nself.head_num = head_num\nself.head_dim = head_dim\nself.dropout = dropout\nself.attention_pre = fc_block(input_dim, head_dim * head_num * 3)\nself.project = fc_block(head_dim * head_num, output_dim)",
"B, N = x.shape[:2]\nx = x.view(B, N, self.head_num, self.head_dim)\nx = x.p... | <|body_start_0|>
super(Attention, self).__init__()
self.head_num = head_num
self.head_dim = head_dim
self.dropout = dropout
self.attention_pre = fc_block(input_dim, head_dim * head_num * 3)
self.project = fc_block(head_dim * head_num, output_dim)
<|end_body_0|>
<|body_st... | Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward | Attention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward"""
def __init__(self, input_dim: int, head_dim: int, output_dim: int, head_num: int, dropout: nn.Module) -> None:
"""Overv... | stack_v2_sparse_classes_36k_train_033514 | 8,556 | permissive | [
{
"docstring": "Overview: Init attention Arguments: - input_dim (:obj:`int`): dimension of input - head_dim (:obj:`int`): dimension of each head - output_dim (:obj:`int`): dimension of output - head_num (:obj:`int`): head num for multihead attention - dropout (:obj:`nn.Module`): dropout layer",
"name": "__i... | 3 | null | Implement the Python class `Attention` described below.
Class description:
Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward
Method signatures and docstrings:
- def __init__(self, input_dim: int, head_dim: int, output_di... | Implement the Python class `Attention` described below.
Class description:
Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward
Method signatures and docstrings:
- def __init__(self, input_dim: int, head_dim: int, output_di... | eb483fa6e46602d58c8e7d2ca1e566adca28e703 | <|skeleton|>
class Attention:
"""Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward"""
def __init__(self, input_dim: int, head_dim: int, output_dim: int, head_num: int, dropout: nn.Module) -> None:
"""Overv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""Overview: For each entry embedding, compute individual attention across all entries, add them up to get output attention Interfaces: split, forward"""
def __init__(self, input_dim: int, head_dim: int, output_dim: int, head_num: int, dropout: nn.Module) -> None:
"""Overview: Init att... | the_stack_v2_python_sparse | ding/torch_utils/network/transformer.py | shengxuesun/DI-engine | train | 1 |
27d604a83ae906267745675b293a9ec2dfdbae67 | [
"img = self\nself.new_shape = shape\nself.crop_type = crop_type",
"print(image.size)\nold_shape = image.size\nif self.crop_type == 'center':\n return image.crop((old_shape[0] / 2 - self.new_shape[0] / 2, old_shape[1] / 2 - self.new_shape[1] / 2, old_shape[0] / 2 + self.new_shape[0] / 2, old_shape[1] / 2 + self... | <|body_start_0|>
img = self
self.new_shape = shape
self.crop_type = crop_type
<|end_body_0|>
<|body_start_1|>
print(image.size)
old_shape = image.size
if self.crop_type == 'center':
return image.crop((old_shape[0] / 2 - self.new_shape[0] / 2, old_shape[1] / 2... | Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) # Output: (500, 300) | CropImage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CropImage:
"""Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) # Output: (500, 300)"""
def __init... | stack_v2_sparse_classes_36k_train_033515 | 1,571 | no_license | [
{
"docstring": "Arguments: shape: output shape of the crop (h, w) crop_type: center crop or random crop. Default: center",
"name": "__init__",
"signature": "def __init__(self, shape, crop_type='center')"
},
{
"docstring": "Arguments: image (numpy array or PIL image) Returns: image (numpy array o... | 2 | stack_v2_sparse_classes_30k_train_009204 | Implement the Python class `CropImage` described below.
Class description:
Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) ... | Implement the Python class `CropImage` described below.
Class description:
Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) ... | 72b7bf2e02d48012506254fa5b2b9db26aa2a101 | <|skeleton|>
class CropImage:
"""Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) # Output: (500, 300)"""
def __init... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CropImage:
"""Performs either random cropping or center cropping. image = Image.open('demo_image.jpg') box = (200, 300, 700, 600) cropped_image = image.crop(box) cropped_image.save('cropped_image.jpg') # Print size of cropped image print(cropped_image.size) # Output: (500, 300)"""
def __init__(self, shap... | the_stack_v2_python_sparse | my_package/data/transforms/crop.py | aditimishra1290/object-detection-effectiveness | train | 0 |
c0c2b71b8e222b7d45bfff8bbdc6624c6eeeefc4 | [
"if type(N) is not int:\n raise TypeError('N must be int representing number of blocks in the encoder')\nif type(dm) is not int:\n raise TypeError('dm must be int representing dimensionality of model')\nif type(h) is not int:\n raise TypeError('h must be int representing number of heads')\nif type(hidden) ... | <|body_start_0|>
if type(N) is not int:
raise TypeError('N must be int representing number of blocks in the encoder')
if type(dm) is not int:
raise TypeError('dm must be int representing dimensionality of model')
if type(h) is not int:
raise TypeError('h must ... | Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model embedding: the embedding layer for the targets positional_encoding [numpy.... | Decoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Decoder:
"""Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model embedding: the embedding layer for the ... | stack_v2_sparse_classes_36k_train_033516 | 28,983 | no_license | [
{
"docstring": "Class constructor parameters: N [int]: represents the number of blocks in the encoder dm [int]: represents the dimensionality of the model h [int]: represents the number of heads hidden [int]: represents the number of hidden units in fully connected layer target_vocab [int]: represents the size ... | 2 | null | Implement the Python class `Decoder` described below.
Class description:
Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model ... | Implement the Python class `Decoder` described below.
Class description:
Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model ... | 8834b201ca84937365e4dcc0fac978656cdf5293 | <|skeleton|>
class Decoder:
"""Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model embedding: the embedding layer for the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Decoder:
"""Class to create the decoder for a transformer class constructor: def __init__(self, N, dm, h, hidden, target_vocab, max_seq_len, drop_rate=0.1) public instance attribute: N: the number of blocks in the encoder dm: the dimensionality of the model embedding: the embedding layer for the targets posit... | the_stack_v2_python_sparse | supervised_learning/0x12-transformer_apps/5-transformer.py | ejonakodra/holbertonschool-machine_learning-1 | train | 0 |
40515293e198138a3aa045976dead1993bc520f9 | [
"self.archival_target = archival_target\nself.cloud_deploy_target = cloud_deploy_target\nself.environment = environment\nself.job_id = job_id\nself.job_run_id = job_run_id\nself.job_uid = job_uid\nself.point_in_time_usecs = point_in_time_usecs\nself.protection_source_id = protection_source_id\nself.source_name = so... | <|body_start_0|>
self.archival_target = archival_target
self.cloud_deploy_target = cloud_deploy_target
self.environment = environment
self.job_id = job_id
self.job_run_id = job_run_id
self.job_uid = job_uid
self.point_in_time_usecs = point_in_time_usecs
se... | Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular snapshot, you must specify a jobRunId and a startTimeUsecs. If jobRunId and startTimeUs... | RestoreObjectDetails | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreObjectDetails:
"""Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular snapshot, you must specify a jobRunId a... | stack_v2_sparse_classes_36k_train_033517 | 9,602 | permissive | [
{
"docstring": "Constructor for the RestoreObjectDetails class",
"name": "__init__",
"signature": "def __init__(self, archival_target=None, cloud_deploy_target=None, environment=None, job_id=None, job_run_id=None, job_uid=None, point_in_time_usecs=None, protection_source_id=None, source_name=None, start... | 2 | stack_v2_sparse_classes_30k_train_010758 | Implement the Python class `RestoreObjectDetails` described below.
Class description:
Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular ... | Implement the Python class `RestoreObjectDetails` described below.
Class description:
Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreObjectDetails:
"""Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular snapshot, you must specify a jobRunId a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreObjectDetails:
"""Implementation of the 'RestoreObjectDetails' model. Specifies an object to recover or clone or an object to restore files and folders from. A VM object can be recovered or cloned. A View object can be cloned. To specify a particular snapshot, you must specify a jobRunId and a startTim... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_object_details.py | cohesity/management-sdk-python | train | 24 |
037d5658e5e85f09b18e9b0cab84902de5aed6fe | [
"super().__init__()\nassert len(fft_sizes) == len(hop_sizes) == len(win_lengths)\nself.stft_losses = nn.LayerList()\nfor fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):\n self.stft_losses.append(STFTLoss(fs, ss, wl, window))",
"if len(x.shape) == 3:\n x = x.reshape([-1, x.shape[2]])\n y = y.reshape... | <|body_start_0|>
super().__init__()
assert len(fft_sizes) == len(hop_sizes) == len(win_lengths)
self.stft_losses = nn.LayerList()
for fs, ss, wl in zip(fft_sizes, hop_sizes, win_lengths):
self.stft_losses.append(STFTLoss(fs, ss, wl, window))
<|end_body_0|>
<|body_start_1|>
... | Multi resolution STFT loss module. | MultiResolutionSTFTLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_36k_train_033518 | 46,210 | permissive | [
{
"docstring": "Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): List of hop sizes. win_lengths (list): List of window lengths. window (str): Window function type.",
"name": "__init__",
"signature": "def __init__(self, fft_sizes=[1024, 2048, 512]... | 2 | stack_v2_sparse_classes_30k_train_003000 | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | Implement the Python class `MultiResolutionSTFTLoss` described below.
Class description:
Multi resolution STFT loss module.
Method signatures and docstrings:
- def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'): Initialize Multi resolution STFT loss ... | 17854a04d43c231eff66bfed9d6aa55e94a29e79 | <|skeleton|>
class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiResolutionSTFTLoss:
"""Multi resolution STFT loss module."""
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann'):
"""Initialize Multi resolution STFT loss module. Args: fft_sizes (list): List of FFT sizes. hop_sizes (list): L... | the_stack_v2_python_sparse | paddlespeech/t2s/modules/losses.py | anniyanvr/DeepSpeech-1 | train | 0 |
95d4ea44038bcf891ee17dbae1108832826f57e4 | [
"super().__init__(self.SCHEMA_NAME)\nself.redfish['error'] = collections.OrderedDict()\nif code not in config.get_registry_dict()['Base']['Messages']:\n raise OneViewRedfishResourceNotFoundException('Registry {} not found.'.format(code))\nself.redfish['error']['code'] = 'Base.1.1.' + code\nself.redfish['error'][... | <|body_start_0|>
super().__init__(self.SCHEMA_NAME)
self.redfish['error'] = collections.OrderedDict()
if code not in config.get_registry_dict()['Base']['Messages']:
raise OneViewRedfishResourceNotFoundException('Registry {} not found.'.format(code))
self.redfish['error']['cod... | Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against. | RedfishError | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
<|body_0|>
def add_extended_in... | stack_v2_sparse_classes_36k_train_033519 | 4,248 | permissive | [
{
"docstring": "Constructor Populates self.redfish with error message.",
"name": "__init__",
"signature": "def __init__(self, code, message)"
},
{
"docstring": "Adds an item to ExtendedInfo list using values from DMTF registry Adds an item to ExtendedInfo list using the values for Message, Sever... | 2 | stack_v2_sparse_classes_30k_train_006967 | Implement the Python class `RedfishError` described below.
Class description:
Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against.
Method signatures and docstrings:
- def __init__(self, code, message): Constructor Populates self.redfish with erro... | Implement the Python class `RedfishError` described below.
Class description:
Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against.
Method signatures and docstrings:
- def __init__(self, code, message): Constructor Populates self.redfish with erro... | ffc86ea0a9e5d192ab6a2fe21c1717957b55d1da | <|skeleton|>
class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
<|body_0|>
def add_extended_in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RedfishError:
"""Creates a Redfish Error Dict Populates self.redfish with errors. Will not validate as there's no schema to validate against."""
def __init__(self, code, message):
"""Constructor Populates self.redfish with error message."""
super().__init__(self.SCHEMA_NAME)
self.... | the_stack_v2_python_sparse | oneview_redfish_toolkit/api/redfish_error.py | shobhit-sinha/oneview-redfish-toolkit | train | 2 |
f82a28f52997bf523afbd1766e03bab4cdc24687 | [
"obj = self.object\nif pk and obj is None:\n abort(404)\nis_new = pk is None\nform = self.admin_module.get_form(obj)\nreturn render_template(self.admin_module.edit_template, admin=self.admin_module.admin, module=self.admin_module, object=obj, form=form, is_new=is_new)",
"obj = self.object\nif pk and obj is Non... | <|body_start_0|>
obj = self.object
if pk and obj is None:
abort(404)
is_new = pk is None
form = self.admin_module.get_form(obj)
return render_template(self.admin_module.edit_template, admin=self.admin_module.admin, module=self.admin_module, object=obj, form=form, is_n... | Creates or updates object. :param admin_module: The admin module | ObjectFormView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectFormView:
"""Creates or updates object. :param admin_module: The admin module"""
def get(self, pk=None):
"""Displays form. :param pk: The object primary key"""
<|body_0|>
def post(self, pk=None):
"""Process form. :param pk: The object primary key"""
... | stack_v2_sparse_classes_36k_train_033520 | 49,388 | no_license | [
{
"docstring": "Displays form. :param pk: The object primary key",
"name": "get",
"signature": "def get(self, pk=None)"
},
{
"docstring": "Process form. :param pk: The object primary key",
"name": "post",
"signature": "def post(self, pk=None)"
},
{
"docstring": "Gets object requi... | 3 | null | Implement the Python class `ObjectFormView` described below.
Class description:
Creates or updates object. :param admin_module: The admin module
Method signatures and docstrings:
- def get(self, pk=None): Displays form. :param pk: The object primary key
- def post(self, pk=None): Process form. :param pk: The object p... | Implement the Python class `ObjectFormView` described below.
Class description:
Creates or updates object. :param admin_module: The admin module
Method signatures and docstrings:
- def get(self, pk=None): Displays form. :param pk: The object primary key
- def post(self, pk=None): Process form. :param pk: The object p... | 0ac6653219c2701c13c508c5c4fc9bc3437eea06 | <|skeleton|>
class ObjectFormView:
"""Creates or updates object. :param admin_module: The admin module"""
def get(self, pk=None):
"""Displays form. :param pk: The object primary key"""
<|body_0|>
def post(self, pk=None):
"""Process form. :param pk: The object primary key"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectFormView:
"""Creates or updates object. :param admin_module: The admin module"""
def get(self, pk=None):
"""Displays form. :param pk: The object primary key"""
obj = self.object
if pk and obj is None:
abort(404)
is_new = pk is None
form = self.adm... | the_stack_v2_python_sparse | repoData/jeanphix-Flask-Dashed/allPythonContent.py | aCoffeeYin/pyreco | train | 0 |
003fa1f3226cd9b8f73033fce36dd1c0686c611e | [
"self.device = device\nself.check_sensors = check_sensors\nself.data = {}\nself._schema = vol.Schema({vol.Optional('temperature'): vol.Range(min=-50, max=150), vol.Optional('humidity'): vol.Range(min=0, max=100), vol.Optional('light'): vol.Any(0, 1, 2, 3), vol.Optional('air_quality'): vol.Any(0, 1, 2, 3), vol.Optio... | <|body_start_0|>
self.device = device
self.check_sensors = check_sensors
self.data = {}
self._schema = vol.Schema({vol.Optional('temperature'): vol.Range(min=-50, max=150), vol.Optional('humidity'): vol.Range(min=0, max=100), vol.Optional('light'): vol.Any(0, 1, 2, 3), vol.Optional('air_... | Representation of a Broadlink data object. | BroadlinkData | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BroadlinkData:
"""Representation of a Broadlink data object."""
def __init__(self, device, check_sensors, interval):
"""Initialize the data object."""
<|body_0|>
async def _async_fetch_data(self):
"""Fetch sensor data."""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_36k_train_033521 | 5,273 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, device, check_sensors, interval)"
},
{
"docstring": "Fetch sensor data.",
"name": "_async_fetch_data",
"signature": "async def _async_fetch_data(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019135 | Implement the Python class `BroadlinkData` described below.
Class description:
Representation of a Broadlink data object.
Method signatures and docstrings:
- def __init__(self, device, check_sensors, interval): Initialize the data object.
- async def _async_fetch_data(self): Fetch sensor data. | Implement the Python class `BroadlinkData` described below.
Class description:
Representation of a Broadlink data object.
Method signatures and docstrings:
- def __init__(self, device, check_sensors, interval): Initialize the data object.
- async def _async_fetch_data(self): Fetch sensor data.
<|skeleton|>
class Bro... | ba55b4b8338a2dc0ba3f1d750efea49d86571291 | <|skeleton|>
class BroadlinkData:
"""Representation of a Broadlink data object."""
def __init__(self, device, check_sensors, interval):
"""Initialize the data object."""
<|body_0|>
async def _async_fetch_data(self):
"""Fetch sensor data."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BroadlinkData:
"""Representation of a Broadlink data object."""
def __init__(self, device, check_sensors, interval):
"""Initialize the data object."""
self.device = device
self.check_sensors = check_sensors
self.data = {}
self._schema = vol.Schema({vol.Optional('te... | the_stack_v2_python_sparse | homeassistant/components/broadlink/sensor.py | basnijholt/home-assistant | train | 5 |
23bcfbe27df8fbe0148618241a0461d66f82cbe6 | [
"try:\n return Track.query.filter(Track.end == None).one()\nexcept exc.NoResultFound:\n return None",
"if end is None:\n self.end = now()\nelse:\n self.end = end\nlength = self.end - self.begin\nself.title.update_length(length.total_seconds())",
"if begin is None:\n current_track = Track.current_... | <|body_start_0|>
try:
return Track.query.filter(Track.end == None).one()
except exc.NoResultFound:
return None
<|end_body_0|>
<|body_start_1|>
if end is None:
self.end = now()
else:
self.end = end
length = self.end - self.begin
... | Database representation of a Track played in a show | Track | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Track:
"""Database representation of a Track played in a show"""
def current_track():
"""returns the current track (not yet ended)"""
<|body_0|>
def end_track(self, end=None):
"""ends the track and updates length in artist/title DB"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k_train_033522 | 6,033 | permissive | [
{
"docstring": "returns the current track (not yet ended)",
"name": "current_track",
"signature": "def current_track()"
},
{
"docstring": "ends the track and updates length in artist/title DB",
"name": "end_track",
"signature": "def end_track(self, end=None)"
},
{
"docstring": "a... | 3 | stack_v2_sparse_classes_30k_test_000380 | Implement the Python class `Track` described below.
Class description:
Database representation of a Track played in a show
Method signatures and docstrings:
- def current_track(): returns the current track (not yet ended)
- def end_track(self, end=None): ends the track and updates length in artist/title DB
- def new_... | Implement the Python class `Track` described below.
Class description:
Database representation of a Track played in a show
Method signatures and docstrings:
- def current_track(): returns the current track (not yet ended)
- def end_track(self, end=None): ends the track and updates length in artist/title DB
- def new_... | d25ec3f9b49915214d10714260f0d171356e49c5 | <|skeleton|>
class Track:
"""Database representation of a Track played in a show"""
def current_track():
"""returns the current track (not yet ended)"""
<|body_0|>
def end_track(self, end=None):
"""ends the track and updates length in artist/title DB"""
<|body_1|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Track:
"""Database representation of a Track played in a show"""
def current_track():
"""returns the current track (not yet ended)"""
try:
return Track.query.filter(Track.end == None).one()
except exc.NoResultFound:
return None
def end_track(self, end=... | the_stack_v2_python_sparse | lib/rfk/database/track.py | krautradio/PyRfK | train | 2 |
2f6ba4cc20176528312b371586d926ac57a78300 | [
"with self.OutputCapturer():\n print('foo')\n print('bar', file=sys.stderr)\nself.AssertOutputContainsLine('foo')\nself.AssertOutputContainsLine('bar', check_stdout=False, check_stderr=True)",
"with self.OutputCapturer():\n print('foo')\n self.AssertOutputContainsLine('foo')\n print('bar')\n sel... | <|body_start_0|>
with self.OutputCapturer():
print('foo')
print('bar', file=sys.stderr)
self.AssertOutputContainsLine('foo')
self.AssertOutputContainsLine('bar', check_stdout=False, check_stderr=True)
<|end_body_0|>
<|body_start_1|>
with self.OutputCapturer():
... | Tests OutputTestCase functionality. | OutputTestCaseTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputTestCaseTest:
"""Tests OutputTestCase functionality."""
def testStdoutAndStderr(self):
"""Check capturing stdout and stderr."""
<|body_0|>
def testStdoutReadDuringCapture(self):
"""Check reading stdout mid-capture."""
<|body_1|>
def testClearCa... | stack_v2_sparse_classes_36k_train_033523 | 9,390 | permissive | [
{
"docstring": "Check capturing stdout and stderr.",
"name": "testStdoutAndStderr",
"signature": "def testStdoutAndStderr(self)"
},
{
"docstring": "Check reading stdout mid-capture.",
"name": "testStdoutReadDuringCapture",
"signature": "def testStdoutReadDuringCapture(self)"
},
{
... | 5 | stack_v2_sparse_classes_30k_val_000682 | Implement the Python class `OutputTestCaseTest` described below.
Class description:
Tests OutputTestCase functionality.
Method signatures and docstrings:
- def testStdoutAndStderr(self): Check capturing stdout and stderr.
- def testStdoutReadDuringCapture(self): Check reading stdout mid-capture.
- def testClearCaptur... | Implement the Python class `OutputTestCaseTest` described below.
Class description:
Tests OutputTestCase functionality.
Method signatures and docstrings:
- def testStdoutAndStderr(self): Check capturing stdout and stderr.
- def testStdoutReadDuringCapture(self): Check reading stdout mid-capture.
- def testClearCaptur... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class OutputTestCaseTest:
"""Tests OutputTestCase functionality."""
def testStdoutAndStderr(self):
"""Check capturing stdout and stderr."""
<|body_0|>
def testStdoutReadDuringCapture(self):
"""Check reading stdout mid-capture."""
<|body_1|>
def testClearCa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputTestCaseTest:
"""Tests OutputTestCase functionality."""
def testStdoutAndStderr(self):
"""Check capturing stdout and stderr."""
with self.OutputCapturer():
print('foo')
print('bar', file=sys.stderr)
self.AssertOutputContainsLine('foo')
self.As... | the_stack_v2_python_sparse | third_party/chromite/lib/cros_test_lib_unittest.py | metux/chromium-suckless | train | 5 |
c5a93edec66b58d3c40daff13932d93179ebb92d | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | BusGrpcEndpointServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusGrpcEndpointServicer:
"""Missing associated documentation comment in .proto file."""
def GetBus(self, request, context):
"""Bus gets initial data about itself, by id"""
<|body_0|>
def GetFob(self, request, context):
"""Scanner gets Fob MAC Address by NFC ID"""... | stack_v2_sparse_classes_36k_train_033524 | 6,893 | no_license | [
{
"docstring": "Bus gets initial data about itself, by id",
"name": "GetBus",
"signature": "def GetBus(self, request, context)"
},
{
"docstring": "Scanner gets Fob MAC Address by NFC ID",
"name": "GetFob",
"signature": "def GetFob(self, request, context)"
},
{
"docstring": "NFC s... | 4 | stack_v2_sparse_classes_30k_train_000143 | Implement the Python class `BusGrpcEndpointServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetBus(self, request, context): Bus gets initial data about itself, by id
- def GetFob(self, request, context): Scanner gets Fob MAC... | Implement the Python class `BusGrpcEndpointServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def GetBus(self, request, context): Bus gets initial data about itself, by id
- def GetFob(self, request, context): Scanner gets Fob MAC... | b4e238edc0af91ba418873541ef75502a2e1433e | <|skeleton|>
class BusGrpcEndpointServicer:
"""Missing associated documentation comment in .proto file."""
def GetBus(self, request, context):
"""Bus gets initial data about itself, by id"""
<|body_0|>
def GetFob(self, request, context):
"""Scanner gets Fob MAC Address by NFC ID"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BusGrpcEndpointServicer:
"""Missing associated documentation comment in .proto file."""
def GetBus(self, request, context):
"""Bus gets initial data about itself, by id"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise ... | the_stack_v2_python_sparse | Protos/BusGrpcService_pb2_grpc.py | MoviaH5Project/BusScanner | train | 0 |
4f0573037474ae51a9f79fb5c4f1659eaea08c13 | [
"self.reqparser = reqparse.RequestParser()\nself.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])\nself.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])",
"if not get_jwt_claims()['admin']:\n return ({... | <|body_start_0|>
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
self.reqparser.add_argument('id', required=False, store_missing=False, type=str, location=['form', 'json'])
<|end_body_0|>
<|b... | Delete an existing Theme | DeleteTheme | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeleteTheme:
"""Delete an existing Theme"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme ... | stack_v2_sparse_classes_36k_train_033525 | 1,917 | permissive | [
{
"docstring": "Set required arguments for POST request",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme to delete. :type name: str :type id: str :returns: A no content with a... | 2 | stack_v2_sparse_classes_30k_train_014532 | Implement the Python class `DeleteTheme` described below.
Class description:
Delete an existing Theme
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing Theme. :param name: name of Theme to delete. :p... | Implement the Python class `DeleteTheme` described below.
Class description:
Delete an existing Theme
Method signatures and docstrings:
- def __init__(self) -> None: Set required arguments for POST request
- def post(self) -> ({str: str}, HTTPStatus): Delete an existing Theme. :param name: name of Theme to delete. :p... | 5d123691d1f25d0b85e20e4e8293266bf23c9f8a | <|skeleton|>
class DeleteTheme:
"""Delete an existing Theme"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
<|body_0|>
def post(self) -> ({str: str}, HTTPStatus):
"""Delete an existing Theme. :param name: name of Theme to delete. :param id: id of Theme ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeleteTheme:
"""Delete an existing Theme"""
def __init__(self) -> None:
"""Set required arguments for POST request"""
self.reqparser = reqparse.RequestParser()
self.reqparser.add_argument('name', required=False, store_missing=False, type=str, location=['form', 'json'])
sel... | the_stack_v2_python_sparse | Analytics/resources/themes/delete_theme.py | thanosbnt/SharingCitiesDashboard | train | 0 |
7188f4eb39c5c7021e91919d10da159d2f547c47 | [
"kw = super(TaskCreateView, self).get_form_kwargs()\nkw.update({'organization': self.request.user.organization})\nreturn kw",
"self.object = task = form.save(commit=False)\ndiscussion = Discussion.objects.create_discussion('TSK')\ntask.discussion = discussion\ntask.owner = self.request.user\ntask.organization = s... | <|body_start_0|>
kw = super(TaskCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
<|end_body_0|>
<|body_start_1|>
self.object = task = form.save(commit=False)
discussion = Discussion.objects.create_discussion('TSK')
... | Create a new task. | TaskCreateView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskCreateView:
"""Create a new task."""
def get_form_kwargs(self):
"""Pass user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first adding owner and organization."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_033526 | 11,257 | permissive | [
{
"docstring": "Pass user organization to the form.",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self)"
},
{
"docstring": "Save -- but first adding owner and organization.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006385 | Implement the Python class `TaskCreateView` described below.
Class description:
Create a new task.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass user organization to the form.
- def form_valid(self, form): Save -- but first adding owner and organization. | Implement the Python class `TaskCreateView` described below.
Class description:
Create a new task.
Method signatures and docstrings:
- def get_form_kwargs(self): Pass user organization to the form.
- def form_valid(self, form): Save -- but first adding owner and organization.
<|skeleton|>
class TaskCreateView:
"... | dc6bc79d450f7e2bdf59cfbcd306d05a736e4db9 | <|skeleton|>
class TaskCreateView:
"""Create a new task."""
def get_form_kwargs(self):
"""Pass user organization to the form."""
<|body_0|>
def form_valid(self, form):
"""Save -- but first adding owner and organization."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskCreateView:
"""Create a new task."""
def get_form_kwargs(self):
"""Pass user organization to the form."""
kw = super(TaskCreateView, self).get_form_kwargs()
kw.update({'organization': self.request.user.organization})
return kw
def form_valid(self, form):
"... | the_stack_v2_python_sparse | project/editorial/views/tasks.py | ProjectFacet/facet | train | 25 |
5179afe6ede7a587c950a98510231d7f44109f4c | [
"B = zeros((3, 8))\nB[0, 0::2] = B[2, 1::2] = dN[0, :]\nB[1, 1::2] = B[2, 0::2] = dN[1, :]\nreturn B",
"xc = self.xc\ndN0dxi = self.shapegrad(self.cp)\ndx0dxi = dot(dN0dxi, xc)\ndxidx0 = inv(dx0dxi)\nJ0 = det(dx0dxi)\ndNdxi = self.shapegrad(xi)\ndxdxi = dot(dNdxi, xc)\nJ = det(dxdxi)\ndNdxi = array([[-2 * xi[0], ... | <|body_start_0|>
B = zeros((3, 8))
B[0, 0::2] = B[2, 1::2] = dN[0, :]
B[1, 1::2] = B[2, 0::2] = dN[1, :]
return B
<|end_body_0|>
<|body_start_1|>
xc = self.xc
dN0dxi = self.shapegrad(self.cp)
dx0dxi = dot(dN0dxi, xc)
dxidx0 = inv(dx0dxi)
J0 = det(... | PlaneStressQuad4Incompat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlaneStressQuad4Incompat:
def bmatrix(self, dN, *args):
"""Assemble and return the B matrix"""
<|body_0|>
def gmatrix(self, xi):
"""Assemble and return the G matrix"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
B = zeros((3, 8))
B[0, 0::2]... | stack_v2_sparse_classes_36k_train_033527 | 2,067 | no_license | [
{
"docstring": "Assemble and return the B matrix",
"name": "bmatrix",
"signature": "def bmatrix(self, dN, *args)"
},
{
"docstring": "Assemble and return the G matrix",
"name": "gmatrix",
"signature": "def gmatrix(self, xi)"
}
] | 2 | null | Implement the Python class `PlaneStressQuad4Incompat` described below.
Class description:
Implement the PlaneStressQuad4Incompat class.
Method signatures and docstrings:
- def bmatrix(self, dN, *args): Assemble and return the B matrix
- def gmatrix(self, xi): Assemble and return the G matrix | Implement the Python class `PlaneStressQuad4Incompat` described below.
Class description:
Implement the PlaneStressQuad4Incompat class.
Method signatures and docstrings:
- def bmatrix(self, dN, *args): Assemble and return the B matrix
- def gmatrix(self, xi): Assemble and return the G matrix
<|skeleton|>
class Plane... | 9872f6ad1ab15cf0804e41ed22d53c60106d7b16 | <|skeleton|>
class PlaneStressQuad4Incompat:
def bmatrix(self, dN, *args):
"""Assemble and return the B matrix"""
<|body_0|>
def gmatrix(self, xi):
"""Assemble and return the G matrix"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlaneStressQuad4Incompat:
def bmatrix(self, dN, *args):
"""Assemble and return the B matrix"""
B = zeros((3, 8))
B[0, 0::2] = B[2, 1::2] = dN[0, :]
B[1, 1::2] = B[2, 0::2] = dN[1, :]
return B
def gmatrix(self, xi):
"""Assemble and return the G matrix"""
... | the_stack_v2_python_sparse | pyfem2/elemlib/stress_displacement/CSDQ4SI.py | sunhangqi/pyfem2 | train | 0 | |
c89523e3d727e25d00ceafeebffd522ba3fdc5f8 | [
"workspace = Workspace()\nworkspace.owner = owner\nworkspace.data_backend = market_tool_name\nreturn workspace",
"workspace = Workspace()\nworkspace.owner = owner\nworkspace.data_backend = app_name\nreturn workspace"
] | <|body_start_0|>
workspace = Workspace()
workspace.owner = owner
workspace.data_backend = market_tool_name
return workspace
<|end_body_0|>
<|body_start_1|>
workspace = Workspace()
workspace.owner = owner
workspace.data_backend = app_name
return workspace
... | Workspace | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Workspace:
def get_market_tool_workspace(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
<|body_0|>
def get_app_workspace(owner, app_name):
"""app的格式为: app:app1"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
workspace = Works... | stack_v2_sparse_classes_36k_train_033528 | 7,349 | no_license | [
{
"docstring": "market_tool_name的格式为: market_tool:vote",
"name": "get_market_tool_workspace",
"signature": "def get_market_tool_workspace(owner, market_tool_name)"
},
{
"docstring": "app的格式为: app:app1",
"name": "get_app_workspace",
"signature": "def get_app_workspace(owner, app_name)"
... | 2 | null | Implement the Python class `Workspace` described below.
Class description:
Implement the Workspace class.
Method signatures and docstrings:
- def get_market_tool_workspace(owner, market_tool_name): market_tool_name的格式为: market_tool:vote
- def get_app_workspace(owner, app_name): app的格式为: app:app1 | Implement the Python class `Workspace` described below.
Class description:
Implement the Workspace class.
Method signatures and docstrings:
- def get_market_tool_workspace(owner, market_tool_name): market_tool_name的格式为: market_tool:vote
- def get_app_workspace(owner, app_name): app的格式为: app:app1
<|skeleton|>
class W... | 8b2f7befe92841bcc35e0e60cac5958ef3f3af54 | <|skeleton|>
class Workspace:
def get_market_tool_workspace(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
<|body_0|>
def get_app_workspace(owner, app_name):
"""app的格式为: app:app1"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Workspace:
def get_market_tool_workspace(owner, market_tool_name):
"""market_tool_name的格式为: market_tool:vote"""
workspace = Workspace()
workspace.owner = owner
workspace.data_backend = market_tool_name
return workspace
def get_app_workspace(owner, app_name):
... | the_stack_v2_python_sparse | weapp/webapp/models.py | chengdg/weizoom | train | 1 | |
cbd1743975b57d28dc5f6e2395d5fa06232d3228 | [
"gs = GameState.singleton()\nself.gs = gs\ngs.nickname = input('For multiplayer game, enter your nickname (default is single player):')\nif gs.nickname:\n gs.multiplayer = True\n while True:\n new_color_text = input(f\"Choose a color code ({', '.join(list(gs.colors()))}) (default is w):\")\n if ... | <|body_start_0|>
gs = GameState.singleton()
self.gs = gs
gs.nickname = input('For multiplayer game, enter your nickname (default is single player):')
if gs.nickname:
gs.multiplayer = True
while True:
new_color_text = input(f"Choose a color code ({'... | Manager for pygame | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
"""Manager for pygame"""
def __init__(self, maze_filename, host, port):
"""Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in single player mode"""
<|body_0|>
def play(s... | stack_v2_sparse_classes_36k_train_033529 | 3,509 | no_license | [
{
"docstring": "Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in single player mode",
"name": "__init__",
"signature": "def __init__(self, maze_filename, host, port)"
},
{
"docstring": "Main game lo... | 3 | stack_v2_sparse_classes_30k_test_000914 | Implement the Python class `Game` described below.
Class description:
Manager for pygame
Method signatures and docstrings:
- def __init__(self, maze_filename, host, port): Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in... | Implement the Python class `Game` described below.
Class description:
Manager for pygame
Method signatures and docstrings:
- def __init__(self, maze_filename, host, port): Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in... | 7e04ab7158f2c06c1d91962049578407400e944a | <|skeleton|>
class Game:
"""Manager for pygame"""
def __init__(self, maze_filename, host, port):
"""Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in single player mode"""
<|body_0|>
def play(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
"""Manager for pygame"""
def __init__(self, maze_filename, host, port):
"""Initialize the game manager object. Arguments: maze_filename - name of human readable/writable text file containing the maze definition for use in single player mode"""
gs = GameState.singleton()
self... | the_stack_v2_python_sparse | Game.py | jonlmiller/pymaze | train | 0 |
6e01bcb18b9315ebe595372e80afa5dd99e7a85a | [
"res = ''\nfor s in strs:\n res += str(len(s)) + '#' + s\nreturn res",
"ans, i = ([], 0)\nwhile i < len(s):\n j = i\n while s[j] != '#':\n j += 1\n length = int(s[i:j])\n ans.append(s[j + 1:j + 1 + length])\n i = j + 1 + length\nreturn ans"
] | <|body_start_0|>
res = ''
for s in strs:
res += str(len(s)) + '#' + s
return res
<|end_body_0|>
<|body_start_1|>
ans, i = ([], 0)
while i < len(s):
j = i
while s[j] != '#':
j += 1
length = int(s[i:j])
an... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
r... | stack_v2_sparse_classes_36k_train_033530 | 1,981 | no_license | [
{
"docstring": "Encodes a list of strings to a single string.",
"name": "encode",
"signature": "def encode(self, strs: List[str]) -> str"
},
{
"docstring": "Decodes a single string to a list of strings.",
"name": "decode",
"signature": "def decode(self, s: str) -> List[str]"
}
] | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: List[str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> List[str]: Decodes a single string to a list of strings. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def encode(self, strs: List[str]) -> str: Encodes a list of strings to a single string.
- def decode(self, s: str) -> List[str]: Decodes a single string to a list of strings.
<|skelet... | 11c81645893fd65f585c3f558ea837c7dd3cb654 | <|skeleton|>
class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
<|body_0|>
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def encode(self, strs: List[str]) -> str:
"""Encodes a list of strings to a single string."""
res = ''
for s in strs:
res += str(len(s)) + '#' + s
return res
def decode(self, s: str) -> List[str]:
"""Decodes a single string to a list of strings."... | the_stack_v2_python_sparse | LC_Encode_and_Decode_Strings.py | venkatsvpr/Problems_Solved | train | 5 | |
68ddf1e3edc40a50b39790f355964a3bffc6a99c | [
"if component == None:\n return\nif isinstance(component, INotifiable):\n component.notify(correlation_id, args)",
"if components == None:\n return\nargs = args if args != None else Parameters()\nfor component in components:\n Notifier.notify_one(correlation_id, component, args)"
] | <|body_start_0|>
if component == None:
return
if isinstance(component, INotifiable):
component.notify(correlation_id, args)
<|end_body_0|>
<|body_start_1|>
if components == None:
return
args = args if args != None else Parameters()
for compone... | Helper class that notifies components. | Notifier | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notifier:
"""Helper class that notifies components."""
def notify_one(correlation_id, component, args):
"""Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call to this method has no effect. :param correlation_id: (opti... | stack_v2_sparse_classes_36k_train_033531 | 1,769 | permissive | [
{
"docstring": "Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param component: the component that is to be notified. :pa... | 2 | stack_v2_sparse_classes_30k_val_000067 | Implement the Python class `Notifier` described below.
Class description:
Helper class that notifies components.
Method signatures and docstrings:
- def notify_one(correlation_id, component, args): Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call t... | Implement the Python class `Notifier` described below.
Class description:
Helper class that notifies components.
Method signatures and docstrings:
- def notify_one(correlation_id, component, args): Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call t... | 4be674228adcf447c1579cbeb45b7aee89d4322c | <|skeleton|>
class Notifier:
"""Helper class that notifies components."""
def notify_one(correlation_id, component, args):
"""Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call to this method has no effect. :param correlation_id: (opti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Notifier:
"""Helper class that notifies components."""
def notify_one(correlation_id, component, args):
"""Notifies specific component. To be notiied components must implement [[INotifiable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transac... | the_stack_v2_python_sparse | pip_services3_commons/run/Notifier.py | banalna/pip-services3-commons-python | train | 0 |
8f65edd339510786122f5f9c64f1b19380d22dad | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn TeamsAsyncOperation()",
"from .entity import Entity\nfrom .operation_error import OperationError\nfrom .teams_async_operation_status import TeamsAsyncOperationStatus\nfrom .teams_async_operation_type import TeamsAsyncOperationType\nfro... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return TeamsAsyncOperation()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .operation_error import OperationError
from .teams_async_operation_status import TeamsAsyncO... | TeamsAsyncOperation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamsAsyncOperation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamsAsyncOperation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k_train_033532 | 4,777 | 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: TeamsAsyncOperation",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `TeamsAsyncOperation` described below.
Class description:
Implement the TeamsAsyncOperation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamsAsyncOperation: Creates a new instance of the appropriate class based on d... | Implement the Python class `TeamsAsyncOperation` described below.
Class description:
Implement the TeamsAsyncOperation class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamsAsyncOperation: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class TeamsAsyncOperation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamsAsyncOperation:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TeamsAsyncOperation:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> TeamsAsyncOperation:
"""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: ... | the_stack_v2_python_sparse | msgraph/generated/models/teams_async_operation.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a38c3cf7e7be6eedd83fdabd9db652cdf3a7fbce | [
"self.executor_anl = executor_anl\nself.executor_fft = executor_fft\nself.task_config_list = task_config_list\nself.ecei_config = ecei_config\nself.storage_config = storage_config\nself.logger = logging.getLogger('simple')\nself.task_list = []\nfor task_cfg in self.task_config_list:\n self.task_list.append(task_... | <|body_start_0|>
self.executor_anl = executor_anl
self.executor_fft = executor_fft
self.task_config_list = task_config_list
self.ecei_config = ecei_config
self.storage_config = storage_config
self.logger = logging.getLogger('simple')
self.task_list = []
fo... | Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor | task_list_spectral | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class task_list_spectral:
"""Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor"""
def __init__(self, executor_anl, executor_fft, task_config_list, fft_config, ecei_config, storage_config):
"""Initialize the object with a list of tasks to be perfo... | stack_v2_sparse_classes_36k_train_033533 | 12,280 | no_license | [
{
"docstring": "Initialize the object with a list of tasks to be performed. These tasks share a common channel list. Inputs: ======= executor_anl: PEP-3148 executor for running analysis executor_fft: PEP-3148 executor to execute FFTs on. task_list: dict, defines parameters of the analysis to be performed fft_co... | 2 | null | Implement the Python class `task_list_spectral` described below.
Class description:
Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor
Method signatures and docstrings:
- def __init__(self, executor_anl, executor_fft, task_config_list, fft_config, ecei_config, storage_config... | Implement the Python class `task_list_spectral` described below.
Class description:
Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor
Method signatures and docstrings:
- def __init__(self, executor_anl, executor_fft, task_config_list, fft_config, ecei_config, storage_config... | a6bde82bcadd53a79751a9d9982df61f353d6028 | <|skeleton|>
class task_list_spectral:
"""Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor"""
def __init__(self, executor_anl, executor_fft, task_config_list, fft_config, ecei_config, storage_config):
"""Initialize the object with a list of tasks to be perfo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class task_list_spectral:
"""Defines a group of analysis that, together with an FFT, are performed on a PEP-3148 exeecutor"""
def __init__(self, executor_anl, executor_fft, task_config_list, fft_config, ecei_config, storage_config):
"""Initialize the object with a list of tasks to be performed. These t... | the_stack_v2_python_sparse | analysis/tasks_mpi.py | rmchurch/delta | train | 0 |
c72e3503a4db7fc0bf5316211def72edd548268b | [
"UserModel = get_user_model()\nuser = None\nservice = extra_fields.pop('service', 'login')\nencoding = extra_fields.pop('encoding', 'utf-8')\nresetcreds = extra_fields.pop('resetcreds', True)\nlog.debug('request: %s, username: %s, service: %s, encoding: %s, resetcreds: %s, extra_fields: %s', request, username, serv... | <|body_start_0|>
UserModel = get_user_model()
user = None
service = extra_fields.pop('service', 'login')
encoding = extra_fields.pop('encoding', 'utf-8')
resetcreds = extra_fields.pop('resetcreds', True)
log.debug('request: %s, username: %s, service: %s, encoding: %s, res... | An implementation of a PAM backend authentication module. | PAMBackend | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service',... | stack_v2_sparse_classes_36k_train_033534 | 3,567 | permissive | [
{
"docstring": "Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service', 'encoding', and 'resetcreds' can also be passed and will be pulled off the 'extra_fields' kwargs. :param username: The users username. This is a manditory field. :type u... | 2 | stack_v2_sparse_classes_30k_train_003556 | Implement the Python class `PAMBackend` described below.
Class description:
An implementation of a PAM backend authentication module.
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **extra_fields): Authenticate using PAM then get the account if it exists else create ... | Implement the Python class `PAMBackend` described below.
Class description:
An implementation of a PAM backend authentication module.
Method signatures and docstrings:
- def authenticate(self, request, username=None, password=None, **extra_fields): Authenticate using PAM then get the account if it exists else create ... | 0839bb50dbaccdd3e41a067175507ee9bc79f754 | <|skeleton|>
class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service',... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PAMBackend:
"""An implementation of a PAM backend authentication module."""
def authenticate(self, request, username=None, password=None, **extra_fields):
"""Authenticate using PAM then get the account if it exists else create a new account. .. note:: The keyword arguments 'service', 'encoding', ... | the_stack_v2_python_sparse | django_pam/auth/backends.py | cnobile2012/django-pam | train | 14 |
0ebf0cd9e831cb61ab6346fd09200285b76a0de5 | [
"if _debug:\n IOGroup._debug('__init__')\nIOCB.__init__(self)\nself.ioMembers = []\nself.ioState = COMPLETED\nself.ioComplete.set()",
"if _debug:\n IOGroup._debug('Add %r', iocb)\nself.ioMembers.append(iocb)\nself.ioState = PENDING\nself.ioComplete.clear()\niocb.add_callback(self.group_callback)",
"if _de... | <|body_start_0|>
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
<|end_body_0|>
<|body_start_1|>
if _debug:
IOGroup._debug('Add %r', iocb)
self.ioMembers.append(i... | IOGroup | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_36k_train_033535 | 39,489 | permissive | [
{
"docstring": "Initialize a group.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Add an IOCB to the group, you can also add other groups.",
"name": "add",
"signature": "def add(self, iocb)"
},
{
"docstring": "Callback when a child iocb completes.",
... | 4 | stack_v2_sparse_classes_30k_test_000918 | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | Implement the Python class `IOGroup` described below.
Class description:
Implement the IOGroup class.
Method signatures and docstrings:
- def __init__(self): Initialize a group.
- def add(self, iocb): Add an IOCB to the group, you can also add other groups.
- def group_callback(self, iocb): Callback when a child iocb... | a5be2ad5ac69821c12299716b167dd52041b5342 | <|skeleton|>
class IOGroup:
def __init__(self):
"""Initialize a group."""
<|body_0|>
def add(self, iocb):
"""Add an IOCB to the group, you can also add other groups."""
<|body_1|>
def group_callback(self, iocb):
"""Callback when a child iocb completes."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IOGroup:
def __init__(self):
"""Initialize a group."""
if _debug:
IOGroup._debug('__init__')
IOCB.__init__(self)
self.ioMembers = []
self.ioState = COMPLETED
self.ioComplete.set()
def add(self, iocb):
"""Add an IOCB to the group, you can... | the_stack_v2_python_sparse | sandbox/io.py | JoelBender/bacpypes | train | 284 | |
e2eaa97178da69bfb79d5d11dbd118223968cc9e | [
"try:\n grant = Grant.objects.get(pk=pk)\n serializer = GrantsSerializer(grant, context={'request': request})\n return Response(serializer.data)\nexcept Exception as ex:\n return HttpResponseServerError(ex)",
"by_wish = self.request.query_params.get('by_wish')\nrelevant_wish = self.request.user.id\nif... | <|body_start_0|>
try:
grant = Grant.objects.get(pk=pk)
serializer = GrantsSerializer(grant, context={'request': request})
return Response(serializer.data)
except Exception as ex:
return HttpResponseServerError(ex)
<|end_body_0|>
<|body_start_1|>
b... | Grants | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to grants resource Returns: Response -- JSON serialized list of g... | stack_v2_sparse_classes_36k_train_033536 | 4,447 | no_license | [
{
"docstring": "Handle GET requests for single grants Returns: Response -- JSON serialized grants instance",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
},
{
"docstring": "Handle GET requests to grants resource Returns: Response -- JSON serialized list of grants",
... | 6 | stack_v2_sparse_classes_30k_val_000649 | Implement the Python class `Grants` described below.
Class description:
Implement the Grants class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single grants Returns: Response -- JSON serialized grants instance
- def list(self, request): Handle GET requests to gra... | Implement the Python class `Grants` described below.
Class description:
Implement the Grants class.
Method signatures and docstrings:
- def retrieve(self, request, pk=None): Handle GET requests for single grants Returns: Response -- JSON serialized grants instance
- def list(self, request): Handle GET requests to gra... | 582048dafa7e354fffdc0478ec68088e8bbf42b1 | <|skeleton|>
class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
<|body_0|>
def list(self, request):
"""Handle GET requests to grants resource Returns: Response -- JSON serialized list of g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Grants:
def retrieve(self, request, pk=None):
"""Handle GET requests for single grants Returns: Response -- JSON serialized grants instance"""
try:
grant = Grant.objects.get(pk=pk)
serializer = GrantsSerializer(grant, context={'request': request})
return Res... | the_stack_v2_python_sparse | genieioapp/views/grants.py | cherkesky/GenieIO | train | 1 | |
2df042a3935a36de50235b743dbd0d6866562726 | [
"if self.memo.get((first, second), None) is None:\n if m.get(first + second, -1) == -1:\n res = 0\n else:\n res = 1 + self.recursion(second, first + second, m)\n self.memo[first, second] = res\nreturn self.memo[first, second]",
"self.memo = {}\nret = 0\nm = {}\nfor i, num in enumerate(A):\n... | <|body_start_0|>
if self.memo.get((first, second), None) is None:
if m.get(first + second, -1) == -1:
res = 0
else:
res = 1 + self.recursion(second, first + second, m)
self.memo[first, second] = res
return self.memo[first, second]
<|end... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
<|body_0|>
def lenLongestFibSubseq1(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
def lenLongestFibSubseq(self, A):
""":type A:... | stack_v2_sparse_classes_36k_train_033537 | 10,775 | no_license | [
{
"docstring": ":param first: :param second: :type m: dict :return:",
"name": "recursion",
"signature": "def recursion(self, first, second, m)"
},
{
"docstring": ":type A: List[int] :rtype: int",
"name": "lenLongestFibSubseq1",
"signature": "def lenLongestFibSubseq1(self, A)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, second, m): :param first: :param second: :type m: dict :return:
- def lenLongestFibSubseq1(self, A): :type A: List[int] :rtype: int
- def lenLongestFib... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recursion(self, first, second, m): :param first: :param second: :type m: dict :return:
- def lenLongestFibSubseq1(self, A): :type A: List[int] :rtype: int
- def lenLongestFib... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
<|body_0|>
def lenLongestFibSubseq1(self, A):
""":type A: List[int] :rtype: int"""
<|body_1|>
def lenLongestFibSubseq(self, A):
""":type A:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recursion(self, first, second, m):
""":param first: :param second: :type m: dict :return:"""
if self.memo.get((first, second), None) is None:
if m.get(first + second, -1) == -1:
res = 0
else:
res = 1 + self.recursion(second,... | the_stack_v2_python_sparse | python/leetcode/873_Length_of_Longest_Fibonacci_Subsequence.py | bobcaoge/my-code | train | 0 | |
fcf6590c788383e4d5cfada7dcb91097724732ed | [
"config.read(config_path, encoding='utf-8-sig')\nconfig_get = config.get(section, key)\nlog1.info('在section:%s下读取%s的值' % (section, key))\nreturn config_get",
"if key is not None and value is not None:\n config.set(section, key, value)\n log1.info('在section:%s下新增%s=%s' % (section, key, value))\n with open... | <|body_start_0|>
config.read(config_path, encoding='utf-8-sig')
config_get = config.get(section, key)
log1.info('在section:%s下读取%s的值' % (section, key))
return config_get
<|end_body_0|>
<|body_start_1|>
if key is not None and value is not None:
config.set(section, key,... | Config | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Config:
def config_read(section, key):
"""从配置文件中读值"""
<|body_0|>
def config_write(section, key=None, value=None):
"""往配置文件写入"""
<|body_1|>
def config_delete(section, key=None):
"""从配置文件中删除"""
<|body_2|>
def config_options(self, secti... | stack_v2_sparse_classes_36k_train_033538 | 2,581 | no_license | [
{
"docstring": "从配置文件中读值",
"name": "config_read",
"signature": "def config_read(section, key)"
},
{
"docstring": "往配置文件写入",
"name": "config_write",
"signature": "def config_write(section, key=None, value=None)"
},
{
"docstring": "从配置文件中删除",
"name": "config_delete",
"signa... | 5 | stack_v2_sparse_classes_30k_train_013556 | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def config_read(section, key): 从配置文件中读值
- def config_write(section, key=None, value=None): 往配置文件写入
- def config_delete(section, key=None): 从配置文件中删除
- def config_options(self, section... | Implement the Python class `Config` described below.
Class description:
Implement the Config class.
Method signatures and docstrings:
- def config_read(section, key): 从配置文件中读值
- def config_write(section, key=None, value=None): 往配置文件写入
- def config_delete(section, key=None): 从配置文件中删除
- def config_options(self, section... | 5afa8a2220165e0ef749b61e91b31b4b267ea635 | <|skeleton|>
class Config:
def config_read(section, key):
"""从配置文件中读值"""
<|body_0|>
def config_write(section, key=None, value=None):
"""往配置文件写入"""
<|body_1|>
def config_delete(section, key=None):
"""从配置文件中删除"""
<|body_2|>
def config_options(self, secti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Config:
def config_read(section, key):
"""从配置文件中读值"""
config.read(config_path, encoding='utf-8-sig')
config_get = config.get(section, key)
log1.info('在section:%s下读取%s的值' % (section, key))
return config_get
def config_write(section, key=None, value=None):
""... | the_stack_v2_python_sparse | Config/config.py | maomaokeen/pyAutoTest | train | 1 | |
e362dd5dafd06d5923d9e4539d6e07cb4b61cc2c | [
"fields = super(IssueReportAdmin, self).get_fields(request, obj)\nif obj and obj.type != 'duplicate' and ('report_duplicate' in fields):\n fields.remove('report_duplicate')\nreturn fields",
"opts = self.model._meta\npk_value = obj._get_pk_val()\npreserved_filters = self.get_preserved_filters(request)\nredirect... | <|body_start_0|>
fields = super(IssueReportAdmin, self).get_fields(request, obj)
if obj and obj.type != 'duplicate' and ('report_duplicate' in fields):
fields.remove('report_duplicate')
return fields
<|end_body_0|>
<|body_start_1|>
opts = self.model._meta
pk_value = ... | IssueReportAdmin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IssueReportAdmin:
def get_fields(self, request, obj=None):
"""Override to hide the 'usecase_duplicate' if type is not 'duplicate'"""
<|body_0|>
def response_change(self, request, obj, *args, **kwargs):
"""Override response_change method of admin/options.py to handle ... | stack_v2_sparse_classes_36k_train_033539 | 19,598 | no_license | [
{
"docstring": "Override to hide the 'usecase_duplicate' if type is not 'duplicate'",
"name": "get_fields",
"signature": "def get_fields(self, request, obj=None)"
},
{
"docstring": "Override response_change method of admin/options.py to handle the click of newly added buttons",
"name": "resp... | 2 | null | Implement the Python class `IssueReportAdmin` described below.
Class description:
Implement the IssueReportAdmin class.
Method signatures and docstrings:
- def get_fields(self, request, obj=None): Override to hide the 'usecase_duplicate' if type is not 'duplicate'
- def response_change(self, request, obj, *args, **kw... | Implement the Python class `IssueReportAdmin` described below.
Class description:
Implement the IssueReportAdmin class.
Method signatures and docstrings:
- def get_fields(self, request, obj=None): Override to hide the 'usecase_duplicate' if type is not 'duplicate'
- def response_change(self, request, obj, *args, **kw... | d9b330ef70b0d0985bfc8248612ba57ee46ff0f4 | <|skeleton|>
class IssueReportAdmin:
def get_fields(self, request, obj=None):
"""Override to hide the 'usecase_duplicate' if type is not 'duplicate'"""
<|body_0|>
def response_change(self, request, obj, *args, **kwargs):
"""Override response_change method of admin/options.py to handle ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IssueReportAdmin:
def get_fields(self, request, obj=None):
"""Override to hide the 'usecase_duplicate' if type is not 'duplicate'"""
fields = super(IssueReportAdmin, self).get_fields(request, obj)
if obj and obj.type != 'duplicate' and ('report_duplicate' in fields):
fields... | the_stack_v2_python_sparse | Code/ReportWriter-master/report/admin.py | happinesstaker/more-website | train | 0 | |
844d78141475afa1c4b7d0fbb47f475ad833e95c | [
"super().__init__(**kwargs)\nself.update_network = update_network\nself.update_network2 = update_network2",
"graph = graph[:]\nend_atom_index = tf.gather(graph[Index.BOND_ATOM_INDICES][:, 1], graph[Index.TRIPLE_BOND_INDICES][:, 1])\natoms = self.update_network(graph[Index.ATOMS])\natoms = tf.gather(atoms, end_ato... | <|body_start_0|>
super().__init__(**kwargs)
self.update_network = update_network
self.update_network2 = update_network2
<|end_body_0|>
<|body_start_1|>
graph = graph[:]
end_atom_index = tf.gather(graph[Index.BOND_ATOM_INDICES][:, 1], graph[Index.TRIPLE_BOND_INDICES][:, 1])
... | Include 3D interactions to the bond update | ThreeDInteraction | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ThreeDInteraction:
"""Include 3D interactions to the bond update"""
def __init__(self, update_network: tf.keras.layers.Layer, update_network2: tf.keras.layers.Layer, **kwargs):
"""Args: update_network (tf.keras.layers.Layer): keras layer for update the atom attributes before merging ... | stack_v2_sparse_classes_36k_train_033540 | 7,328 | permissive | [
{
"docstring": "Args: update_network (tf.keras.layers.Layer): keras layer for update the atom attributes before merging with 3d interactions update_network2 (tf.keras.layers.Layer): keras layer for update the bond information after merging with 3d interactions **kwargs:",
"name": "__init__",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_019962 | Implement the Python class `ThreeDInteraction` described below.
Class description:
Include 3D interactions to the bond update
Method signatures and docstrings:
- def __init__(self, update_network: tf.keras.layers.Layer, update_network2: tf.keras.layers.Layer, **kwargs): Args: update_network (tf.keras.layers.Layer): k... | Implement the Python class `ThreeDInteraction` described below.
Class description:
Include 3D interactions to the bond update
Method signatures and docstrings:
- def __init__(self, update_network: tf.keras.layers.Layer, update_network2: tf.keras.layers.Layer, **kwargs): Args: update_network (tf.keras.layers.Layer): k... | 1f89ecb564b2691c810cd106c3476b15a8699bb7 | <|skeleton|>
class ThreeDInteraction:
"""Include 3D interactions to the bond update"""
def __init__(self, update_network: tf.keras.layers.Layer, update_network2: tf.keras.layers.Layer, **kwargs):
"""Args: update_network (tf.keras.layers.Layer): keras layer for update the atom attributes before merging ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ThreeDInteraction:
"""Include 3D interactions to the bond update"""
def __init__(self, update_network: tf.keras.layers.Layer, update_network2: tf.keras.layers.Layer, **kwargs):
"""Args: update_network (tf.keras.layers.Layer): keras layer for update the atom attributes before merging with 3d inter... | the_stack_v2_python_sparse | m3gnet/layers/_bond.py | materialsvirtuallab/m3gnet | train | 175 |
2e0cb2cca1caf7eb75d6be0dbca03fdb94325a80 | [
"super(PPO, self).__init__(logger=logger, name=name)\nself.policy = policy\nself.value_function = value_function\nself.p_optimizer = tf.keras.optimizers.Adam(learning_rate=policy_learning_rate)\nself.v_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_learning_rate)\nself.epoch = epoch\nself.batch_size = ba... | <|body_start_0|>
super(PPO, self).__init__(logger=logger, name=name)
self.policy = policy
self.value_function = value_function
self.p_optimizer = tf.keras.optimizers.Adam(learning_rate=policy_learning_rate)
self.v_optimizer = tf.keras.optimizers.Adam(learning_rate=critic_learning... | PPO | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PPO:
def __init__(self, policy, value_function, policy_learning_rate=0.0003, critic_learning_rate=0.0003, epoch=10, batch_size=32, epsilon=0.2, entropy_bonus=0.01, logger=None, name='ppo/'):
"""Creates an optimizer using PPO for training a policy and value function with reinforcement lea... | stack_v2_sparse_classes_36k_train_033541 | 9,469 | no_license | [
{
"docstring": "Creates an optimizer using PPO for training a policy and value function with reinforcement learning Arguments: policy: Distribution a distribution that can be called in order to construct the conditional distribution of the model outputs given inputs value_function: Distribution a distribution t... | 4 | stack_v2_sparse_classes_30k_train_005956 | Implement the Python class `PPO` described below.
Class description:
Implement the PPO class.
Method signatures and docstrings:
- def __init__(self, policy, value_function, policy_learning_rate=0.0003, critic_learning_rate=0.0003, epoch=10, batch_size=32, epsilon=0.2, entropy_bonus=0.01, logger=None, name='ppo/'): Cr... | Implement the Python class `PPO` described below.
Class description:
Implement the PPO class.
Method signatures and docstrings:
- def __init__(self, policy, value_function, policy_learning_rate=0.0003, critic_learning_rate=0.0003, epoch=10, batch_size=32, epsilon=0.2, entropy_bonus=0.01, logger=None, name='ppo/'): Cr... | c8b1ffa94575eb91eb28042c22ce5caf7ff64a54 | <|skeleton|>
class PPO:
def __init__(self, policy, value_function, policy_learning_rate=0.0003, critic_learning_rate=0.0003, epoch=10, batch_size=32, epsilon=0.2, entropy_bonus=0.01, logger=None, name='ppo/'):
"""Creates an optimizer using PPO for training a policy and value function with reinforcement lea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PPO:
def __init__(self, policy, value_function, policy_learning_rate=0.0003, critic_learning_rate=0.0003, epoch=10, batch_size=32, epsilon=0.2, entropy_bonus=0.01, logger=None, name='ppo/'):
"""Creates an optimizer using PPO for training a policy and value function with reinforcement learning Argument... | the_stack_v2_python_sparse | on_policy/algorithms/ppo.py | brandontrabucco/on_policy | train | 0 | |
883249bc722c818afa6852428188d5bd6414be2a | [
"layers_ = list()\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nlayers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))\nmodes = ['concat', 'sum', 'mean', 'prod', 'max', 'min', 'logsumexp', 'el... | <|body_start_0|>
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
modes = ['concat', 'sum'... | Tests MergeLayer. | MergeLayerTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_033542 | 6,335 | permissive | [
{
"docstring": "Test the logic of MergeLayer.",
"name": "test_layer_logic",
"signature": "def test_layer_logic(self)"
},
{
"docstring": "Test the output of MergeLayer with empty layers.",
"name": "test_empty_merge_layer",
"signature": "def test_empty_merge_layer(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000011 | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers. | Implement the Python class `MergeLayerTest` described below.
Class description:
Tests MergeLayer.
Method signatures and docstrings:
- def test_layer_logic(self): Test the logic of MergeLayer.
- def test_empty_merge_layer(self): Test the output of MergeLayer with empty layers.
<|skeleton|>
class MergeLayerTest:
"... | 931ead9222ca90bfc75c3045dc79fb118de340c9 | <|skeleton|>
class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
<|body_0|>
def test_empty_merge_layer(self):
"""Test the output of MergeLayer with empty layers."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MergeLayerTest:
"""Tests MergeLayer."""
def test_layer_logic(self):
"""Test the logic of MergeLayer."""
layers_ = list()
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
layers_.append(nn.Conv1d(in_channels=32, out_channels=32, kernel_size=3))
... | the_stack_v2_python_sparse | texar/torch/core/layers_test.py | panaali/texar-pytorch | train | 1 |
1959b261cb3adba293dd554460287b63056b8576 | [
"if attribute in self.DIRECT_MAPPING_ATTRS:\n return {self.DIRECT_MAPPING_ATTRS[attribute][0]: value if self.DIRECT_MAPPING_ATTRS[attribute][1] is None else self.DIRECT_MAPPING_ATTRS[attribute][1](value)}\nif attribute == 'system_mode':\n if value == self.SystemMode.Off:\n return {HAOZEE_ENABLED_ATTR: ... | <|body_start_0|>
if attribute in self.DIRECT_MAPPING_ATTRS:
return {self.DIRECT_MAPPING_ATTRS[attribute][0]: value if self.DIRECT_MAPPING_ATTRS[attribute][1] is None else self.DIRECT_MAPPING_ATTRS[attribute][1](value)}
if attribute == 'system_mode':
if value == self.SystemMode.Of... | Thermostat cluster for some thermostatic valves. | HY08WEThermostat | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HY08WEThermostat:
"""Thermostat cluster for some thermostatic valves."""
def map_attribute(self, attribute, value):
"""Map standardized attribute value to dict of manufacturer values."""
<|body_0|>
def mode_change(self, value):
"""System Mode change."""
<... | stack_v2_sparse_classes_36k_train_033543 | 11,396 | permissive | [
{
"docstring": "Map standardized attribute value to dict of manufacturer values.",
"name": "map_attribute",
"signature": "def map_attribute(self, attribute, value)"
},
{
"docstring": "System Mode change.",
"name": "mode_change",
"signature": "def mode_change(self, value)"
},
{
"d... | 3 | stack_v2_sparse_classes_30k_train_002348 | Implement the Python class `HY08WEThermostat` described below.
Class description:
Thermostat cluster for some thermostatic valves.
Method signatures and docstrings:
- def map_attribute(self, attribute, value): Map standardized attribute value to dict of manufacturer values.
- def mode_change(self, value): System Mode... | Implement the Python class `HY08WEThermostat` described below.
Class description:
Thermostat cluster for some thermostatic valves.
Method signatures and docstrings:
- def map_attribute(self, attribute, value): Map standardized attribute value to dict of manufacturer values.
- def mode_change(self, value): System Mode... | 84d02be7abde55a6cee80fa155f0cbbc20347c40 | <|skeleton|>
class HY08WEThermostat:
"""Thermostat cluster for some thermostatic valves."""
def map_attribute(self, attribute, value):
"""Map standardized attribute value to dict of manufacturer values."""
<|body_0|>
def mode_change(self, value):
"""System Mode change."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HY08WEThermostat:
"""Thermostat cluster for some thermostatic valves."""
def map_attribute(self, attribute, value):
"""Map standardized attribute value to dict of manufacturer values."""
if attribute in self.DIRECT_MAPPING_ATTRS:
return {self.DIRECT_MAPPING_ATTRS[attribute][0]... | the_stack_v2_python_sparse | zhaquirks/tuya/ts0601_haozee.py | Shulyaka/zha-device-handlers | train | 1 |
09c3844e443721b21298f44464f9c458046392f4 | [
"super(FocalLoss, self).__init__()\nself.size_average = size_average\nif isinstance(alpha, list):\n assert len(alpha) == num_classes\n self.alpha = torch.Tensor(alpha)\nelse:\n assert alpha < 1\n self.alpha = torch.zeros(num_classes)\n self.alpha[0] += alpha\n self.alpha[1:] += 1 - alpha\nself.gam... | <|body_start_0|>
super(FocalLoss, self).__init__()
self.size_average = size_average
if isinstance(alpha, list):
assert len(alpha) == num_classes
self.alpha = torch.Tensor(alpha)
else:
assert alpha < 1
self.alpha = torch.zeros(num_classes)
... | FocalLoss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=53, size_average=True):
"""FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本... | stack_v2_sparse_classes_36k_train_033544 | 2,534 | no_license | [
{
"docstring": "FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainnet中设置为2 :param num_classes: 类别数量 :param size_average: 损失计算方式,默认取均值",
"name": "__i... | 2 | null | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=53, size_average=True): FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,... | Implement the Python class `FocalLoss` described below.
Class description:
Implement the FocalLoss class.
Method signatures and docstrings:
- def __init__(self, alpha=0.25, gamma=2, num_classes=53, size_average=True): FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,... | b60e2b7a8f2ad604c7d28b21498991da60066dc3 | <|skeleton|>
class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=53, size_average=True):
"""FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FocalLoss:
def __init__(self, alpha=0.25, gamma=2, num_classes=53, size_average=True):
"""FocalLoss损失函数, -α(1-yi)**γ *ce_loss(xi,yi) 步骤详细的实现了 focal_loss损失函数. :param alpha: 阿尔法α,类别权重. 当α是列表时,为各类别权重,当α为常数时,类别权重为[α, 1-α, 1-α, ....],常用于 目标检测算法中抑制背景类 , retainnet中设置为0.25 :param gamma: 伽马γ,难易样本调节参数. retainne... | the_stack_v2_python_sparse | BS/networks/focal_loss.py | Nobody0321/MyCodes | train | 0 | |
9b7245bb2a38fc8e5dd4b9ca34587552b5908dda | [
"con_ = sqlite3.connect(DB_SOURCE)\ncur_ = con_.cursor()\ncur_.execute('INSERT INTO data(abs_pressure,\\n delay,\\n hum_in,\\n hum_out,\\n idx,\\n ... | <|body_start_0|>
con_ = sqlite3.connect(DB_SOURCE)
cur_ = con_.cursor()
cur_.execute('INSERT INTO data(abs_pressure,\n delay,\n hum_in,\n hum_out,\n ... | Represents a whether forecast. | Forecast | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Forecast:
"""Represents a whether forecast."""
def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None:
"""Add data to the forecast. :param tagged_data: the data dictionary"""
<|body_0|>
def generate(self, number_of_entries: int) -> None:
"""G... | stack_v2_sparse_classes_36k_train_033545 | 5,044 | permissive | [
{
"docstring": "Add data to the forecast. :param tagged_data: the data dictionary",
"name": "add_data",
"signature": "def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None"
},
{
"docstring": "Generate weather data.",
"name": "generate",
"signature": "def generate(se... | 2 | null | Implement the Python class `Forecast` described below.
Class description:
Represents a whether forecast.
Method signatures and docstrings:
- def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None: Add data to the forecast. :param tagged_data: the data dictionary
- def generate(self, number_of_ent... | Implement the Python class `Forecast` described below.
Class description:
Represents a whether forecast.
Method signatures and docstrings:
- def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None: Add data to the forecast. :param tagged_data: the data dictionary
- def generate(self, number_of_ent... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class Forecast:
"""Represents a whether forecast."""
def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None:
"""Add data to the forecast. :param tagged_data: the data dictionary"""
<|body_0|>
def generate(self, number_of_entries: int) -> None:
"""G... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Forecast:
"""Represents a whether forecast."""
def add_data(tagged_data: Dict[str, Union[int, datetime.datetime]]) -> None:
"""Add data to the forecast. :param tagged_data: the data dictionary"""
con_ = sqlite3.connect(DB_SOURCE)
cur_ = con_.cursor()
cur_.execute('INSERT I... | the_stack_v2_python_sparse | packages/fetchai/skills/weather_station/dummy_weather_station_data.py | fetchai/agents-aea | train | 192 |
555ff7e75e6a06ccfb454c2367fd443e236d6063 | [
"super(PostProcessor, self).__init__()\nself.score_thresh = score_thresh\nself.nms = nms\nself.detections_per_img = detections_per_img\nif box_coder is None:\n box_coder = BoxCoder(weights=(10.0, 10.0, 5.0, 5.0))\nself.box_coder = box_coder\nself.cls_agnostic_bbox_reg = cls_agnostic_bbox_reg\nself.is_repeat = is... | <|body_start_0|>
super(PostProcessor, self).__init__()
self.score_thresh = score_thresh
self.nms = nms
self.detections_per_img = detections_per_img
if box_coder is None:
box_coder = BoxCoder(weights=(10.0, 10.0, 5.0, 5.0))
self.box_coder = box_coder
se... | From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results | PostProcessor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, detections_per_img=100, box_coder=None, cls_agnostic_bbox_reg=False, is_repeat... | stack_v2_sparse_classes_36k_train_033546 | 7,503 | permissive | [
{
"docstring": "Arguments: score_thresh (float) nms (float) detections_per_img (int) box_coder (BoxCoder)",
"name": "__init__",
"signature": "def __init__(self, score_thresh=0.05, nms=0.5, detections_per_img=100, box_coder=None, cls_agnostic_bbox_reg=False, is_repeat=False)"
},
{
"docstring": "A... | 6 | stack_v2_sparse_classes_30k_train_006726 | Implement the Python class `PostProcessor` described below.
Class description:
From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results
Method signatures and docstrings:
- def __init__(self, score_thresh=0.05, nms=0.5, detections... | Implement the Python class `PostProcessor` described below.
Class description:
From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results
Method signatures and docstrings:
- def __init__(self, score_thresh=0.05, nms=0.5, detections... | a0c9ed8850abe740eedf8bfc6e1577cc0aa3fc7b | <|skeleton|>
class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, detections_per_img=100, box_coder=None, cls_agnostic_bbox_reg=False, is_repeat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PostProcessor:
"""From a set of classification scores, box regression and proposals, computes the post-processed boxes, and applies NMS to obtain the final results"""
def __init__(self, score_thresh=0.05, nms=0.5, detections_per_img=100, box_coder=None, cls_agnostic_bbox_reg=False, is_repeat=False):
... | the_stack_v2_python_sparse | rcnn/modeling/cascade_rcnn/inference.py | rs9899/Parsing-R-CNN | train | 0 |
e71978c5e927b461b1e23b6e32d2d10885e7ba2f | [
"self.distribution = distribution\nself.d = self.distribution.dimension\nif isscalar(lower_bound):\n lower_bound = tile(lower_bound, self.d)\nif isscalar(upper_bound):\n upper_bound = tile(upper_bound, self.d)\nself.lower_bound = array(lower_bound)\nself.upper_bound = array(upper_bound)\nif len(self.lower_bou... | <|body_start_0|>
self.distribution = distribution
self.d = self.distribution.dimension
if isscalar(lower_bound):
lower_bound = tile(lower_bound, self.d)
if isscalar(upper_bound):
upper_bound = tile(upper_bound, self.d)
self.lower_bound = array(lower_bound)... | >>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -inf] upper_bound [inf inf] | Lebesgue | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lebesgue:
""">>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -inf] upper_bound [inf inf]"""
def ... | stack_v2_sparse_classes_36k_train_033547 | 3,880 | permissive | [
{
"docstring": "Args: distribution (DiscreteDistribution): DiscreteDistribution instance lower_bound (float or inf): lower bound of integration upper_bound (float or inf): upper bound of integration",
"name": "__init__",
"signature": "def __init__(self, distribution, lower_bound=0.0, upper_bound=1.0)"
... | 3 | stack_v2_sparse_classes_30k_train_001164 | Implement the Python class `Lebesgue` described below.
Class description:
>>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -... | Implement the Python class `Lebesgue` described below.
Class description:
>>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -... | 0ed9da2f10b9ac0004c993c01392b4c86002954c | <|skeleton|>
class Lebesgue:
""">>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -inf] upper_bound [inf inf]"""
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lebesgue:
""">>> dd = Sobol(2,seed=7) >>> Lebesgue(dd,lower_bound=[-1,0],upper_bound=[1,3]) Lebesgue (TrueMeasure Object) lower_bound [-1 0] upper_bound [1 3] >>> Lebesgue(dd,lower_bound=-inf,upper_bound=inf) Lebesgue (TrueMeasure Object) lower_bound [-inf -inf] upper_bound [inf inf]"""
def __init__(self... | the_stack_v2_python_sparse | qmcpy/true_measure/lebesgue.py | kachiann/QMCSoftware | train | 1 |
c5effd7aad9e33598eff7a4e2c8e47736781c1d6 | [
"reporting_entities = filter(self.is_entity_reporting, file.values())\nfiltered = filter(self.is_entity_canonical, reporting_entities) if exclude_noncanonical else reporting_entities\nreturn [entity.cloud_device_id for entity in filtered]",
"virtual_entities = filter(self.is_entity_virtual, file.values())\nfilter... | <|body_start_0|>
reporting_entities = filter(self.is_entity_reporting, file.values())
filtered = filter(self.is_entity_canonical, reporting_entities) if exclude_noncanonical else reporting_entities
return [entity.cloud_device_id for entity in filtered]
<|end_body_0|>
<|body_start_1|>
vi... | Quantifies whether the correct entities were included in the proposed file. | EntityIdentification | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EntityIdentification:
"""Quantifies whether the correct entities were included in the proposed file."""
def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]:
"""Generates list of `cloud_device_id`s representing reporting entities... | stack_v2_sparse_classes_36k_train_033548 | 3,656 | permissive | [
{
"docstring": "Generates list of `cloud_device_id`s representing reporting entities.",
"name": "_list_ids_reporting",
"signature": "def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]"
},
{
"docstring": "Generates list of `cloud_device_id`... | 3 | null | Implement the Python class `EntityIdentification` described below.
Class description:
Quantifies whether the correct entities were included in the proposed file.
Method signatures and docstrings:
- def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]: Generates l... | Implement the Python class `EntityIdentification` described below.
Class description:
Quantifies whether the correct entities were included in the proposed file.
Method signatures and docstrings:
- def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]: Generates l... | 0ffe5b61769143826142da4bada3c712b1fd0222 | <|skeleton|>
class EntityIdentification:
"""Quantifies whether the correct entities were included in the proposed file."""
def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]:
"""Generates list of `cloud_device_id`s representing reporting entities... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EntityIdentification:
"""Quantifies whether the correct entities were included in the proposed file."""
def _list_ids_reporting(self, *, file: DeserializedFile, exclude_noncanonical: bool) -> List[CloudDeviceId]:
"""Generates list of `cloud_device_id`s representing reporting entities."""
... | the_stack_v2_python_sparse | tools/scoring/score/dimensions/entity_identification.py | google/digitalbuildings | train | 319 |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(VggSubsampling, self).__init__()\ncur_channels = 1\nlayers = []\nblock_dims = [32, 64]\nfor block_dim in block_dims:\n layers.append(torch.nn.Conv2d(in_channels=cur_channels, out_channels=block_dim, kernel_size=3, padding=1, stride=1))\n layers.append(torch.nn.ReLU())\n layers.append(torch.nn.Conv2d... | <|body_start_0|>
super(VggSubsampling, self).__init__()
cur_channels = 1
layers = []
block_dims = [32, 64]
for block_dim in block_dims:
layers.append(torch.nn.Conv2d(in_channels=cur_channels, out_channels=block_dim, kernel_size=3, padding=1, stride=1))
lay... | Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension. | VggSubsampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, ... | stack_v2_sparse_classes_36k_train_033549 | 33,189 | permissive | [
{
"docstring": "Construct a VggSubsampling object. This uses 2 VGG blocks with 2 Conv2d layers each, subsampling its input by a factor of 4 in the time dimensions. Args: idim: Number of features at input, e.g. 40 or 80 for MFCC (will be treated as the image height). odim: Output dimension (number of features), ... | 2 | stack_v2_sparse_classes_30k_train_007779 | Implement the Python class `VggSubsampling` described below.
Class description:
Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output... | Implement the Python class `VggSubsampling` described below.
Class description:
Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, idim: int, od... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
a3f2d25f3f2b1ac2460ae2abab83bec781fafa12 | [
"email = get_jwt_identity()\nif state == 'active':\n cond = {'$and': [{'$eq': ['$$task.meta.is_archived', False]}, {'$eq': ['$$task.meta.is_deleted', False]}]}\nelif state == 'archived':\n cond = {'$and': [{'$eq': ['$$task.meta.is_archived', True]}, {'$eq': ['$$task.meta.is_deleted', False]}]}\nelif state == ... | <|body_start_0|>
email = get_jwt_identity()
if state == 'active':
cond = {'$and': [{'$eq': ['$$task.meta.is_archived', False]}, {'$eq': ['$$task.meta.is_deleted', False]}]}
elif state == 'archived':
cond = {'$and': [{'$eq': ['$$task.meta.is_archived', True]}, {'$eq': ['$$... | Tasks Service | TasksService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TasksService:
"""Tasks Service"""
def get_tasks(self, id, state):
"""Get Tasks list :param id: :return:"""
<|body_0|>
def create_task(self, id, payload):
"""Create a task in task room :param payload: :return:"""
<|body_1|>
def update_task(self, taskr... | stack_v2_sparse_classes_36k_train_033550 | 4,050 | no_license | [
{
"docstring": "Get Tasks list :param id: :return:",
"name": "get_tasks",
"signature": "def get_tasks(self, id, state)"
},
{
"docstring": "Create a task in task room :param payload: :return:",
"name": "create_task",
"signature": "def create_task(self, id, payload)"
},
{
"docstrin... | 6 | stack_v2_sparse_classes_30k_train_020713 | Implement the Python class `TasksService` described below.
Class description:
Tasks Service
Method signatures and docstrings:
- def get_tasks(self, id, state): Get Tasks list :param id: :return:
- def create_task(self, id, payload): Create a task in task room :param payload: :return:
- def update_task(self, taskroom_... | Implement the Python class `TasksService` described below.
Class description:
Tasks Service
Method signatures and docstrings:
- def get_tasks(self, id, state): Get Tasks list :param id: :return:
- def create_task(self, id, payload): Create a task in task room :param payload: :return:
- def update_task(self, taskroom_... | 075cd9a9faaa2d24f1c7ea8507c115e6936aed04 | <|skeleton|>
class TasksService:
"""Tasks Service"""
def get_tasks(self, id, state):
"""Get Tasks list :param id: :return:"""
<|body_0|>
def create_task(self, id, payload):
"""Create a task in task room :param payload: :return:"""
<|body_1|>
def update_task(self, taskr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TasksService:
"""Tasks Service"""
def get_tasks(self, id, state):
"""Get Tasks list :param id: :return:"""
email = get_jwt_identity()
if state == 'active':
cond = {'$and': [{'$eq': ['$$task.meta.is_archived', False]}, {'$eq': ['$$task.meta.is_deleted', False]}]}
... | the_stack_v2_python_sparse | app/task_rooms/tasks/service.py | nosqlly/Todo-App | train | 3 |
1559636107666f7d3c3cccd3788e9d7957d84276 | [
"unittest_lib.BuildELF(os.path.join(self.tempdir, 'liba.so'), ['func_a'])\nelf = parseelf.ParseELF(self.tempdir, 'liba.so', self._ldpaths)\nself.assertTrue('is_lib' in elf)\nself.assertTrue(elf['is_lib'])",
"unittest_lib.BuildELF(os.path.join(self.tempdir, 'abc_main'), executable=True)\nelf = parseelf.ParseELF(se... | <|body_start_0|>
unittest_lib.BuildELF(os.path.join(self.tempdir, 'liba.so'), ['func_a'])
elf = parseelf.ParseELF(self.tempdir, 'liba.so', self._ldpaths)
self.assertTrue('is_lib' in elf)
self.assertTrue(elf['is_lib'])
<|end_body_0|>
<|body_start_1|>
unittest_lib.BuildELF(os.path... | Test the ELF parsing functions. | ELFParsingTest | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ELFParsingTest:
"""Test the ELF parsing functions."""
def testIsLib(self):
"""Tests the 'is_lib' attribute is inferred correctly for libs."""
<|body_0|>
def testNotIsLib(self):
"""Tests the 'is_lib' attribute is inferred correctly for executables."""
<|bo... | stack_v2_sparse_classes_36k_train_033551 | 4,985 | permissive | [
{
"docstring": "Tests the 'is_lib' attribute is inferred correctly for libs.",
"name": "testIsLib",
"signature": "def testIsLib(self)"
},
{
"docstring": "Tests the 'is_lib' attribute is inferred correctly for executables.",
"name": "testNotIsLib",
"signature": "def testNotIsLib(self)"
... | 6 | null | Implement the Python class `ELFParsingTest` described below.
Class description:
Test the ELF parsing functions.
Method signatures and docstrings:
- def testIsLib(self): Tests the 'is_lib' attribute is inferred correctly for libs.
- def testNotIsLib(self): Tests the 'is_lib' attribute is inferred correctly for executa... | Implement the Python class `ELFParsingTest` described below.
Class description:
Test the ELF parsing functions.
Method signatures and docstrings:
- def testIsLib(self): Tests the 'is_lib' attribute is inferred correctly for libs.
- def testNotIsLib(self): Tests the 'is_lib' attribute is inferred correctly for executa... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ELFParsingTest:
"""Test the ELF parsing functions."""
def testIsLib(self):
"""Tests the 'is_lib' attribute is inferred correctly for libs."""
<|body_0|>
def testNotIsLib(self):
"""Tests the 'is_lib' attribute is inferred correctly for executables."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ELFParsingTest:
"""Test the ELF parsing functions."""
def testIsLib(self):
"""Tests the 'is_lib' attribute is inferred correctly for libs."""
unittest_lib.BuildELF(os.path.join(self.tempdir, 'liba.so'), ['func_a'])
elf = parseelf.ParseELF(self.tempdir, 'liba.so', self._ldpaths)
... | the_stack_v2_python_sparse | third_party/chromite/lib/parseelf_unittest.py | metux/chromium-suckless | train | 5 |
fb7df2b147e1e8ffc4028df0dc5583196d0efad8 | [
"self.__name = _os.path.basename(path)\nself.__data = []\nfor name in _os.listdir(path):\n path_name = _os.path.join(path, name)\n if _os.path.isdir(path_name):\n self.__data.append(Directory(path_name))\n elif _os.path.isfile(path_name):\n self.__data.append(File(path_name))",
"if self.__n... | <|body_start_0|>
self.__name = _os.path.basename(path)
self.__data = []
for name in _os.listdir(path):
path_name = _os.path.join(path, name)
if _os.path.isdir(path_name):
self.__data.append(Directory(path_name))
elif _os.path.isfile(path_name):... | Directory(path) -> Directory | Directory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Directory:
"""Directory(path) -> Directory"""
def __init__(self, path):
"""Initialize the Directory object."""
<|body_0|>
def write(self, path):
"""Write directory to path."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.__name = _os.path.b... | stack_v2_sparse_classes_36k_train_033552 | 1,638 | no_license | [
{
"docstring": "Initialize the Directory object.",
"name": "__init__",
"signature": "def __init__(self, path)"
},
{
"docstring": "Write directory to path.",
"name": "write",
"signature": "def write(self, path)"
}
] | 2 | null | Implement the Python class `Directory` described below.
Class description:
Directory(path) -> Directory
Method signatures and docstrings:
- def __init__(self, path): Initialize the Directory object.
- def write(self, path): Write directory to path. | Implement the Python class `Directory` described below.
Class description:
Directory(path) -> Directory
Method signatures and docstrings:
- def __init__(self, path): Initialize the Directory object.
- def write(self, path): Write directory to path.
<|skeleton|>
class Directory:
"""Directory(path) -> Directory"""... | 45837fc39f99b5f7f69919ed2f6732e6b7bec936 | <|skeleton|>
class Directory:
"""Directory(path) -> Directory"""
def __init__(self, path):
"""Initialize the Directory object."""
<|body_0|>
def write(self, path):
"""Write directory to path."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Directory:
"""Directory(path) -> Directory"""
def __init__(self, path):
"""Initialize the Directory object."""
self.__name = _os.path.basename(path)
self.__data = []
for name in _os.listdir(path):
path_name = _os.path.join(path, name)
if _os.path.is... | the_stack_v2_python_sparse | Python 2.X/ZERO/GUI/Archive/Version 1/cap.py | jacobbridges/my-chaos | train | 0 |
97aa8ccfe2a562375b70c38f76d9a77453d46f2d | [
"self.job_type = job_type\nself.project = project\nself.location = location\nself.gcp_resources = gcp_resources\nself.client_options = {'api_endpoint': location + '-aiplatform.googleapis.com'}\nself.client_info = gapic_v1.client_info.ClientInfo(user_agent='google-cloud-pipeline-components')\nself.job_client = aipla... | <|body_start_0|>
self.job_type = job_type
self.project = project
self.location = location
self.gcp_resources = gcp_resources
self.client_options = {'api_endpoint': location + '-aiplatform.googleapis.com'}
self.client_info = gapic_v1.client_info.ClientInfo(user_agent='goog... | Common module for creating and poll jobs on the Vertex Platform. | JobRemoteRunner | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobRemoteRunner:
"""Common module for creating and poll jobs on the Vertex Platform."""
def __init__(self, job_type, project, location, gcp_resources):
"""Initlizes a job client and other common attributes."""
<|body_0|>
def check_if_job_exists(self) -> Optional[str]:
... | stack_v2_sparse_classes_36k_train_033553 | 6,426 | permissive | [
{
"docstring": "Initlizes a job client and other common attributes.",
"name": "__init__",
"signature": "def __init__(self, job_type, project, location, gcp_resources)"
},
{
"docstring": "Check if the job already exists.",
"name": "check_if_job_exists",
"signature": "def check_if_job_exis... | 4 | stack_v2_sparse_classes_30k_train_005768 | Implement the Python class `JobRemoteRunner` described below.
Class description:
Common module for creating and poll jobs on the Vertex Platform.
Method signatures and docstrings:
- def __init__(self, job_type, project, location, gcp_resources): Initlizes a job client and other common attributes.
- def check_if_job_e... | Implement the Python class `JobRemoteRunner` described below.
Class description:
Common module for creating and poll jobs on the Vertex Platform.
Method signatures and docstrings:
- def __init__(self, job_type, project, location, gcp_resources): Initlizes a job client and other common attributes.
- def check_if_job_e... | 73804f8928ce671839d34800627b6d3ea9f820a7 | <|skeleton|>
class JobRemoteRunner:
"""Common module for creating and poll jobs on the Vertex Platform."""
def __init__(self, job_type, project, location, gcp_resources):
"""Initlizes a job client and other common attributes."""
<|body_0|>
def check_if_job_exists(self) -> Optional[str]:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobRemoteRunner:
"""Common module for creating and poll jobs on the Vertex Platform."""
def __init__(self, job_type, project, location, gcp_resources):
"""Initlizes a job client and other common attributes."""
self.job_type = job_type
self.project = project
self.location =... | the_stack_v2_python_sparse | components/google-cloud/google_cloud_pipeline_components/container/experimental/gcp_launcher/job_remote_runner.py | NikeNano/pipelines | train | 1 |
4b1bb7bb46dc83b5312d2116b49f0b1aacea8a9a | [
"dist_utils.validate_callbacks(input_callbacks=callbacks, optimizer=model.optimizer)\ndist_utils.validate_inputs(x, y)\nbatch_size, steps_per_epoch = dist_utils.process_batch_and_step_size(model._distribution_strategy, x, batch_size, steps_per_epoch, ModeKeys.TRAIN, validation_split=validation_split)\nbatch_size = ... | <|body_start_0|>
dist_utils.validate_callbacks(input_callbacks=callbacks, optimizer=model.optimizer)
dist_utils.validate_inputs(x, y)
batch_size, steps_per_epoch = dist_utils.process_batch_and_step_size(model._distribution_strategy, x, batch_size, steps_per_epoch, ModeKeys.TRAIN, validation_spli... | Training loop for distribution strategy with single worker. | DistributionSingleWorkerTrainingLoop | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DistributionSingleWorkerTrainingLoop:
"""Training loop for distribution strategy with single worker."""
def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, ... | stack_v2_sparse_classes_36k_train_033554 | 29,780 | permissive | [
{
"docstring": "Fit loop for Distribution Strategies.",
"name": "fit",
"signature": "def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoc... | 3 | null | Implement the Python class `DistributionSingleWorkerTrainingLoop` described below.
Class description:
Training loop for distribution strategy with single worker.
Method signatures and docstrings:
- def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validat... | Implement the Python class `DistributionSingleWorkerTrainingLoop` described below.
Class description:
Training loop for distribution strategy with single worker.
Method signatures and docstrings:
- def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validat... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class DistributionSingleWorkerTrainingLoop:
"""Training loop for distribution strategy with single worker."""
def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DistributionSingleWorkerTrainingLoop:
"""Training loop for distribution strategy with single worker."""
def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch... | the_stack_v2_python_sparse | tensorflow/python/keras/engine/training_distributed_v1.py | tensorflow/tensorflow | train | 208,740 |
288a7a869273e2890ad9a830660f26a62ebe3230 | [
"await self._async_send_command(self._power_on_command)\nself._attr_is_on = True\nself.async_write_ha_state()",
"await self._async_send_command(self._power_off_command)\nself._attr_is_on = False\nself.async_write_ha_state()",
"if len(status) != 4:\n return\nstate = status[0]\nself._attr_is_on = state == '1'"... | <|body_start_0|>
await self._async_send_command(self._power_on_command)
self._attr_is_on = True
self.async_write_ha_state()
<|end_body_0|>
<|body_start_1|>
await self._async_send_command(self._power_off_command)
self._attr_is_on = False
self.async_write_ha_state()
<|end_... | A lookin IR controlled light. | LookinLightEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LookinLightEntity:
"""A lookin IR controlled light."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
<|body_0|>
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
<|body_1|>
def _update_f... | stack_v2_sparse_classes_36k_train_033555 | 2,281 | permissive | [
{
"docstring": "Turn on the light.",
"name": "async_turn_on",
"signature": "async def async_turn_on(self, **kwargs: Any) -> None"
},
{
"docstring": "Turn off the light.",
"name": "async_turn_off",
"signature": "async def async_turn_off(self, **kwargs: Any) -> None"
},
{
"docstrin... | 3 | null | Implement the Python class `LookinLightEntity` described below.
Class description:
A lookin IR controlled light.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn on the light.
- async def async_turn_off(self, **kwargs: Any) -> None: Turn off the light.
- def _update_from_... | Implement the Python class `LookinLightEntity` described below.
Class description:
A lookin IR controlled light.
Method signatures and docstrings:
- async def async_turn_on(self, **kwargs: Any) -> None: Turn on the light.
- async def async_turn_off(self, **kwargs: Any) -> None: Turn off the light.
- def _update_from_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class LookinLightEntity:
"""A lookin IR controlled light."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
<|body_0|>
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
<|body_1|>
def _update_f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LookinLightEntity:
"""A lookin IR controlled light."""
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
await self._async_send_command(self._power_on_command)
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(se... | the_stack_v2_python_sparse | homeassistant/components/lookin/light.py | home-assistant/core | train | 35,501 |
802813e5f6e7a39f62c285e7e3d269f48a2b3a6f | [
"BaseType.__init__(self, cle)\nself.efficacite = 30\nself.etendre_editeur('f', 'efficacite', Entier, self, 'efficacite', 1, 50)",
"efficacite = enveloppes['f']\nefficacite.apercu = '{objet.efficacite}'\nefficacite.prompt = 'Entrez une efficacité : '\nefficacite.aide_courte = \"Entrez l'|ent|efficacité|ff| initial... | <|body_start_0|>
BaseType.__init__(self, cle)
self.efficacite = 30
self.etendre_editeur('f', 'efficacite', Entier, self, 'efficacite', 1, 50)
<|end_body_0|>
<|body_start_1|>
efficacite = enveloppes['f']
efficacite.apercu = '{objet.efficacite}'
efficacite.prompt = 'Entrez... | Type d'objet: pierre à feu. | PierreFeu | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PierreFeu:
"""Type d'objet: pierre à feu."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
BaseType... | stack_v2_sparse_classes_36k_train_033556 | 2,720 | permissive | [
{
"docstring": "Constructeur de l'objet",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Travail sur les enveloppes",
"name": "travailler_enveloppes",
"signature": "def travailler_enveloppes(self, enveloppes)"
}
] | 2 | null | Implement the Python class `PierreFeu` described below.
Class description:
Type d'objet: pierre à feu.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes | Implement the Python class `PierreFeu` described below.
Class description:
Type d'objet: pierre à feu.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def travailler_enveloppes(self, enveloppes): Travail sur les enveloppes
<|skeleton|>
class PierreFeu:
"""Type d'objet: p... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PierreFeu:
"""Type d'objet: pierre à feu."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def travailler_enveloppes(self, enveloppes):
"""Travail sur les enveloppes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PierreFeu:
"""Type d'objet: pierre à feu."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
BaseType.__init__(self, cle)
self.efficacite = 30
self.etendre_editeur('f', 'efficacite', Entier, self, 'efficacite', 1, 50)
def travailler_enveloppes(self, envelopp... | the_stack_v2_python_sparse | src/primaires/objet/types/pierre_feu.py | vincent-lg/tsunami | train | 5 |
cc7eba945a11325885ab4dd86da5078746bb3a0c | [
"delete_database()\ntest_import = import_data(self.folder_name, 'inventory.csv', 'customers.csv', 'rental.csv')\nself.assertEqual(test_import, ((7, 9, 7), (0, 0, 0)))\n'test import bad data'\ndelete_database()\ntest_import = import_data(self.folder_name, 'inventory1.csv', 'customers2.csv', 'rental3.csv')\nself.asse... | <|body_start_0|>
delete_database()
test_import = import_data(self.folder_name, 'inventory.csv', 'customers.csv', 'rental.csv')
self.assertEqual(test_import, ((7, 9, 7), (0, 0, 0)))
'test import bad data'
delete_database()
test_import = import_data(self.folder_name, 'inven... | "test for Mongo database.py | TestDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDatabase:
""""test for Mongo database.py"""
def test_import_data(self):
"""test import all good data"""
<|body_0|>
def test_show_rentals(self):
"""test for show_rentals"""
<|body_1|>
def test_show_available_products(self):
"""rest for sho... | stack_v2_sparse_classes_36k_train_033557 | 3,154 | no_license | [
{
"docstring": "test import all good data",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "test for show_rentals",
"name": "test_show_rentals",
"signature": "def test_show_rentals(self)"
},
{
"docstring": "rest for show_available_products... | 4 | stack_v2_sparse_classes_30k_train_005166 | Implement the Python class `TestDatabase` described below.
Class description:
"test for Mongo database.py
Method signatures and docstrings:
- def test_import_data(self): test import all good data
- def test_show_rentals(self): test for show_rentals
- def test_show_available_products(self): rest for show_available_pro... | Implement the Python class `TestDatabase` described below.
Class description:
"test for Mongo database.py
Method signatures and docstrings:
- def test_import_data(self): test import all good data
- def test_show_rentals(self): test for show_rentals
- def test_show_available_products(self): rest for show_available_pro... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestDatabase:
""""test for Mongo database.py"""
def test_import_data(self):
"""test import all good data"""
<|body_0|>
def test_show_rentals(self):
"""test for show_rentals"""
<|body_1|>
def test_show_available_products(self):
"""rest for sho... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestDatabase:
""""test for Mongo database.py"""
def test_import_data(self):
"""test import all good data"""
delete_database()
test_import = import_data(self.folder_name, 'inventory.csv', 'customers.csv', 'rental.csv')
self.assertEqual(test_import, ((7, 9, 7), (0, 0, 0)))
... | the_stack_v2_python_sparse | students/ethan_nguyen/Lesson05/assignment/test_unit.py | JavaRod/SP_Python220B_2019 | train | 1 |
d8b43981d1bf8672f67c0a3a49921e3772e9d486 | [
"super().__init__(reduction=reduction)\nself.adversarial_temperature = adversarial_temperature\nself.margin = margin",
"neg_score_weights = functional.softmax(neg_scores * self.adversarial_temperature, dim=-1).detach()\nneg_distances = -neg_scores\nweighted_neg_scores = neg_score_weights * functional.logsigmoid(n... | <|body_start_0|>
super().__init__(reduction=reduction)
self.adversarial_temperature = adversarial_temperature
self.margin = margin
<|end_body_0|>
<|body_start_1|>
neg_score_weights = functional.softmax(neg_scores * self.adversarial_temperature, dim=-1).detach()
neg_distances = -... | An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_. | NSSALoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSSALoss:
"""An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_."""
def __init__(self, margin: float=9.0, adversarial_temperature: float=1.0, reduction: str='mean') -> None:
"""Initialize the NSSA loss. :param margin: The loss's margin (a... | stack_v2_sparse_classes_36k_train_033558 | 16,772 | permissive | [
{
"docstring": "Initialize the NSSA loss. :param margin: The loss's margin (also written as gamma in the reference paper) :param adversarial_temperature: The negative sampling temperature (also written as alpha in the reference paper) :param reduction: The name of the reduction operation to aggregate the indivi... | 2 | stack_v2_sparse_classes_30k_train_015400 | Implement the Python class `NSSALoss` described below.
Class description:
An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_.
Method signatures and docstrings:
- def __init__(self, margin: float=9.0, adversarial_temperature: float=1.0, reduction: str='mean') -> None: Init... | Implement the Python class `NSSALoss` described below.
Class description:
An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_.
Method signatures and docstrings:
- def __init__(self, margin: float=9.0, adversarial_temperature: float=1.0, reduction: str='mean') -> None: Init... | eeaf1d623aa881c0c897772372988390e1d8302d | <|skeleton|>
class NSSALoss:
"""An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_."""
def __init__(self, margin: float=9.0, adversarial_temperature: float=1.0, reduction: str='mean') -> None:
"""Initialize the NSSA loss. :param margin: The loss's margin (a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NSSALoss:
"""An implementation of the self-adversarial negative sampling loss function proposed by [sun2019]_."""
def __init__(self, margin: float=9.0, adversarial_temperature: float=1.0, reduction: str='mean') -> None:
"""Initialize the NSSA loss. :param margin: The loss's margin (also written a... | the_stack_v2_python_sparse | src/pykeen/losses.py | Moon-xm/pykeen | train | 1 |
ac92d98280c94f3bc8d3d4dc39547210bc6be7bc | [
"tags = result.tags.split()\nif 'have_youtube' in tags:\n return True\nreturn False",
"log.info('Started %s.pipeline(profile_id=%s, route=%s)' % (type(self).__name__, profile_id, route))\ntry:\n profile = InstagramProfile.objects.get(id=profile_id)\n result = self.proceed(result=profile)\n SocialProfi... | <|body_start_0|>
tags = result.tags.split()
if 'have_youtube' in tags:
return True
return False
<|end_body_0|>
<|body_start_1|>
log.info('Started %s.pipeline(profile_id=%s, route=%s)' % (type(self).__name__, profile_id, route))
try:
profile = InstagramPro... | This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url | HaveYoutubeUrlProcessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HaveYoutubeUrlProcessor:
"""This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url"""
def proceed(self, result):
"""This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. gets ... | stack_v2_sparse_classes_36k_train_033559 | 30,721 | no_license | [
{
"docstring": "This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. gets Profile as result",
"name": "proceed",
"signature": "def proceed(self, result)"
},
{
"docstring": "This function is called when performing Processor as a part of p... | 2 | null | Implement the Python class `HaveYoutubeUrlProcessor` described below.
Class description:
This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url
Method signatures and docstrings:
- def proceed(self, result): This function determines condition when it will proceed to t... | Implement the Python class `HaveYoutubeUrlProcessor` described below.
Class description:
This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url
Method signatures and docstrings:
- def proceed(self, result): This function determines condition when it will proceed to t... | 2f15c4ddd8bbb112c407d222ae48746b626c674f | <|skeleton|>
class HaveYoutubeUrlProcessor:
"""This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url"""
def proceed(self, result):
"""This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. gets ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HaveYoutubeUrlProcessor:
"""This processor is used as a filter to proceed only if this inftagramProfile.description has a youtube url"""
def proceed(self, result):
"""This function determines condition when it will proceed to the next Processor, Classifier or Upgrader in chain. gets Profile as re... | the_stack_v2_python_sparse | Projects/miami_metro/social_discovery/processors.py | TopWebGhost/Angular-Influencer | train | 1 |
836ab8f7a476ba31fd7fb598eaeb1843c2782235 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ExternalItem()",
"from ..entity import Entity\nfrom .acl import Acl\nfrom .external_activity import ExternalActivity\nfrom .external_item_content import ExternalItemContent\nfrom .properties import Properties\nfrom ..entity import Enti... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ExternalItem()
<|end_body_0|>
<|body_start_1|>
from ..entity import Entity
from .acl import Acl
from .external_activity import ExternalActivity
from .external_item_conten... | ExternalItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExternalItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalItem:
"""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: ... | stack_v2_sparse_classes_36k_train_033560 | 3,606 | 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: ExternalItem",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | null | Implement the Python class `ExternalItem` described below.
Class description:
Implement the ExternalItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalItem: Creates a new instance of the appropriate class based on discriminator value Ar... | Implement the Python class `ExternalItem` described below.
Class description:
Implement the ExternalItem class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalItem: Creates a new instance of the appropriate class based on discriminator value Ar... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ExternalItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalItem:
"""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: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExternalItem:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExternalItem:
"""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: ExternalItem""... | the_stack_v2_python_sparse | msgraph/generated/models/external_connectors/external_item.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
41cb7080d4173d34a825a03aa9120e40535d9f71 | [
"self.trained = False\nself.rank = rank\nself.random_state = random_state",
"assert isinstance(K, Kinterface)\nself.n = K.shape[0]\nkernel = lambda x, y: K.kernel(x, y, **K.kernel_args)\nself.model = Nystroem(kernel=kernel, n_components=self.rank, random_state=self.random_state)\nself.model.fit(K.data, y)\nself.a... | <|body_start_0|>
self.trained = False
self.rank = rank
self.random_state = random_state
<|end_body_0|>
<|body_start_1|>
assert isinstance(K, Kinterface)
self.n = K.shape[0]
kernel = lambda x, y: K.kernel(x, y, **K.kernel_args)
self.model = Nystroem(kernel=kernel,... | Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs. | NystromScikit | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NystromScikit:
"""Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs."""
def __init__(self, rank=10, random_state=42):
""":param rank: (``int``) Maximal decomposition rank. :param random_state: (``int``) Random generator seed."""
... | stack_v2_sparse_classes_36k_train_033561 | 6,490 | permissive | [
{
"docstring": ":param rank: (``int``) Maximal decomposition rank. :param random_state: (``int``) Random generator seed.",
"name": "__init__",
"signature": "def __init__(self, rank=10, random_state=42)"
},
{
"docstring": "Fit approximation to the kernel function / matrix. :param K: (``numpy.ndar... | 2 | stack_v2_sparse_classes_30k_train_014595 | Implement the Python class `NystromScikit` described below.
Class description:
Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs.
Method signatures and docstrings:
- def __init__(self, rank=10, random_state=42): :param rank: (``int``) Maximal decomposition rank. ... | Implement the Python class `NystromScikit` described below.
Class description:
Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs.
Method signatures and docstrings:
- def __init__(self, rank=10, random_state=42): :param rank: (``int``) Maximal decomposition rank. ... | d9e7890aaa26cb3877e1a82114ab1e52df595d96 | <|skeleton|>
class NystromScikit:
"""Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs."""
def __init__(self, rank=10, random_state=42):
""":param rank: (``int``) Maximal decomposition rank. :param random_state: (``int``) Random generator seed."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NystromScikit:
"""Nystrom implementation form Scikit Learn wrapper. The main difference is in selection of inducing inputs."""
def __init__(self, rank=10, random_state=42):
""":param rank: (``int``) Maximal decomposition rank. :param random_state: (``int``) Random generator seed."""
self.... | the_stack_v2_python_sparse | mklaren/projection/nystrom.py | tkemps/mklaren | train | 0 |
c5149d43f1b2981aa59858493d74937e1e648bf2 | [
"if not root:\n return 'None'\nls = self.serialize(root.left)\nrs = self.serialize(root.right)\nserial = str(root.val) + ',' + ls + ',' + rs\nreturn serial",
"def redeserialize(l_data):\n if l_data[0] == 'None':\n l_data.pop(0)\n return None\n root = TreeNode(int(l_data[0]))\n l_data.pop... | <|body_start_0|>
if not root:
return 'None'
ls = self.serialize(root.left)
rs = self.serialize(root.right)
serial = str(root.val) + ',' + ls + ',' + rs
return serial
<|end_body_0|>
<|body_start_1|>
def redeserialize(l_data):
if l_data[0] == 'None'... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_033562 | 2,138 | 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:... | 8290ad1c763d9f7c7f7bed63426b4769b34fd2fc | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return 'None'
ls = self.serialize(root.left)
rs = self.serialize(root.right)
serial = str(root.val) + ',' + ls + ',' + rs
return ... | the_stack_v2_python_sparse | tree_449_serialize_BST.py | screnary/Algorithm_python | train | 0 | |
2ea436f30a73cb05c3e4638b0860ae76553ad758 | [
"super(PixToFlow, self).__init__()\nself.batch_size = batch_size\nself.height = height\nself.width = width\nmeshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')\nself.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\nself.id_coords = nn.Parameter(torch.from_numpy(self.id_coords))\ns... | <|body_start_0|>
super(PixToFlow, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
meshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')
self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)
self... | Layer to transform flow into camera pixel coordiantes | PixToFlow | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PixToFlow:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, pix_coords, normalized=False):
"""Forward pass Args: pix_coords (tensor, [NxHxW... | stack_v2_sparse_classes_36k_train_033563 | 13,421 | permissive | [
{
"docstring": "Prepare regular grid (Nx2xHxW)",
"name": "__init__",
"signature": "def __init__(self, batch_size, height, width)"
},
{
"docstring": "Forward pass Args: pix_coords (tensor, [NxHxWx2]): pixel coordinates (normalized) normalized (bool): flow vector normalized by image size Returns: ... | 2 | stack_v2_sparse_classes_30k_train_003299 | Implement the Python class `PixToFlow` described below.
Class description:
Layer to transform flow into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, pix_coords, normalized=False): Forward pass Args: pix_c... | Implement the Python class `PixToFlow` described below.
Class description:
Layer to transform flow into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, pix_coords, normalized=False): Forward pass Args: pix_c... | 50e6ffa9b5164a0dfb34d3215e86cc2288df256d | <|skeleton|>
class PixToFlow:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, pix_coords, normalized=False):
"""Forward pass Args: pix_coords (tensor, [NxHxW... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PixToFlow:
"""Layer to transform flow into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
super(PixToFlow, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
... | the_stack_v2_python_sparse | libs/deep_models/depth/monodepth2/layers.py | Huangying-Zhan/DF-VO | train | 494 |
dff53f89f1a92c45a8c6ac70f1d2f166a20f41e7 | [
"self.num_feat_per_dim = num_feat_per_dim\nself.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))\nself.freq = to.randn(num_feat_per_dim, inp_dim)\nif not isinstance(bandwidth, to.Tensor):\n bandwidth = to.from_numpy(np.asanyarray(bandwidth))\nself.freq *= to.sqrt(to.tensor(2.0) / atleast_2D(bandwidth))\nself.s... | <|body_start_0|>
self.num_feat_per_dim = num_feat_per_dim
self.scale = to.sqrt(to.tensor(2.0 / num_feat_per_dim))
self.freq = to.randn(num_feat_per_dim, inp_dim)
if not isinstance(bandwidth, to.Tensor):
bandwidth = to.from_numpy(np.asanyarray(bandwidth))
self.freq *= ... | Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007 | RandFourierFeat | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandFourierFeat:
"""Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor]):
"""Gaussian kernel: $k(x,y) = ... | stack_v2_sparse_classes_36k_train_033564 | 17,010 | permissive | [
{
"docstring": "Gaussian kernel: $k(x,y) = \\\\exp(-\\\\sigma**2 / (2*d) * ||x-y||^2)$ Sample from $\\\\mathcal{N}(0,1)$ and scale the result by $\\\\sigma / \\\\sqrt{2*d}$ :param inp_dim: flat dimension of the inputs i.e. the observations, called $d$ in [1] :param num_feat_per_dim: number of random Fourier fea... | 2 | null | Implement the Python class `RandFourierFeat` described below.
Class description:
Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[fl... | Implement the Python class `RandFourierFeat` described below.
Class description:
Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007
Method signatures and docstrings:
- def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[fl... | 15901f70f0538bce19acdda2a0018984f67cc0fe | <|skeleton|>
class RandFourierFeat:
"""Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor]):
"""Gaussian kernel: $k(x,y) = ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandFourierFeat:
"""Random Fourier features .. seealso:: [1] A. Rahimi and B. Recht "Random Features for Large-Scale Kernel Machines", NIPS, 2007"""
def __init__(self, inp_dim: int, num_feat_per_dim: int, bandwidth: Union[float, np.ndarray, to.Tensor]):
"""Gaussian kernel: $k(x,y) = \\exp(-\\sigm... | the_stack_v2_python_sparse | Pyrado/pyrado/policies/features.py | arlene-kuehn/SimuRLacra | train | 0 |
e02fc93e1f8e11a252e2220bc27da44260e751ee | [
"self.client = Client()\nself.mechanic = get_sample_mechanic_data()\nself.client.post('/workshop/api/mechanic/signup', self.mechanic, content_type='application/json')\nuser_data = get_sample_user_data()\nself.user = User.objects.create(id=2, email=user_data['email'], number=user_data['number'], password=bcrypt.hash... | <|body_start_0|>
self.client = Client()
self.mechanic = get_sample_mechanic_data()
self.client.post('/workshop/api/mechanic/signup', self.mechanic, content_type='application/json')
user_data = get_sample_user_data()
self.user = User.objects.create(id=2, email=user_data['email'], ... | contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_headers: Auth headers for dummy mechanic vehicle: dummy vehicle object contact_mechanic_r... | MerchantTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MerchantTestCase:
"""contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_headers: Auth headers for dummy mechanic vehi... | stack_v2_sparse_classes_36k_train_033565 | 7,919 | permissive | [
{
"docstring": "stores a sample request body for mechanic signup creates a dummy mechanic, a dummy user, a dummy vehicle and corresponding auth tokens stores a sample request body for contact mechanic :return: None",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "increases nu... | 6 | stack_v2_sparse_classes_30k_train_021685 | Implement the Python class `MerchantTestCase` described below.
Class description:
contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_header... | Implement the Python class `MerchantTestCase` described below.
Class description:
contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_header... | 45e98d77b2fef6004dd36c640bd95b25395d0948 | <|skeleton|>
class MerchantTestCase:
"""contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_headers: Auth headers for dummy mechanic vehi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MerchantTestCase:
"""contains all the test cases related to merchant Attributes: client: Client object used for testing mechanic: sample mechanic sign up request body user: dummy user object user_auth_headers: Auth headers for dummy user mechanic_auth_headers: Auth headers for dummy mechanic vehicle: dummy ve... | the_stack_v2_python_sparse | services/workshop/crapi/merchant/tests.py | OWASP/crAPI | train | 772 |
9babe20fd577dc535d5eed9047e4221d3efedcc9 | [
"if not isinstance(customize_feature_funcs, list):\n customize_feature_funcs = [customize_feature_funcs]\nself.feature_extractors: List[Callable[[List[Candidate]], Iterator[Tuple[int, str, int]]]] = []\nfor feature in features:\n if feature not in FEATURES:\n raise ValueError(f'Unrecognized feature typ... | <|body_start_0|>
if not isinstance(customize_feature_funcs, list):
customize_feature_funcs = [customize_feature_funcs]
self.feature_extractors: List[Callable[[List[Candidate]], Iterator[Tuple[int, str, int]]]] = []
for feature in features:
if feature not in FEATURES:
... | A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extractors where the extractor takes a list of candidates as input and yield tuples of (... | FeatureExtractor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FeatureExtractor:
"""A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extractors where the extractor takes a list ... | stack_v2_sparse_classes_36k_train_033566 | 2,598 | permissive | [
{
"docstring": "Initialize FeatureExtractor.",
"name": "__init__",
"signature": "def __init__(self, features: List[str]=['textual', 'structural', 'tabular', 'visual'], customize_feature_funcs: Union[Feature_func, List[Feature_func]]=[]) -> None"
},
{
"docstring": "Extract features from candidate... | 2 | stack_v2_sparse_classes_30k_train_015787 | Implement the Python class `FeatureExtractor` described below.
Class description:
A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extra... | Implement the Python class `FeatureExtractor` described below.
Class description:
A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extra... | e857285867f01536192524a195b02cbffe40c4b2 | <|skeleton|>
class FeatureExtractor:
"""A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extractors where the extractor takes a list ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FeatureExtractor:
"""A class to extract features from candidates. :param features: a list of which Fonduer feature types to extract, defaults to ["textual", "structural", "tabular", "visual"] :param customize_feature_funcs: a list of customized feature extractors where the extractor takes a list of candidates... | the_stack_v2_python_sparse | src/fonduer/features/feature_extractors.py | HiromuHota/fonduer | train | 0 |
f2cd2a875453514f67451f26f07f6a9673851e55 | [
"directory = os.path.join(storage_path, signal_type)\nlatest_directory = max(pathlib.Path(directory).glob('*/'), key=os.path.getmtime)\nwith open(latest_directory, 'rb') as f:\n return pickle.load(f)",
"with metrics.timer(metrics.names.lcc.get_data):\n d = timedelta(days=1)\n past_day_content = TimeBucke... | <|body_start_0|>
directory = os.path.join(storage_path, signal_type)
latest_directory = max(pathlib.Path(directory).glob('*/'), key=os.path.getmtime)
with open(latest_directory, 'rb') as f:
return pickle.load(f)
<|end_body_0|>
<|body_start_1|>
with metrics.timer(metrics.name... | LCCIndexer | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LCCIndexer:
def get_recent_index(cls, storage_path, signal_type) -> PDQIndex:
"""Get the most recent index."""
<|body_0|>
def build_index_from_last_24h(cls, signal_type, storage_path, bucket_width) -> None:
"""Create an index"""
<|body_1|>
def override_r... | stack_v2_sparse_classes_36k_train_033567 | 2,383 | permissive | [
{
"docstring": "Get the most recent index.",
"name": "get_recent_index",
"signature": "def get_recent_index(cls, storage_path, signal_type) -> PDQIndex"
},
{
"docstring": "Create an index",
"name": "build_index_from_last_24h",
"signature": "def build_index_from_last_24h(cls, signal_type,... | 3 | stack_v2_sparse_classes_30k_train_021013 | Implement the Python class `LCCIndexer` described below.
Class description:
Implement the LCCIndexer class.
Method signatures and docstrings:
- def get_recent_index(cls, storage_path, signal_type) -> PDQIndex: Get the most recent index.
- def build_index_from_last_24h(cls, signal_type, storage_path, bucket_width) -> ... | Implement the Python class `LCCIndexer` described below.
Class description:
Implement the LCCIndexer class.
Method signatures and docstrings:
- def get_recent_index(cls, storage_path, signal_type) -> PDQIndex: Get the most recent index.
- def build_index_from_last_24h(cls, signal_type, storage_path, bucket_width) -> ... | 45dff06ba21f1afdb43a434c9ba0fc49e07b48d8 | <|skeleton|>
class LCCIndexer:
def get_recent_index(cls, storage_path, signal_type) -> PDQIndex:
"""Get the most recent index."""
<|body_0|>
def build_index_from_last_24h(cls, signal_type, storage_path, bucket_width) -> None:
"""Create an index"""
<|body_1|>
def override_r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LCCIndexer:
def get_recent_index(cls, storage_path, signal_type) -> PDQIndex:
"""Get the most recent index."""
directory = os.path.join(storage_path, signal_type)
latest_directory = max(pathlib.Path(directory).glob('*/'), key=os.path.getmtime)
with open(latest_directory, 'rb') ... | the_stack_v2_python_sparse | hasher-matcher-actioner/hmalib/indexers/lcc.py | facebook/ThreatExchange | train | 1,146 | |
8e5d3b88da7e9bdb971fa521ef913f7baaffb76f | [
"self.vertex = vertex\nself.adj = defaultdict(list)\nself.edge = edge\nfor u, v, w in edge:\n self.adj[u].append((v, w))\n self.adj[v].append((u, w))",
"tmp = []\nfor u, v in edge:\n tmp.extend([u, v])\nvertex = list(set(tmp))\nreturn cls(vertex, edge)"
] | <|body_start_0|>
self.vertex = vertex
self.adj = defaultdict(list)
self.edge = edge
for u, v, w in edge:
self.adj[u].append((v, w))
self.adj[v].append((u, w))
<|end_body_0|>
<|body_start_1|>
tmp = []
for u, v in edge:
tmp.extend([u, v]... | UnDirectionGraph | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnDirectionGraph:
def __init__(self, vertex, edge):
""":param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]"""
<|body_0|>
def createGraphByEdge(cls, edge):
"""note: 可实现多态性,先调用该方法处理原始数据=>标准输入,再调用构造函数 :param edge: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_033568 | 2,601 | no_license | [
{
"docstring": ":param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]",
"name": "__init__",
"signature": "def __init__(self, vertex, edge)"
},
{
"docstring": "note: 可实现多态性,先调用该方法处理原始数据=>标准输入,再调用构造函数 :param edge: :return:",
"name": "createGraphByEdge",
"signature": "d... | 2 | null | Implement the Python class `UnDirectionGraph` described below.
Class description:
Implement the UnDirectionGraph class.
Method signatures and docstrings:
- def __init__(self, vertex, edge): :param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]
- def createGraphByEdge(cls, edge): note: 可实现多态性,先调用该... | Implement the Python class `UnDirectionGraph` described below.
Class description:
Implement the UnDirectionGraph class.
Method signatures and docstrings:
- def __init__(self, vertex, edge): :param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]
- def createGraphByEdge(cls, edge): note: 可实现多态性,先调用该... | f7421522c437c952698736dbac8fb7ac6c0b8b88 | <|skeleton|>
class UnDirectionGraph:
def __init__(self, vertex, edge):
""":param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]"""
<|body_0|>
def createGraphByEdge(cls, edge):
"""note: 可实现多态性,先调用该方法处理原始数据=>标准输入,再调用构造函数 :param edge: :return:"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnDirectionGraph:
def __init__(self, vertex, edge):
""":param vertex: [u1,u2,...] :param edge: [[u1,v1,w1],[u2,v2,w2],[u3,v3,w3]]"""
self.vertex = vertex
self.adj = defaultdict(list)
self.edge = edge
for u, v, w in edge:
self.adj[u].append((v, w))
... | the_stack_v2_python_sparse | leetcode/algorithm_introduction/23.2_kruskal_mst.py | whitepaper2/data_beauty | train | 0 | |
0e9a9d838a1bd57c7cafcd15b2b9e9410df5458b | [
"super(AddKNgramModel, self).__init__(*args)\nself.k = k\nself.k_norm = len(self.ngram_counter.vocabulary) * k",
"context = self.check_context(context)\ncontext_freqdist = self.ngrams[context]\nword_count = context_freqdist[word]\ncontext_count = context_freqdist.N()\nreturn (word_count + self.k) / (context_count... | <|body_start_0|>
super(AddKNgramModel, self).__init__(*args)
self.k = k
self.k_norm = len(self.ngram_counter.vocabulary) * k
<|end_body_0|>
<|body_start_1|>
context = self.check_context(context)
context_freqdist = self.ngrams[context]
word_count = context_freqdist[word]
... | Provides Add-k-smoothed scores. | AddKNgramModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddKNgramModel:
"""Provides Add-k-smoothed scores."""
def __init__(self, k, *args):
"""Expects an input value, k, a number by which to increment word counts during scoring."""
<|body_0|>
def score(self, word, context):
"""With Add-k-smoothing, the score is normal... | stack_v2_sparse_classes_36k_train_033569 | 7,225 | permissive | [
{
"docstring": "Expects an input value, k, a number by which to increment word counts during scoring.",
"name": "__init__",
"signature": "def __init__(self, k, *args)"
},
{
"docstring": "With Add-k-smoothing, the score is normalized with a k value.",
"name": "score",
"signature": "def sc... | 2 | stack_v2_sparse_classes_30k_train_004906 | Implement the Python class `AddKNgramModel` described below.
Class description:
Provides Add-k-smoothed scores.
Method signatures and docstrings:
- def __init__(self, k, *args): Expects an input value, k, a number by which to increment word counts during scoring.
- def score(self, word, context): With Add-k-smoothing... | Implement the Python class `AddKNgramModel` described below.
Class description:
Provides Add-k-smoothed scores.
Method signatures and docstrings:
- def __init__(self, k, *args): Expects an input value, k, a number by which to increment word counts during scoring.
- def score(self, word, context): With Add-k-smoothing... | 43fd3317b641e0830905a734226afad3a0ea19f6 | <|skeleton|>
class AddKNgramModel:
"""Provides Add-k-smoothed scores."""
def __init__(self, k, *args):
"""Expects an input value, k, a number by which to increment word counts during scoring."""
<|body_0|>
def score(self, word, context):
"""With Add-k-smoothing, the score is normal... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddKNgramModel:
"""Provides Add-k-smoothed scores."""
def __init__(self, k, *args):
"""Expects an input value, k, a number by which to increment word counts during scoring."""
super(AddKNgramModel, self).__init__(*args)
self.k = k
self.k_norm = len(self.ngram_counter.vocab... | the_stack_v2_python_sparse | snippets/ch07/model.py | foxbook/atap | train | 401 |
0ec5394fe250feccaceb3daed9c66bfd6c188bde | [
"super(VDSMImportLog, self).parse_content(content)\nsplited_file_name = self.file_name.split('-')\nself.vm_uuid = '-'.join(splited_file_name[1:-1])\n_datetime = splited_file_name[-1].replace('.log', '')\ntry:\n self.file_datetime = datetime.strptime(_datetime, '%Y%m%dT%H%M%S')\nexcept:\n self.file_datetime = ... | <|body_start_0|>
super(VDSMImportLog, self).parse_content(content)
splited_file_name = self.file_name.split('-')
self.vm_uuid = '-'.join(splited_file_name[1:-1])
_datetime = splited_file_name[-1].replace('.log', '')
try:
self.file_datetime = datetime.strptime(_datetim... | Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and storage-type have different lengths Example: >>> log = vdsm_import_logs.get('pr... | VDSMImportLog | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VDSMImportLog:
"""Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and storage-type have different lengths Ex... | stack_v2_sparse_classes_36k_train_033570 | 11,713 | permissive | [
{
"docstring": "Parse ``import-@UUID-@datetime.log`` log file.",
"name": "parse_content",
"signature": "def parse_content(self, content)"
},
{
"docstring": "Find all the (available) logs that are after the given time stamp. If `s` is not supplied, then all lines are used. Otherwise, only the lin... | 2 | stack_v2_sparse_classes_30k_train_010839 | Implement the Python class `VDSMImportLog` described below.
Class description:
Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and... | Implement the Python class `VDSMImportLog` described below.
Class description:
Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and... | b0ea07fc3f4dd8801b505fe70e9b36e628152c4a | <|skeleton|>
class VDSMImportLog:
"""Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and storage-type have different lengths Ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VDSMImportLog:
"""Parser for the log file detailing virtual machine imports. Sample log file:: [ 0.2] preparing for copy [ 0.2] Copying disk 1/1 to /rhev/data-center/958ca292-9126/f524d2ba-155a/images/502f5598-335d-/d4b140c8-9cd5 [ 0.0] >>> source, dest, and storage-type have different lengths Example: >>> lo... | the_stack_v2_python_sparse | insights/parsers/vdsm_log.py | RedHatInsights/insights-core | train | 144 |
43a8a05055fa77862642c7d6bbe9d47b30629ac7 | [
"obj = MBKDomainConfig()\nobj.name = name\nobj.type = type\nobj.domain = domain\nobj.mapped_domain = mapped_domain\nDBBusiness(DBTable.MBKDomainConfig).add_record(obj)",
"where = MBKDomainConfig()\nwhere.name = name\nwhere.type = type\nwhere.domain = domain\nDBBusiness(DBTable.MBKDomainConfig).del_record(where_in... | <|body_start_0|>
obj = MBKDomainConfig()
obj.name = name
obj.type = type
obj.domain = domain
obj.mapped_domain = mapped_domain
DBBusiness(DBTable.MBKDomainConfig).add_record(obj)
<|end_body_0|>
<|body_start_1|>
where = MBKDomainConfig()
where.name = name
... | MBKInternationalBusiness | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MBKInternationalBusiness:
def add_domainconfig(self, name, type, domain, mapped_domain):
"""添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:"""
<|body_0|>
def del_domainconfig(self, name, type, domain):
"""删除domain配置 :param name: :pa... | stack_v2_sparse_classes_36k_train_033571 | 1,024 | no_license | [
{
"docstring": "添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:",
"name": "add_domainconfig",
"signature": "def add_domainconfig(self, name, type, domain, mapped_domain)"
},
{
"docstring": "删除domain配置 :param name: :param type: :param domain: :return:",
"nam... | 2 | null | Implement the Python class `MBKInternationalBusiness` described below.
Class description:
Implement the MBKInternationalBusiness class.
Method signatures and docstrings:
- def add_domainconfig(self, name, type, domain, mapped_domain): 添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:
... | Implement the Python class `MBKInternationalBusiness` described below.
Class description:
Implement the MBKInternationalBusiness class.
Method signatures and docstrings:
- def add_domainconfig(self, name, type, domain, mapped_domain): 添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:
... | 3e51e9e80e9778540c8cc1c799fed402f2469ae8 | <|skeleton|>
class MBKInternationalBusiness:
def add_domainconfig(self, name, type, domain, mapped_domain):
"""添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:"""
<|body_0|>
def del_domainconfig(self, name, type, domain):
"""删除domain配置 :param name: :pa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MBKInternationalBusiness:
def add_domainconfig(self, name, type, domain, mapped_domain):
"""添加domain配置 :param name: :param type: :param domain: :param mapped_domain: :return:"""
obj = MBKDomainConfig()
obj.name = name
obj.type = type
obj.domain = domain
obj.mapp... | the_stack_v2_python_sparse | mobike-api-test/lib/business/mysqldb/mbk_international_business.py | lijule168/python_test_web | train | 0 | |
aae85eac3a15170d92a11f5675a5ede6b325cb2a | [
"self.arr_set = set(arr)\nself.arr_hash_prefixt = {}\nfor ele in self.arr_set:\n self.arr_hash_prefixt[ele] = [0] * (len(arr) + 1)\nfor i in range(len(arr)):\n for key, val in self.arr_hash_prefixt.items():\n if key == arr[i]:\n val[i + 1] += val[i] + 1\n else:\n val[i + 1]... | <|body_start_0|>
self.arr_set = set(arr)
self.arr_hash_prefixt = {}
for ele in self.arr_set:
self.arr_hash_prefixt[ele] = [0] * (len(arr) + 1)
for i in range(len(arr)):
for key, val in self.arr_hash_prefixt.items():
if key == arr[i]:
... | MajorityChecker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.arr_se... | stack_v2_sparse_classes_36k_train_033572 | 1,324 | no_license | [
{
"docstring": ":type arr: List[int]",
"name": "__init__",
"signature": "def __init__(self, arr)"
},
{
"docstring": ":type left: int :type right: int :type threshold: int :rtype: int",
"name": "query",
"signature": "def query(self, left, right, threshold)"
}
] | 2 | null | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int | Implement the Python class `MajorityChecker` described below.
Class description:
Implement the MajorityChecker class.
Method signatures and docstrings:
- def __init__(self, arr): :type arr: List[int]
- def query(self, left, right, threshold): :type left: int :type right: int :type threshold: int :rtype: int
<|skelet... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
<|body_0|>
def query(self, left, right, threshold):
""":type left: int :type right: int :type threshold: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MajorityChecker:
def __init__(self, arr):
""":type arr: List[int]"""
self.arr_set = set(arr)
self.arr_hash_prefixt = {}
for ele in self.arr_set:
self.arr_hash_prefixt[ele] = [0] * (len(arr) + 1)
for i in range(len(arr)):
for key, val in self.arr_... | the_stack_v2_python_sparse | 1157. Online Majority Element In Subarray.py | dundunmao/LeetCode2019 | train | 0 | |
752a73494dfa5acee5f1a8ce0d58dddda84b6791 | [
"a = r.randint(1, 10)\nlogging.info('=============%s次测试首页注意事项=============' % a)\nl = AdviceAndHealthView(self.driver)\nself.assertTrue(l.login_health())\nfor i in range(a):\n l.advice_action()\n self.assertTrue(l.check_advice())",
"a = r.randint(1, 10)\nlogging.info('=============%s次测试首页健康宣教=============' ... | <|body_start_0|>
a = r.randint(1, 10)
logging.info('=============%s次测试首页注意事项=============' % a)
l = AdviceAndHealthView(self.driver)
self.assertTrue(l.login_health())
for i in range(a):
l.advice_action()
self.assertTrue(l.check_advice())
<|end_body_0|>
<|... | TestAdviceAndHealth | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAdviceAndHealth:
def test_advice(self):
"""测试首页注意事项 :return:"""
<|body_0|>
def test_health(self):
"""测试首页健康宣教 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
a = r.randint(1, 10)
logging.info('=============%s次测试首页注意事项===========... | stack_v2_sparse_classes_36k_train_033573 | 1,330 | no_license | [
{
"docstring": "测试首页注意事项 :return:",
"name": "test_advice",
"signature": "def test_advice(self)"
},
{
"docstring": "测试首页健康宣教 :return:",
"name": "test_health",
"signature": "def test_health(self)"
}
] | 2 | null | Implement the Python class `TestAdviceAndHealth` described below.
Class description:
Implement the TestAdviceAndHealth class.
Method signatures and docstrings:
- def test_advice(self): 测试首页注意事项 :return:
- def test_health(self): 测试首页健康宣教 :return: | Implement the Python class `TestAdviceAndHealth` described below.
Class description:
Implement the TestAdviceAndHealth class.
Method signatures and docstrings:
- def test_advice(self): 测试首页注意事项 :return:
- def test_health(self): 测试首页健康宣教 :return:
<|skeleton|>
class TestAdviceAndHealth:
def test_advice(self):
... | d2b7819fd3687e0a011988fefab3e6fd70bb014a | <|skeleton|>
class TestAdviceAndHealth:
def test_advice(self):
"""测试首页注意事项 :return:"""
<|body_0|>
def test_health(self):
"""测试首页健康宣教 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestAdviceAndHealth:
def test_advice(self):
"""测试首页注意事项 :return:"""
a = r.randint(1, 10)
logging.info('=============%s次测试首页注意事项=============' % a)
l = AdviceAndHealthView(self.driver)
self.assertTrue(l.login_health())
for i in range(a):
l.advice_acti... | the_stack_v2_python_sparse | care_user/test_case/test_advice.py | vothin/code | train | 0 | |
6c14f26d6a7f97018defa499315f335a6c1787a6 | [
"Frame.__init__(self, master, **kw)\nself.nicks = sorted(scores, key=lambda player: player[1], reverse=True)\nself.create_widgets()\nself.grid(row=0, column=0, padx=40, pady=40)",
"bold_font = tkfont.Font(family='Helvetica', size=11, weight='bold')\nsmall_font = tkfont.Font(family='Helvetica', size=11)\nself._lab... | <|body_start_0|>
Frame.__init__(self, master, **kw)
self.nicks = sorted(scores, key=lambda player: player[1], reverse=True)
self.create_widgets()
self.grid(row=0, column=0, padx=40, pady=40)
<|end_body_0|>
<|body_start_1|>
bold_font = tkfont.Font(family='Helvetica', size=11, wei... | ResultBoard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResultBoard:
def __init__(self, scores, master=None, **kw):
"""creates a frame that will contain result board gets list of players and their scores sorts list of players according to their scores"""
<|body_0|>
def create_widgets(self):
"""creates a widget with result... | stack_v2_sparse_classes_36k_train_033574 | 1,633 | no_license | [
{
"docstring": "creates a frame that will contain result board gets list of players and their scores sorts list of players according to their scores",
"name": "__init__",
"signature": "def __init__(self, scores, master=None, **kw)"
},
{
"docstring": "creates a widget with result board",
"nam... | 2 | stack_v2_sparse_classes_30k_train_010284 | Implement the Python class `ResultBoard` described below.
Class description:
Implement the ResultBoard class.
Method signatures and docstrings:
- def __init__(self, scores, master=None, **kw): creates a frame that will contain result board gets list of players and their scores sorts list of players according to their... | Implement the Python class `ResultBoard` described below.
Class description:
Implement the ResultBoard class.
Method signatures and docstrings:
- def __init__(self, scores, master=None, **kw): creates a frame that will contain result board gets list of players and their scores sorts list of players according to their... | d2737b10dbdc2e980641ee3529ebcd06fe52faed | <|skeleton|>
class ResultBoard:
def __init__(self, scores, master=None, **kw):
"""creates a frame that will contain result board gets list of players and their scores sorts list of players according to their scores"""
<|body_0|>
def create_widgets(self):
"""creates a widget with result... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResultBoard:
def __init__(self, scores, master=None, **kw):
"""creates a frame that will contain result board gets list of players and their scores sorts list of players according to their scores"""
Frame.__init__(self, master, **kw)
self.nicks = sorted(scores, key=lambda player: playe... | the_stack_v2_python_sparse | src/client/ui/result_board.py | msemikin/distributed-sudoku | train | 0 | |
7f0b936f620be94e04564f0ad3abbe602dfae87b | [
"super(Encoder, self).__init__()\nself._hidden_size = hidden_size\nself._dropout_rate = dropout_rate\nself._recurrent_layer = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(self._hidden_size, dropout=dropout_rate, return_sequences=True, return_state=True))",
"result_list = self._recurrent_layer(src_token_embe... | <|body_start_0|>
super(Encoder, self).__init__()
self._hidden_size = hidden_size
self._dropout_rate = dropout_rate
self._recurrent_layer = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(self._hidden_size, dropout=dropout_rate, return_sequences=True, return_state=True))
<|end_body_0|>... | The Encoder that consists of a bidirectional one-layer LSTM RNN. | Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Encoder:
"""The Encoder that consists of a bidirectional one-layer LSTM RNN."""
def __init__(self, hidden_size, dropout_rate):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout_rate: float scalar, dropout rate for the Dropout layers.... | stack_v2_sparse_classes_36k_train_033575 | 20,679 | no_license | [
{
"docstring": "Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout_rate: float scalar, dropout rate for the Dropout layers.",
"name": "__init__",
"signature": "def __init__(self, hidden_size, dropout_rate)"
},
{
"docstring": "Computes the output of ... | 2 | stack_v2_sparse_classes_30k_train_000763 | Implement the Python class `Encoder` described below.
Class description:
The Encoder that consists of a bidirectional one-layer LSTM RNN.
Method signatures and docstrings:
- def __init__(self, hidden_size, dropout_rate): Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout... | Implement the Python class `Encoder` described below.
Class description:
The Encoder that consists of a bidirectional one-layer LSTM RNN.
Method signatures and docstrings:
- def __init__(self, hidden_size, dropout_rate): Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout... | 63cd17dd38234d47d5d992930d8136e2c30f5de7 | <|skeleton|>
class Encoder:
"""The Encoder that consists of a bidirectional one-layer LSTM RNN."""
def __init__(self, hidden_size, dropout_rate):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout_rate: float scalar, dropout rate for the Dropout layers.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Encoder:
"""The Encoder that consists of a bidirectional one-layer LSTM RNN."""
def __init__(self, hidden_size, dropout_rate):
"""Constructor. Args: hidden_size: int scalar, the hidden size of continuous representation. dropout_rate: float scalar, dropout rate for the Dropout layers."""
s... | the_stack_v2_python_sparse | model.py | chao-ji/tf-seq2seq | train | 3 |
29e990292415a356b38a584f034c46d13b9cadec | [
"def merge_two_lists(p: ListNode, q: ListNode) -> ListNode:\n r = prehead = ListNode()\n while p or q:\n if p and q:\n if p.val < q.val:\n r.next = p\n p = p.next\n else:\n r.next = q\n q = q.next\n elif p:\n ... | <|body_start_0|>
def merge_two_lists(p: ListNode, q: ListNode) -> ListNode:
r = prehead = ListNode()
while p or q:
if p and q:
if p.val < q.val:
r.next = p
p = p.next
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode:
"""Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%"""
<|body_0|>
def mergeKLists_v2(self, lists: List[ListNode]) -> ListNode:
"""Use... | stack_v2_sparse_classes_36k_train_033576 | 3,579 | no_license | [
{
"docstring": "Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%",
"name": "mergeKLists_v1",
"signature": "def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode"
},
{
"docstring": "Use a heap to process all of the lists.",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode: Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode: Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%
- def... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode:
"""Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%"""
<|body_0|>
def mergeKLists_v2(self, lists: List[ListNode]) -> ListNode:
"""Use... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists_v1(self, lists: List[ListNode]) -> ListNode:
"""Merge two linked-lists at a time -- Divide and conquer. LeetCode: runtime 144 ms > 40.27%; mem 17.7 MB < 42.99%"""
def merge_two_lists(p: ListNode, q: ListNode) -> ListNode:
r = prehead = ListNode()
... | the_stack_v2_python_sparse | python3/linked_list/merge_k_sorted_lists.py | victorchu/algorithms | train | 0 | |
a203b81e372b94b5fc4fe80aefe7b9e8b9008ccf | [
"if not head:\n return\npre = head.val\ntmp = head.next\nt = ListNode(head.val)\nres = t\nwhile tmp:\n if tmp.val == pre:\n tmp = tmp.next\n else:\n pre = tmp.val\n t.next = ListNode(tmp.val)\n t = t.next\n tmp = tmp.next\nreturn res",
"cur = head\nwhile cur:\n runne... | <|body_start_0|>
if not head:
return
pre = head.val
tmp = head.next
t = ListNode(head.val)
res = t
while tmp:
if tmp.val == pre:
tmp = tmp.next
else:
pre = tmp.val
t.next = ListNode(tmp.va... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates0(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head:
r... | stack_v2_sparse_classes_36k_train_033577 | 1,036 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates",
"signature": "def deleteDuplicates(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "deleteDuplicates0",
"signature": "def deleteDuplicates0(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009742 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates0(self, head): :type head: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def deleteDuplicates(self, head): :type head: ListNode :rtype: ListNode
- def deleteDuplicates0(self, head): :type head: ListNode :rtype: ListNode
<|skeleton|>
class Solution:
... | 9e49b2c6003b957276737005d4aaac276b44d251 | <|skeleton|>
class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def deleteDuplicates0(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def deleteDuplicates(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return
pre = head.val
tmp = head.next
t = ListNode(head.val)
res = t
while tmp:
if tmp.val == pre:
tmp = tmp.next... | the_stack_v2_python_sparse | PythonCode/src/0083_Remove_Duplicates_from_Sorted_List.py | oneyuan/CodeforFun | train | 0 | |
e841ca0952ac386d6e65dd35699cd94b3ac87b66 | [
"def dfs(d, target):\n if target < 0:\n return\n if target == 0:\n return True\n for key, value in d.items():\n if value == 0:\n continue\n d[key] -= 1\n if dfs(d, target - key):\n return True\n d[key] += 1\n return False\nif sum(nums) % 2:... | <|body_start_0|>
def dfs(d, target):
if target < 0:
return
if target == 0:
return True
for key, value in d.items():
if value == 0:
continue
d[key] -= 1
if dfs(d, target - key):... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPartition(self, nums):
"""回溯 :type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition2(self, nums):
"""dfs :param nums: :return:"""
<|body_1|>
def canPartition3(self, nums):
"""01背包问题 :param nums: :return:"""
<|b... | stack_v2_sparse_classes_36k_train_033578 | 4,442 | no_license | [
{
"docstring": "回溯 :type nums: List[int] :rtype: bool",
"name": "canPartition",
"signature": "def canPartition(self, nums)"
},
{
"docstring": "dfs :param nums: :return:",
"name": "canPartition2",
"signature": "def canPartition2(self, nums)"
},
{
"docstring": "01背包问题 :param nums: ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): 回溯 :type nums: List[int] :rtype: bool
- def canPartition2(self, nums): dfs :param nums: :return:
- def canPartition3(self, nums): 01背包问题 :param nums... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPartition(self, nums): 回溯 :type nums: List[int] :rtype: bool
- def canPartition2(self, nums): dfs :param nums: :return:
- def canPartition3(self, nums): 01背包问题 :param nums... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def canPartition(self, nums):
"""回溯 :type nums: List[int] :rtype: bool"""
<|body_0|>
def canPartition2(self, nums):
"""dfs :param nums: :return:"""
<|body_1|>
def canPartition3(self, nums):
"""01背包问题 :param nums: :return:"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def canPartition(self, nums):
"""回溯 :type nums: List[int] :rtype: bool"""
def dfs(d, target):
if target < 0:
return
if target == 0:
return True
for key, value in d.items():
if value == 0:
... | the_stack_v2_python_sparse | 416_分割等和子集.py | lovehhf/LeetCode | train | 0 | |
876d1d26635d85f2f94a706ea78757ce80e3824d | [
"if 'even' == 'odd':\n arrayextension = 5\nelse:\n arrayextension = 0\narraylength = 96 + arrayextension\nMaxVal = 255\nMinVal = 0\nself.gentest = bytes([MaxVal // 2] * arraylength)",
"with self.assertRaises(TypeError):\n result = bytesfunc.bmin(1)\nwith self.assertRaises(TypeError):\n result = min(1)... | <|body_start_0|>
if 'even' == 'odd':
arrayextension = 5
else:
arrayextension = 0
arraylength = 96 + arrayextension
MaxVal = 255
MinVal = 0
self.gentest = bytes([MaxVal // 2] * arraylength)
<|end_body_0|>
<|body_start_1|>
with self.assertRa... | Test bmin for basic parameter tests. op_template_params | bmin_parameter_even_arraysize_with_simd_bytes | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class bmin_parameter_even_arraysize_with_simd_bytes:
"""Test bmin for basic parameter tests. op_template_params"""
def setUp(self):
"""Initialise."""
<|body_0|>
def test_bmin_param_function_01(self):
"""Test bmin - Sequence type bytes. Test invalid parameter type even ... | stack_v2_sparse_classes_36k_train_033579 | 49,998 | permissive | [
{
"docstring": "Initialise.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test bmin - Sequence type bytes. Test invalid parameter type even length array with SIMD.",
"name": "test_bmin_param_function_01",
"signature": "def test_bmin_param_function_01(self)"
},
... | 5 | stack_v2_sparse_classes_30k_val_000970 | Implement the Python class `bmin_parameter_even_arraysize_with_simd_bytes` described below.
Class description:
Test bmin for basic parameter tests. op_template_params
Method signatures and docstrings:
- def setUp(self): Initialise.
- def test_bmin_param_function_01(self): Test bmin - Sequence type bytes. Test invalid... | Implement the Python class `bmin_parameter_even_arraysize_with_simd_bytes` described below.
Class description:
Test bmin for basic parameter tests. op_template_params
Method signatures and docstrings:
- def setUp(self): Initialise.
- def test_bmin_param_function_01(self): Test bmin - Sequence type bytes. Test invalid... | 28fe0705fc59b0646a4d44e539c919173e8e8b99 | <|skeleton|>
class bmin_parameter_even_arraysize_with_simd_bytes:
"""Test bmin for basic parameter tests. op_template_params"""
def setUp(self):
"""Initialise."""
<|body_0|>
def test_bmin_param_function_01(self):
"""Test bmin - Sequence type bytes. Test invalid parameter type even ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class bmin_parameter_even_arraysize_with_simd_bytes:
"""Test bmin for basic parameter tests. op_template_params"""
def setUp(self):
"""Initialise."""
if 'even' == 'odd':
arrayextension = 5
else:
arrayextension = 0
arraylength = 96 + arrayextension
... | the_stack_v2_python_sparse | unittest/test_bmin.py | m1griffin/bytesfunc | train | 2 |
c37d07e980cc2fcdd0a935333d86d1274e5ecfaa | [
"num = 0\ndigit_length = len(str(n))\nfirst_digit = int(str(n)[0])\npass",
"a = [str(i) for i in range(1, n + 1)]\na.sort()\nreturn a[k - 1]"
] | <|body_start_0|>
num = 0
digit_length = len(str(n))
first_digit = int(str(n)[0])
pass
<|end_body_0|>
<|body_start_1|>
a = [str(i) for i in range(1, n + 1)]
a.sort()
return a[k - 1]
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
"""字符串排序"""
<|body_0|>
def findKthNumberSlow(self, n: int, k: int) -> int:
"""慢速法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
num = 0
digit_length = len(str(n))
first_digi... | stack_v2_sparse_classes_36k_train_033580 | 534 | no_license | [
{
"docstring": "字符串排序",
"name": "findKthNumber",
"signature": "def findKthNumber(self, n: int, k: int) -> int"
},
{
"docstring": "慢速法",
"name": "findKthNumberSlow",
"signature": "def findKthNumberSlow(self, n: int, k: int) -> int"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthNumber(self, n: int, k: int) -> int: 字符串排序
- def findKthNumberSlow(self, n: int, k: int) -> int: 慢速法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findKthNumber(self, n: int, k: int) -> int: 字符串排序
- def findKthNumberSlow(self, n: int, k: int) -> int: 慢速法
<|skeleton|>
class Solution:
def findKthNumber(self, n: int,... | 91ca9cd0df3c88fc7ef3c829dacd4d13f6b71ab1 | <|skeleton|>
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
"""字符串排序"""
<|body_0|>
def findKthNumberSlow(self, n: int, k: int) -> int:
"""慢速法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findKthNumber(self, n: int, k: int) -> int:
"""字符串排序"""
num = 0
digit_length = len(str(n))
first_digit = int(str(n)[0])
pass
def findKthNumberSlow(self, n: int, k: int) -> int:
"""慢速法"""
a = [str(i) for i in range(1, n + 1)]
a.... | the_stack_v2_python_sparse | leetcode_projects/bytedance/lt_440.py | miniyk2012/leetcode | train | 1 | |
9055c64e01fbf07b3a5f0b17d7e16f4148140538 | [
"\"\"\"\n Input: \"ab\"\n \"aa\"\n Output: true\n Expected: false \n \"\"\"\nmapping = {}\ntarget = set()\nif len(s) != len(t):\n return False\nfor index in range(len(s)):\n firstL = s[index]\n secondL = t[index]\n if firstL not in mapping:\n if secon... | <|body_start_0|>
"""
Input: "ab"
"aa"
Output: true
Expected: false
"""
mapping = {}
target = set()
if len(s) != len(t):
return False
for index in range(len(s)):
fir... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""
Input: "ab"
... | stack_v2_sparse_classes_36k_train_033581 | 2,113 | no_license | [
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isIsomorphic",
"signature": "def isIsomorphic(self, s, t)"
},
{
"docstring": ":type s: str :type t: str :rtype: bool",
"name": "isIsomorphic",
"signature": "def isIsomorphic(self, s, t)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016290 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
- def isIsomorphic(self, s, t): :type s: str :type t: str :rtype: bool
<|skeleton|>
class Solution:
def... | d953abe2c9680f636563e76287d2f907e90ced63 | <|skeleton|>
class Solution:
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_0|>
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isIsomorphic(self, s, t):
""":type s: str :type t: str :rtype: bool"""
"""
Input: "ab"
"aa"
Output: true
Expected: false
"""
mapping = {}
target = set()
if len(s) !... | the_stack_v2_python_sparse | Python_leetcode/205_isomorphic_strings.py | xiangcao/Leetcode | train | 0 | |
1bee1a66bef9e1105d2811d2990b71180217f433 | [
"super().__init__(loader)\nassert isinstance(num_batches, (int, float)), f'Expected ``num_batches`` type is int/floatbut got {type(num_batches)}'\nif isinstance(num_batches, float):\n assert 0.0 <= num_batches <= 1, f'Expected ``num_batches`` to be in range [0; 1]but got {num_batches}'\n num_batches = int(len... | <|body_start_0|>
super().__init__(loader)
assert isinstance(num_batches, (int, float)), f'Expected ``num_batches`` type is int/floatbut got {type(num_batches)}'
if isinstance(num_batches, float):
assert 0.0 <= num_batches <= 1, f'Expected ``num_batches`` to be in range [0; 1]but got ... | Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst.data.loader import BatchLimitLoaderWrapper num_samples, num_features = int(... | BatchLimitLoaderWrapper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchLimitLoaderWrapper:
"""Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst.data.loader import Batch... | stack_v2_sparse_classes_36k_train_033582 | 9,744 | permissive | [
{
"docstring": "Loader wrapper. Limits number of batches used per each iteration. Args: loader: torch dataloader. num_batches (Union[int, float]): number of batches to use (int), or portion of iterator (float, should be in [0;1] range)",
"name": "__init__",
"signature": "def __init__(self, loader: DataL... | 3 | null | Implement the Python class `BatchLimitLoaderWrapper` described below.
Class description:
Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset... | Implement the Python class `BatchLimitLoaderWrapper` described below.
Class description:
Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset... | e99f90655d0efcf22559a46e928f0f98c9807ebf | <|skeleton|>
class BatchLimitLoaderWrapper:
"""Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst.data.loader import Batch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BatchLimitLoaderWrapper:
"""Loader wrapper. Limits number of batches used per each iteration. For example, if you have some loader and want to use only first 5 bathes: .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst.data.loader import BatchLimitLoaderWr... | the_stack_v2_python_sparse | catalyst/data/loader.py | catalyst-team/catalyst | train | 3,038 |
571fc5d93916d27456a9d13331f128114cf24d9c | [
"assert termination_type in ('any', 'except', 'none', 'only', 'single', 'less_than', 'greater_than', 'equals')\nself.choices: List[str] = choices or []\nself.termination_type: str = termination_type if isinstance(termination_type, str) else None\nif termination_type in ('only', 'single'):\n if len(self.choices) ... | <|body_start_0|>
assert termination_type in ('any', 'except', 'none', 'only', 'single', 'less_than', 'greater_than', 'equals')
self.choices: List[str] = choices or []
self.termination_type: str = termination_type if isinstance(termination_type, str) else None
if termination_type in ('onl... | Class to represent when a survey should be terminated for a given respondent. | Termination | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Termination:
"""Class to represent when a survey should be terminated for a given respondent."""
def __init__(self, choices: Optional[List[str]]=None, termination_type: Optional[str]=None, value: Optional[str]=None, otherwise: str=None):
"""Create a new Termination. :param choices: L... | stack_v2_sparse_classes_36k_train_033583 | 4,768 | permissive | [
{
"docstring": "Create a new Termination. :param choices: List of choices to use if the termination condition is a selection. :param termination_type: Options for the type of Termination. 'any' terminates where any of `choices` are selected. 'except' terminates where any except `choices` are selected. 'none' te... | 2 | stack_v2_sparse_classes_30k_train_006241 | Implement the Python class `Termination` described below.
Class description:
Class to represent when a survey should be terminated for a given respondent.
Method signatures and docstrings:
- def __init__(self, choices: Optional[List[str]]=None, termination_type: Optional[str]=None, value: Optional[str]=None, otherwis... | Implement the Python class `Termination` described below.
Class description:
Class to represent when a survey should be terminated for a given respondent.
Method signatures and docstrings:
- def __init__(self, choices: Optional[List[str]]=None, termination_type: Optional[str]=None, value: Optional[str]=None, otherwis... | 1a0fcf0c22e2c7306cba0218f82d24c97d28ee1f | <|skeleton|>
class Termination:
"""Class to represent when a survey should be terminated for a given respondent."""
def __init__(self, choices: Optional[List[str]]=None, termination_type: Optional[str]=None, value: Optional[str]=None, otherwise: str=None):
"""Create a new Termination. :param choices: L... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Termination:
"""Class to represent when a survey should be terminated for a given respondent."""
def __init__(self, choices: Optional[List[str]]=None, termination_type: Optional[str]=None, value: Optional[str]=None, otherwise: str=None):
"""Create a new Termination. :param choices: List of choice... | the_stack_v2_python_sparse | survey/generation/termination.py | vahndi/quant-survey | train | 2 |
31c7d54cb2ebf974366c31050cedde8cf2113d27 | [
"super().__init__()\nself.alpha = alpha\nself.isrlu = isrlu",
"if self.isrlu is not False:\n return (input < 0).float() * isru(input, self.apha) + (input >= 0).float() * input\nelse:\n return isru(input, self.apha)"
] | <|body_start_0|>
super().__init__()
self.alpha = alpha
self.isrlu = isrlu
<|end_body_0|>
<|body_start_1|>
if self.isrlu is not False:
return (input < 0).float() * isru(input, self.apha) + (input >= 0).float() * input
else:
return isru(input, self.apha)
<|... | ISRU | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.alpha = alpha
self.isr... | stack_v2_sparse_classes_36k_train_033584 | 32,265 | no_license | [
{
"docstring": "Init method.",
"name": "__init__",
"signature": "def __init__(self, alpha=1.0, isrlu=False)"
},
{
"docstring": "Forward pass of the function.",
"name": "forward",
"signature": "def forward(self, input)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000481 | Implement the Python class `ISRU` described below.
Class description:
Implement the ISRU class.
Method signatures and docstrings:
- def __init__(self, alpha=1.0, isrlu=False): Init method.
- def forward(self, input): Forward pass of the function. | Implement the Python class `ISRU` described below.
Class description:
Implement the ISRU class.
Method signatures and docstrings:
- def __init__(self, alpha=1.0, isrlu=False): Init method.
- def forward(self, input): Forward pass of the function.
<|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=Fals... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
<|body_0|>
def forward(self, input):
"""Forward pass of the function."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ISRU:
def __init__(self, alpha=1.0, isrlu=False):
"""Init method."""
super().__init__()
self.alpha = alpha
self.isrlu = isrlu
def forward(self, input):
"""Forward pass of the function."""
if self.isrlu is not False:
return (input < 0).float() * ... | the_stack_v2_python_sparse | generated/test_digantamisra98_Echo.py | jansel/pytorch-jit-paritybench | train | 35 | |
e71de778b6e5802c27fcb7ad870a187aa3555768 | [
"self.name = name\nself.hparams = hparams\nself.optimizer_n = hparams.optimizer\nself.training_freq = hparams.training_freq\nself.training_epochs = hparams.training_epochs\nself.t = 0\nself.data_h = ContextualDataset(hparams.context_dim, hparams.num_actions, hparams.buffer_s)\nbnn_name = '{}-bnn'.format(name)\nif b... | <|body_start_0|>
self.name = name
self.hparams = hparams
self.optimizer_n = hparams.optimizer
self.training_freq = hparams.training_freq
self.training_epochs = hparams.training_epochs
self.t = 0
self.data_h = ContextualDataset(hparams.context_dim, hparams.num_acti... | Posterior Sampling algorithm based on a Bayesian neural network. | PosteriorBNNSampling | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PosteriorBNNSampling:
"""Posterior Sampling algorithm based on a Bayesian neural network."""
def __init__(self, name, hparams, bnn_model='RMSProp'):
"""Creates a PosteriorBNNSampling object based on a specific optimizer. The algorithm has two basic tools: an Approx BNN and a Contextu... | stack_v2_sparse_classes_36k_train_033585 | 3,741 | permissive | [
{
"docstring": "Creates a PosteriorBNNSampling object based on a specific optimizer. The algorithm has two basic tools: an Approx BNN and a Contextual Dataset. The Bayesian Network keeps the posterior based on the optimizer iterations. Args: name: Name of the algorithm. hparams: Hyper-parameters of the algorith... | 3 | stack_v2_sparse_classes_30k_train_014679 | Implement the Python class `PosteriorBNNSampling` described below.
Class description:
Posterior Sampling algorithm based on a Bayesian neural network.
Method signatures and docstrings:
- def __init__(self, name, hparams, bnn_model='RMSProp'): Creates a PosteriorBNNSampling object based on a specific optimizer. The al... | Implement the Python class `PosteriorBNNSampling` described below.
Class description:
Posterior Sampling algorithm based on a Bayesian neural network.
Method signatures and docstrings:
- def __init__(self, name, hparams, bnn_model='RMSProp'): Creates a PosteriorBNNSampling object based on a specific optimizer. The al... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class PosteriorBNNSampling:
"""Posterior Sampling algorithm based on a Bayesian neural network."""
def __init__(self, name, hparams, bnn_model='RMSProp'):
"""Creates a PosteriorBNNSampling object based on a specific optimizer. The algorithm has two basic tools: an Approx BNN and a Contextu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PosteriorBNNSampling:
"""Posterior Sampling algorithm based on a Bayesian neural network."""
def __init__(self, name, hparams, bnn_model='RMSProp'):
"""Creates a PosteriorBNNSampling object based on a specific optimizer. The algorithm has two basic tools: an Approx BNN and a Contextual Dataset. T... | the_stack_v2_python_sparse | models/research/deep_contextual_bandits/bandits/algorithms/posterior_bnn_sampling.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
9f82ea2edfaa1f97df869b28a1868171460304ae | [
"if not Permission(UserNeed(profile_id)).can():\n if not VerifyEducationPermission.can():\n return abort(HTTPStatus.FORBIDDEN, 'User is not authorized to view this profile education')\neducation = Education.query.get(profile_id)\nif education is None:\n return abort(HTTPStatus.NOT_FOUND, 'Education is ... | <|body_start_0|>
if not Permission(UserNeed(profile_id)).can():
if not VerifyEducationPermission.can():
return abort(HTTPStatus.FORBIDDEN, 'User is not authorized to view this profile education')
education = Education.query.get(profile_id)
if education is None:
... | ProfileEducationResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProfileEducationResource:
def get(self, profile_id):
"""Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info"""
<|body_0|>
def put(self, profile_id):
"""Update profile education i... | stack_v2_sparse_classes_36k_train_033586 | 2,764 | permissive | [
{
"docstring": "Get profile education info * User can view **their education** info * User with permission to **\"verify education\"** can view education info",
"name": "get",
"signature": "def get(self, profile_id)"
},
{
"docstring": "Update profile education info * User can edit **their educat... | 2 | null | Implement the Python class `ProfileEducationResource` described below.
Class description:
Implement the ProfileEducationResource class.
Method signatures and docstrings:
- def get(self, profile_id): Get profile education info * User can view **their education** info * User with permission to **"verify education"** ca... | Implement the Python class `ProfileEducationResource` described below.
Class description:
Implement the ProfileEducationResource class.
Method signatures and docstrings:
- def get(self, profile_id): Get profile education info * User can view **their education** info * User with permission to **"verify education"** ca... | dce87ffe395ae4bd08b47f28e07594e1889da819 | <|skeleton|>
class ProfileEducationResource:
def get(self, profile_id):
"""Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info"""
<|body_0|>
def put(self, profile_id):
"""Update profile education i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProfileEducationResource:
def get(self, profile_id):
"""Get profile education info * User can view **their education** info * User with permission to **"verify education"** can view education info"""
if not Permission(UserNeed(profile_id)).can():
if not VerifyEducationPermission.ca... | the_stack_v2_python_sparse | src/backend/app/api/public/profiles/profile/education/education.py | aimanow/sft | train | 0 | |
486cf534beb8a6ef07aa872d3d2c6a0f9e442f22 | [
"self._newtext = ''\nself._replace_location = 0\nself._current_location = 0\nself._counter = 0\nself._start_location = 0\nself._end_location = 0",
"self._newtext = newtext\nself._replace_location = location\nself._current_location = 0",
"self._newtext = newtext\nself._start_location = start_location\nself._end_... | <|body_start_0|>
self._newtext = ''
self._replace_location = 0
self._current_location = 0
self._counter = 0
self._start_location = 0
self._end_location = 0
<|end_body_0|>
<|body_start_1|>
self._newtext = newtext
self._replace_location = location
s... | Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement is to occur. _current_location : int current location in the file. _counter ... | _SubHelper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _SubHelper:
"""Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement is to occur. _current_location : int c... | stack_v2_sparse_classes_36k_train_033587 | 33,972 | no_license | [
{
"docstring": "Initialize attributes.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Set a new word location and value for replacement. Parameters ---------- newtext : string text to insert. location : int location in the file where replacement is to occur.",
"na... | 5 | stack_v2_sparse_classes_30k_train_020593 | Implement the Python class `_SubHelper` described below.
Class description:
Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement... | Implement the Python class `_SubHelper` described below.
Class description:
Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement... | d9e89fe017f1131d554599c248247f73bb9b534d | <|skeleton|>
class _SubHelper:
"""Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement is to occur. _current_location : int c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _SubHelper:
"""Replaces file text at the correct word location in a line. This class contains the Helper Function that is passed to re.sub. Attributes ---------- _newtext : string text to insert. _replace_location : int location in the file where replacement is to occur. _current_location : int current locati... | the_stack_v2_python_sparse | venv/Lib/site-packages/openmdao/utils/file_wrap.py | ManojDjs/Heart-rate-estimation | train | 1 |
94ba6f1b4f062ce9f899a3a0130cb63235d5f015 | [
"if request.user.is_authenticated:\n files = File.objects.all()\n serializer = FileSerializer(files, many=True)\n return Response(serializer.data)\nreturn Response(status=status.HTTP_401_UNAUTHORIZED)",
"if request.user.is_authenticated:\n serializer = FileSerializer(data=request.data)\n if seriali... | <|body_start_0|>
if request.user.is_authenticated:
files = File.objects.all()
serializer = FileSerializer(files, many=True)
return Response(serializer.data)
return Response(status=status.HTTP_401_UNAUTHORIZED)
<|end_body_0|>
<|body_start_1|>
if request.user.i... | List all Files or add one. | FileList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileList:
"""List all Files or add one."""
def get(self, request):
"""Send the list of File in the database."""
<|body_0|>
def post(self, request):
"""Add a File into the database."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if request.user.... | stack_v2_sparse_classes_36k_train_033588 | 3,371 | permissive | [
{
"docstring": "Send the list of File in the database.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "Add a File into the database.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_017145 | Implement the Python class `FileList` described below.
Class description:
List all Files or add one.
Method signatures and docstrings:
- def get(self, request): Send the list of File in the database.
- def post(self, request): Add a File into the database. | Implement the Python class `FileList` described below.
Class description:
List all Files or add one.
Method signatures and docstrings:
- def get(self, request): Send the list of File in the database.
- def post(self, request): Add a File into the database.
<|skeleton|>
class FileList:
"""List all Files or add on... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class FileList:
"""List all Files or add one."""
def get(self, request):
"""Send the list of File in the database."""
<|body_0|>
def post(self, request):
"""Add a File into the database."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileList:
"""List all Files or add one."""
def get(self, request):
"""Send the list of File in the database."""
if request.user.is_authenticated:
files = File.objects.all()
serializer = FileSerializer(files, many=True)
return Response(serializer.data)
... | the_stack_v2_python_sparse | maintenancemanagement/views/views_file.py | Open-CMMS/openCMMS_backend | train | 4 |
48e84cb7c637413524e4bc656249fc0523504334 | [
"nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\ndb = pymysql.connect('10.0.0.224', 'root', 'databases001', 'bms')\ncursor = db.cursor()\nsql = \"UPDATE bms.bd_learn_annex SET annex_url = 'std/155114117217621675/3BD56545A9924CE0BB8C7333308D1695.jpg',annex_status = 2,upload_user = 'autotester1',uplo... | <|body_start_0|>
nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
db = pymysql.connect('10.0.0.224', 'root', 'databases001', 'bms')
cursor = db.cursor()
sql = "UPDATE bms.bd_learn_annex SET annex_url = 'std/155114117217621675/3BD56545A9924CE0BB8C7333308D1695.jpg',annex_sta... | ConnectMysql | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectMysql:
def updatalearnannex(self, learn_id):
"""设置成教学员附件资料"""
<|body_0|>
def upgklearnannex(self, learn_id):
"""设置国开学员附件资料"""
<|body_1|>
def getlearnid(self, mobile):
"""获取学员learn_id"""
<|body_2|>
def getstdid(self, mobile):
... | stack_v2_sparse_classes_36k_train_033589 | 5,499 | no_license | [
{
"docstring": "设置成教学员附件资料",
"name": "updatalearnannex",
"signature": "def updatalearnannex(self, learn_id)"
},
{
"docstring": "设置国开学员附件资料",
"name": "upgklearnannex",
"signature": "def upgklearnannex(self, learn_id)"
},
{
"docstring": "获取学员learn_id",
"name": "getlearnid",
... | 6 | null | Implement the Python class `ConnectMysql` described below.
Class description:
Implement the ConnectMysql class.
Method signatures and docstrings:
- def updatalearnannex(self, learn_id): 设置成教学员附件资料
- def upgklearnannex(self, learn_id): 设置国开学员附件资料
- def getlearnid(self, mobile): 获取学员learn_id
- def getstdid(self, mobile... | Implement the Python class `ConnectMysql` described below.
Class description:
Implement the ConnectMysql class.
Method signatures and docstrings:
- def updatalearnannex(self, learn_id): 设置成教学员附件资料
- def upgklearnannex(self, learn_id): 设置国开学员附件资料
- def getlearnid(self, mobile): 获取学员learn_id
- def getstdid(self, mobile... | 08d7fab053f6797016d827396fc7b48a3eba9b6e | <|skeleton|>
class ConnectMysql:
def updatalearnannex(self, learn_id):
"""设置成教学员附件资料"""
<|body_0|>
def upgklearnannex(self, learn_id):
"""设置国开学员附件资料"""
<|body_1|>
def getlearnid(self, mobile):
"""获取学员learn_id"""
<|body_2|>
def getstdid(self, mobile):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectMysql:
def updatalearnannex(self, learn_id):
"""设置成教学员附件资料"""
nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
db = pymysql.connect('10.0.0.224', 'root', 'databases001', 'bms')
cursor = db.cursor()
sql = "UPDATE bms.bd_learn_annex SET annex_url = '... | the_stack_v2_python_sparse | YZ_AutoTest_Project/Website/test_case/public/ConnectMysql.py | MikeDarkCloud/YZ | train | 0 | |
e2d1f7a76edb600bf93a166787ffac9c9290cb3e | [
"self.rolenames = rn = {}\nself.roleids = ri = {}\nfor n, f in enumerate(fieldlist):\n rid = n + 100\n rn[rid] = f\n ri[f] = rid\nself.model = mo = QtGui.QStandardItemModel()\ntry:\n mo.setRoleNames(rn)\nexcept AttributeError:\n pass",
"si = QtGui.QStandardItem()\nfor k, v in d.items():\n rid = ... | <|body_start_0|>
self.rolenames = rn = {}
self.roleids = ri = {}
for n, f in enumerate(fieldlist):
rid = n + 100
rn[rid] = f
ri[f] = rid
self.model = mo = QtGui.QStandardItemModel()
try:
mo.setRoleNames(rn)
except AttributeE... | ModelWrapper | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
<|body_0|>
def mkitem(self, d):
"""dict with field->value"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.rolenames = rn = {}
self.roleids = ri = {}
... | stack_v2_sparse_classes_36k_train_033590 | 4,067 | permissive | [
{
"docstring": "Ctor for ModelWrapper class.",
"name": "__init__",
"signature": "def __init__(self, fieldlist)"
},
{
"docstring": "dict with field->value",
"name": "mkitem",
"signature": "def mkitem(self, d)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003012 | Implement the Python class `ModelWrapper` described below.
Class description:
Implement the ModelWrapper class.
Method signatures and docstrings:
- def __init__(self, fieldlist): Ctor for ModelWrapper class.
- def mkitem(self, d): dict with field->value | Implement the Python class `ModelWrapper` described below.
Class description:
Implement the ModelWrapper class.
Method signatures and docstrings:
- def __init__(self, fieldlist): Ctor for ModelWrapper class.
- def mkitem(self, d): dict with field->value
<|skeleton|>
class ModelWrapper:
def __init__(self, fieldl... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
<|body_0|>
def mkitem(self, d):
"""dict with field->value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelWrapper:
def __init__(self, fieldlist):
"""Ctor for ModelWrapper class."""
self.rolenames = rn = {}
self.roleids = ri = {}
for n, f in enumerate(fieldlist):
rid = n + 100
rn[rid] = f
ri[f] = rid
self.model = mo = QtGui.QStandardI... | the_stack_v2_python_sparse | leo/plugins/notebook.py | leo-editor/leo-editor | train | 1,671 | |
a1f671855898540f0aebeea277619dddc88666da | [
"unit = db_session.get_session()\nquery = unit.query(models.Session).filter(models.Session.environment_id == environment_id)\nif state:\n query = query.filter(models.Session.state == state)\nreturn query.order_by(models.Session.version.desc(), models.Session.updated.desc()).all()",
"unit = db_session.get_sessi... | <|body_start_0|>
unit = db_session.get_session()
query = unit.query(models.Session).filter(models.Session.environment_id == environment_id)
if state:
query = query.filter(models.Session.state == state)
return query.order_by(models.Session.version.desc(), models.Session.update... | SessionServices | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionServices:
def get_sessions(environment_id, state=None):
"""Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.states.EnvironmentStatus :return: Sessions for specified Environment, if SessionState is not defined all s... | stack_v2_sparse_classes_36k_train_033591 | 4,555 | permissive | [
{
"docstring": "Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.states.EnvironmentStatus :return: Sessions for specified Environment, if SessionState is not defined all sessions for specified environment is returned.",
"name": "get_sessions... | 4 | null | Implement the Python class `SessionServices` described below.
Class description:
Implement the SessionServices class.
Method signatures and docstrings:
- def get_sessions(environment_id, state=None): Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.st... | Implement the Python class `SessionServices` described below.
Class description:
Implement the SessionServices class.
Method signatures and docstrings:
- def get_sessions(environment_id, state=None): Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.st... | c898a310afbc27f12190446ef75d8b0bd12115eb | <|skeleton|>
class SessionServices:
def get_sessions(environment_id, state=None):
"""Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.states.EnvironmentStatus :return: Sessions for specified Environment, if SessionState is not defined all s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionServices:
def get_sessions(environment_id, state=None):
"""Get list of sessions for specified environment. :param environment_id: Environment Id :param state: murano.services.states.EnvironmentStatus :return: Sessions for specified Environment, if SessionState is not defined all sessions for sp... | the_stack_v2_python_sparse | murano/db/services/sessions.py | openstack/murano | train | 94 | |
ef10982b6e273e7456dff909c70456075cd34d19 | [
"logs.log_info('You are using the vgK channel: Kv1.3')\nself.time_unit = 1000.0\nself.vrev = -65\nself.m = 1.0 / (1 + np.exp((V - -14.1) / -10.3))\nself.h = 1.0 / (1 + np.exp((V - -33.0) / 3.7))\nself._mpower = 1\nself._hpower = 1",
"self._mInf = 1.0 / (1 + np.exp((V - -14.1) / -10.3))\nself._mTau = -0.284 * V + ... | <|body_start_0|>
logs.log_info('You are using the vgK channel: Kv1.3')
self.time_unit = 1000.0
self.vrev = -65
self.m = 1.0 / (1 + np.exp((V - -14.1) / -10.3))
self.h = 1.0 / (1 + np.exp((V - -33.0) / 3.7))
self._mpower = 1
self._hpower = 1
<|end_body_0|>
<|body_... | Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action potential. This channel is implicated in a host of non-neural activity, i... | Kv1p3 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kv1p3:
"""Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action potential. This channel is implicated in... | stack_v2_sparse_classes_36k_train_033592 | 24,227 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `Kv1p3` described below.
Class description:
Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action p... | Implement the Python class `Kv1p3` described below.
Class description:
Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action p... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Kv1p3:
"""Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action potential. This channel is implicated in... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kv1p3:
"""Kv1.3 model from Douglass et al 1990. Potassium voltage-gated channel Kv1.3 is a member of the shaker-related subfamily and belongs to the delayed rectifier class of channels, which allow nerve cells to efficiently re-polarize following an action potential. This channel is implicated in a host of no... | the_stack_v2_python_sparse | betse/science/channels/vg_k.py | R-Stefano/betse-ml | train | 0 |
627df901eb782fb4142ecff0970083a9c47db8b5 | [
"path = '/'.join([self.LOCKS_BASEURL, quote_plus(scope), quote_plus(name)])\nurl = build_url(choice(self.list_hosts), path=path, params={'did_type': 'dataset'})\nresult = self._send_request(url)\nif result.status_code == codes.ok:\n locks = self._load_json_data(result)\n return locks\nelse:\n exc_cls, exc_... | <|body_start_0|>
path = '/'.join([self.LOCKS_BASEURL, quote_plus(scope), quote_plus(name)])
url = build_url(choice(self.list_hosts), path=path, params={'did_type': 'dataset'})
result = self._send_request(url)
if result.status_code == codes.ok:
locks = self._load_json_data(res... | Lock client class for working with rucio locks | LockClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LockClient:
"""Lock client class for working with rucio locks"""
def get_dataset_locks(self, scope, name):
"""Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: the name of the did of the locks to list."""
<|bod... | stack_v2_sparse_classes_36k_train_033593 | 3,973 | permissive | [
{
"docstring": "Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: the name of the did of the locks to list.",
"name": "get_dataset_locks",
"signature": "def get_dataset_locks(self, scope, name)"
},
{
"docstring": "Get list of lock... | 3 | stack_v2_sparse_classes_30k_train_007401 | Implement the Python class `LockClient` described below.
Class description:
Lock client class for working with rucio locks
Method signatures and docstrings:
- def get_dataset_locks(self, scope, name): Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: t... | Implement the Python class `LockClient` described below.
Class description:
Lock client class for working with rucio locks
Method signatures and docstrings:
- def get_dataset_locks(self, scope, name): Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: t... | 7f0d229ac0b3bc7dec12c6e158bea2b82d414a3b | <|skeleton|>
class LockClient:
"""Lock client class for working with rucio locks"""
def get_dataset_locks(self, scope, name):
"""Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: the name of the did of the locks to list."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LockClient:
"""Lock client class for working with rucio locks"""
def get_dataset_locks(self, scope, name):
"""Get a dataset locks of the specified dataset. :param scope: the scope of the did of the locks to list. :param name: the name of the did of the locks to list."""
path = '/'.join([s... | the_stack_v2_python_sparse | lib/rucio/client/lockclient.py | rucio/rucio | train | 232 |
f898f93a99c2cc4cd84acf4e62379d9d5dbef531 | [
"self.keys = {}\nself.times = {}\nself.max_time = 0\nself.min_time = sys.maxsize\nself.head = self.Node()\nself.tail = self.Node()\nself.head.next = self.tail\nself.tail.prev = self.head",
"if key in self.keys:\n time = self.keys[key]\n self.times[time].keys.remove(key)\n new_time = time + 1\n if new_... | <|body_start_0|>
self.keys = {}
self.times = {}
self.max_time = 0
self.min_time = sys.maxsize
self.head = self.Node()
self.tail = self.Node()
self.head.next = self.tail
self.tail.prev = self.head
<|end_body_0|>
<|body_start_1|>
if key in self.keys... | AllOne | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_36k_train_033594 | 3,344 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void",
"name": "inc",
"signature": "def inc(self, key)"
},
... | 5 | null | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | Implement the Python class `AllOne` described below.
Class description:
Implement the AllOne class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def inc(self, key): Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void
-... | 7a501cf84cfa46b677d9c9fced18deacb61de0e8 | <|skeleton|>
class AllOne:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def inc(self, key):
"""Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void"""
<|body_1|>
def dec(self, key):
"""De... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AllOne:
def __init__(self):
"""Initialize your data structure here."""
self.keys = {}
self.times = {}
self.max_time = 0
self.min_time = sys.maxsize
self.head = self.Node()
self.tail = self.Node()
self.head.next = self.tail
self.tail.prev ... | the_stack_v2_python_sparse | 432. All O`one Data Structure/Python/Solution.py | xiaole0310/leetcode | train | 1 | |
8228042941c2133364bfd382005fd6823d56ca4d | [
"flash_sale_ids = []\ndetail_id2promotion = {}\nfor promotion in promotions:\n flash_sale_ids.append(promotion.context['detail_id'])\n detail_id2promotion[promotion.context['detail_id']] = promotion\nflash_sale_models = promotion_models.FlashSale.select().dj_where(id__in=flash_sale_ids)\nfor model in flash_sa... | <|body_start_0|>
flash_sale_ids = []
detail_id2promotion = {}
for promotion in promotions:
flash_sale_ids.append(promotion.context['detail_id'])
detail_id2promotion[promotion.context['detail_id']] = promotion
flash_sale_models = promotion_models.FlashSale.select()... | 对促销集合批量填充详情服务 | FillPromotionDetailService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
<|body_0|>
def __fill_integral_sale_rule_details(self, promotions):
"""填充与积分应用相关的`积分应用规则`"""
<|body_1|>
def __fill_premium_sale_details... | stack_v2_sparse_classes_36k_train_033595 | 6,129 | no_license | [
{
"docstring": "填充限时抢购的详细信息",
"name": "__fill_flash_sale_details",
"signature": "def __fill_flash_sale_details(self, promotions)"
},
{
"docstring": "填充与积分应用相关的`积分应用规则`",
"name": "__fill_integral_sale_rule_details",
"signature": "def __fill_integral_sale_rule_details(self, promotions)"
... | 6 | null | Implement the Python class `FillPromotionDetailService` described below.
Class description:
对促销集合批量填充详情服务
Method signatures and docstrings:
- def __fill_flash_sale_details(self, promotions): 填充限时抢购的详细信息
- def __fill_integral_sale_rule_details(self, promotions): 填充与积分应用相关的`积分应用规则`
- def __fill_premium_sale_details(sel... | Implement the Python class `FillPromotionDetailService` described below.
Class description:
对促销集合批量填充详情服务
Method signatures and docstrings:
- def __fill_flash_sale_details(self, promotions): 填充限时抢购的详细信息
- def __fill_integral_sale_rule_details(self, promotions): 填充与积分应用相关的`积分应用规则`
- def __fill_premium_sale_details(sel... | 39860a451678ab50ad93ce8ebe2ef8490af65d62 | <|skeleton|>
class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
<|body_0|>
def __fill_integral_sale_rule_details(self, promotions):
"""填充与积分应用相关的`积分应用规则`"""
<|body_1|>
def __fill_premium_sale_details... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FillPromotionDetailService:
"""对促销集合批量填充详情服务"""
def __fill_flash_sale_details(self, promotions):
"""填充限时抢购的详细信息"""
flash_sale_ids = []
detail_id2promotion = {}
for promotion in promotions:
flash_sale_ids.append(promotion.context['detail_id'])
detail... | the_stack_v2_python_sparse | business/mall/promotion/fill_promotion_detail_service.py | chengdg/gaia | train | 0 |
9a587d39bc1270298602d44133407d899b3943d6 | [
"self.allow_prefixes = allow_prefixes\nself.deny_prefixes = deny_prefixes\nself.disable_indexing = disable_indexing",
"if dictionary is None:\n return None\nallow_prefixes = dictionary.get('allowPrefixes')\ndeny_prefixes = dictionary.get('denyPrefixes')\ndisable_indexing = dictionary.get('disableIndexing')\nre... | <|body_start_0|>
self.allow_prefixes = allow_prefixes
self.deny_prefixes = deny_prefixes
self.disable_indexing = disable_indexing
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
allow_prefixes = dictionary.get('allowPrefixes')
deny_prefixes... | Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (list of string): List of directory prefixes to filter out. disable_indexing (bool): If... | IndexingPolicyProto | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexingPolicyProto:
"""Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (list of string): List of directory pref... | stack_v2_sparse_classes_36k_train_033596 | 2,075 | permissive | [
{
"docstring": "Constructor for the IndexingPolicyProto class",
"name": "__init__",
"signature": "def __init__(self, allow_prefixes=None, deny_prefixes=None, disable_indexing=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary... | 2 | stack_v2_sparse_classes_30k_train_008562 | Implement the Python class `IndexingPolicyProto` described below.
Class description:
Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (... | Implement the Python class `IndexingPolicyProto` described below.
Class description:
Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class IndexingPolicyProto:
"""Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (list of string): List of directory pref... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexingPolicyProto:
"""Implementation of the 'IndexingPolicyProto' model. Proto to encapsulate file level indexing policy for VMs in a backup job. Attributes: allow_prefixes (list of string): List of directory prefixes to allow for indexing. deny_prefixes (list of string): List of directory prefixes to filte... | the_stack_v2_python_sparse | cohesity_management_sdk/models/indexing_policy_proto.py | cohesity/management-sdk-python | train | 24 |
1d37fa696197189a580a2147405421fd1a1141f2 | [
"self._builder = builder\nself._src = None\nif not os.path.exists(program_path):\n raise FileNotFoundError('Unable to find {} program.'.format(program_path))\nself._builder.set_program_command(program_path)",
"self._builder.new_command()\nself._builder.build_program_command()\nself._builder.build_option()\nsel... | <|body_start_0|>
self._builder = builder
self._src = None
if not os.path.exists(program_path):
raise FileNotFoundError('Unable to find {} program.'.format(program_path))
self._builder.set_program_command(program_path)
<|end_body_0|>
<|body_start_1|>
self._builder.new... | Use this to generate commands for sending to exiv2. | Exiv2CommandBuilder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exiv2CommandBuilder:
"""Use this to generate commands for sending to exiv2."""
def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path()):
"""Configure how the director should configure the builders. Args: builder: Choose which type of command to build. program_path:... | stack_v2_sparse_classes_36k_train_033597 | 2,819 | no_license | [
{
"docstring": "Configure how the director should configure the builders. Args: builder: Choose which type of command to build. program_path: Override the location of exiv2 utility.",
"name": "__init__",
"signature": "def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path())"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_001888 | Implement the Python class `Exiv2CommandBuilder` described below.
Class description:
Use this to generate commands for sending to exiv2.
Method signatures and docstrings:
- def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path()): Configure how the director should configure the builders. Args: buil... | Implement the Python class `Exiv2CommandBuilder` described below.
Class description:
Use this to generate commands for sending to exiv2.
Method signatures and docstrings:
- def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path()): Configure how the director should configure the builders. Args: buil... | 452fc7dec411b2af76aa5a34409ea3fa0ec0e29e | <|skeleton|>
class Exiv2CommandBuilder:
"""Use this to generate commands for sending to exiv2."""
def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path()):
"""Configure how the director should configure the builders. Args: builder: Choose which type of command to build. program_path:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exiv2CommandBuilder:
"""Use this to generate commands for sending to exiv2."""
def __init__(self, builder: AbsBuilder, program_path: str=get_exiv2_path()):
"""Configure how the director should configure the builders. Args: builder: Choose which type of command to build. program_path: Override the... | the_stack_v2_python_sparse | dcc_jp2_converter/modules/exiv2Driver/exiv2commandbuilder.py | jtgorman/DCC_jp2_converter | train | 0 |
7b3dc8838ab8abd0d0562fc642e1246bb223135f | [
"member_id = self.alt_tenant_id\nimage = self.images_behavior.create_image_via_task()\nresponse = self.images_client.add_member(image.id_, member_id)\nself.assertEqual(response.status_code, 200)\nmember = response.entity\nresponse = self.images_client.get_member(image.id_, member.member_id)\nself.assertEqual(respon... | <|body_start_0|>
member_id = self.alt_tenant_id
image = self.images_behavior.create_image_via_task()
response = self.images_client.add_member(image.id_, member_id)
self.assertEqual(response.status_code, 200)
member = response.entity
response = self.images_client.get_membe... | TestGetImageMember | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
<|b... | stack_v2_sparse_classes_36k_train_033598 | 2,773 | permissive | [
{
"docstring": "@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data",
"name": "test_get_image_member",
"signature": "def test_get_image_me... | 2 | stack_v2_sparse_classes_30k_test_000607 | Implement the Python class `TestGetImageMember` described below.
Class description:
Implement the TestGetImageMember class.
Method signatures and docstrings:
- def test_get_image_member(self): @summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5)... | Implement the Python class `TestGetImageMember` described below.
Class description:
Implement the TestGetImageMember class.
Method signatures and docstrings:
- def test_get_image_member(self): @summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5)... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
member_id = self.... | the_stack_v2_python_sparse | cloudroast/images/v2/functional/test_get_image_member.py | RULCSoft/cloudroast | train | 1 | |
aeff8d5acd7a4d89e00f382ceed5d9c145314278 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ExportPostRequestBody()",
"from ........models.security.export_file_structure import ExportFileStructure\nfrom ........models.security.export_options import ExportOptions\nfrom ........models.security.export_file_structure import Expor... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ExportPostRequestBody()
<|end_body_0|>
<|body_start_1|>
from ........models.security.export_file_structure import ExportFileStructure
from ........models.security.export_options import E... | ExportPostRequestBody | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExportPostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExportPostRequestBody:
"""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 th... | stack_v2_sparse_classes_36k_train_033599 | 3,517 | 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: ExportPostRequestBody",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `ExportPostRequestBody` described below.
Class description:
Implement the ExportPostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExportPostRequestBody: Creates a new instance of the appropriate class base... | Implement the Python class `ExportPostRequestBody` described below.
Class description:
Implement the ExportPostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExportPostRequestBody: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ExportPostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExportPostRequestBody:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExportPostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ExportPostRequestBody:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/security/cases/ediscovery_cases/item/review_sets/item/microsoft_graph_security_export/export_post_request_body.py | microsoftgraph/msgraph-sdk-python | train | 135 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.