blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
888a4acfa32b1adf7a54521f3d6a695973d61eb0 | [
"if contents:\n assert isinstance(contents, MemoryBuffer)\nif filename is not None:\n contents = MemoryBuffer(filename=filename)\nif contents is None:\n raise Exception('No input found.')\nptr = lib.LLVMCreateObjectFile(contents)\nLLVMObject.__init__(self, ptr, disposer=lib.LLVMDisposeObjectFile)\nself.tak... | <|body_start_0|>
if contents:
assert isinstance(contents, MemoryBuffer)
if filename is not None:
contents = MemoryBuffer(filename=filename)
if contents is None:
raise Exception('No input found.')
ptr = lib.LLVMCreateObjectFile(contents)
LLVMObj... | Represents an object/binary file. | ObjectFile | [
"NCSA",
"LLVM-exception",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like st... | stack_v2_sparse_classes_10k_train_003600 | 16,044 | permissive | [
{
"docstring": "Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like str) or a llvm.core.MemoryBuffer instance.",
"name": "__init__",
"signature": "def __init__(self, filename=None... | 3 | stack_v2_sparse_classes_30k_train_001478 | Implement the Python class `ObjectFile` described below.
Class description:
Represents an object/binary file.
Method signatures and docstrings:
- def __init__(self, filename=None, contents=None): Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). co... | Implement the Python class `ObjectFile` described below.
Class description:
Represents an object/binary file.
Method signatures and docstrings:
- def __init__(self, filename=None, contents=None): Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). co... | 700d4b7795d76a37110f8acfb6f05ee4894ab651 | <|skeleton|>
class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like st... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ObjectFile:
"""Represents an object/binary file."""
def __init__(self, filename=None, contents=None):
"""Construct an instance from a filename or binary data. filename must be a path to a file that can be opened with open(). contents can be either a native Python buffer type (like str) or a llvm.... | the_stack_v2_python_sparse | bindings/python/llvm/object.py | etclabscore/evm_llvm | train | 88 |
7971ae69eec593041f3bb59c11e8855bb4f0e8ff | [
"if sampling_strategy == 'easy':\n sampling_fn = sample_easy_alternative\nelif sampling_strategy == 'hard':\n sampling_fn = sample_hard_alternative\nelse:\n raise ValueError('Only easy and hard sampling are currently supported.')\nself.design = PGMDesign(random_state, num_relations, atom_counts, num_rows, ... | <|body_start_0|>
if sampling_strategy == 'easy':
sampling_fn = sample_easy_alternative
elif sampling_strategy == 'hard':
sampling_fn = sample_hard_alternative
else:
raise ValueError('Only easy and hard sampling are currently supported.')
self.design = ... | PGM where ground-truh factors are represented as integer values. | PGM | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the ... | stack_v2_sparse_classes_10k_train_003601 | 10,947 | permissive | [
{
"docstring": "Creates a PGM. Args: random_state: np.random.RandomState used to sample the PGM. num_relations: Number of relations to enforce for each row in the PGM. atom_counts: List that contains the number of atoms for each of the ground-truth factors. sampling_strategy: Either `easy` or `hard`. For `easy`... | 2 | stack_v2_sparse_classes_30k_train_006462 | Implement the Python class `PGM` described below.
Class description:
PGM where ground-truh factors are represented as integer values.
Method signatures and docstrings:
- def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6): Creates a PGM. Args... | Implement the Python class `PGM` described below.
Class description:
PGM where ground-truh factors are represented as integer values.
Method signatures and docstrings:
- def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6): Creates a PGM. Args... | 73d4b995e88efdd5ffbe98a72e48a620c58f4dc7 | <|skeleton|>
class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PGM:
"""PGM where ground-truh factors are represented as integer values."""
def __init__(self, random_state, num_relations, atom_counts, sampling_strategy='easy', num_rows=3, num_cols=3, num_solutions=6):
"""Creates a PGM. Args: random_state: np.random.RandomState used to sample the PGM. num_rela... | the_stack_v2_python_sparse | disentanglement_lib/evaluation/abstract_reasoning/pgm_utils.py | travers-rhodes/disentanglement_lib | train | 0 |
894d068ac9d964bbbcbe791d4e891c2f63d78f4e | [
"data = []\ntry:\n while True:\n data.append(self.instrument.read())\nexcept pyvisa.VisaIOError:\n pass\nreturn data",
"data = []\ntry:\n while True:\n data.append(self.instrument.read_bytes(1))\nexcept pyvisa.VisaIOError:\n pass\nreturn data"
] | <|body_start_0|>
data = []
try:
while True:
data.append(self.instrument.read())
except pyvisa.VisaIOError:
pass
return data
<|end_body_0|>
<|body_start_1|>
data = []
try:
while True:
data.append(self.ins... | PyVisaInstrument | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
<|body_0|>
def read_all_bytes(self):
"""Helper func for when read/writes are out of sync - consu... | stack_v2_sparse_classes_10k_train_003602 | 1,224 | permissive | [
{
"docstring": "Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.",
"name": "read_all",
"signature": "def read_all(self)"
},
{
"docstring": "Helper func for when read/writes are out of sync - consume all waiting reads u... | 2 | stack_v2_sparse_classes_30k_train_000229 | Implement the Python class `PyVisaInstrument` described below.
Class description:
Implement the PyVisaInstrument class.
Method signatures and docstrings:
- def read_all(self): Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.
- def read_all_... | Implement the Python class `PyVisaInstrument` described below.
Class description:
Implement the PyVisaInstrument class.
Method signatures and docstrings:
- def read_all(self): Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data.
- def read_all_... | c89dfbd87533b7a402d0ce8217daef5be25389c8 | <|skeleton|>
class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
<|body_0|>
def read_all_bytes(self):
"""Helper func for when read/writes are out of sync - consu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PyVisaInstrument:
def read_all(self):
"""Helper func for when read/writes are out of sync - consume all waiting reads until buffer is empty. :return list of read data."""
data = []
try:
while True:
data.append(self.instrument.read())
except pyvisa.Vi... | the_stack_v2_python_sparse | catkit/hardware/pyvisa_instrument.py | spacetelescope/catkit | train | 3 | |
9c260e7b1cd639ea8444901e53e07223c6d685aa | [
"if context is None:\n context = {}\nreturn context.get('type', False)",
"if 'number' not in vals or vals.get('number') == '/':\n seq = self.pool.get('ir.sequence').get(cr, user, 'account.budget.niss')\n vals['number'] = seq and seq or '/'\n if not seq:\n raise osv.except_osv(_('Warning'), _(\"... | <|body_start_0|>
if context is None:
context = {}
return context.get('type', False)
<|end_body_0|>
<|body_start_1|>
if 'number' not in vals or vals.get('number') == '/':
seq = self.pool.get('ir.sequence').get(cr, user, 'account.budget.niss')
vals['number'] = ... | account_budget_niss | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
<|body_0|>
def create(self, cr, user, vals, context=None):
"""Override to add constrain of sequance @param vals: Dictionary of values @return: super of e... | stack_v2_sparse_classes_10k_train_003603 | 4,517 | no_license | [
{
"docstring": "Get type of Budget @return : type or False",
"name": "_get_type",
"signature": "def _get_type(self, cr, uid, context=None)"
},
{
"docstring": "Override to add constrain of sequance @param vals: Dictionary of values @return: super of exchange_order",
"name": "create",
"sig... | 3 | null | Implement the Python class `account_budget_niss` described below.
Class description:
Implement the account_budget_niss class.
Method signatures and docstrings:
- def _get_type(self, cr, uid, context=None): Get type of Budget @return : type or False
- def create(self, cr, user, vals, context=None): Override to add con... | Implement the Python class `account_budget_niss` described below.
Class description:
Implement the account_budget_niss class.
Method signatures and docstrings:
- def _get_type(self, cr, uid, context=None): Get type of Budget @return : type or False
- def create(self, cr, user, vals, context=None): Override to add con... | 0b997095c260d58b026440967fea3a202bef7efb | <|skeleton|>
class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
<|body_0|>
def create(self, cr, user, vals, context=None):
"""Override to add constrain of sequance @param vals: Dictionary of values @return: super of e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class account_budget_niss:
def _get_type(self, cr, uid, context=None):
"""Get type of Budget @return : type or False"""
if context is None:
context = {}
return context.get('type', False)
def create(self, cr, user, vals, context=None):
"""Override to add constrain of ... | the_stack_v2_python_sparse | v_7/NISS/shamil_v3/account_budget_niss/account_budget_niss.py | musabahmed/baba | train | 0 | |
60726b77b088184efdeabb5df32fc0acaf1dc4cb | [
"super().__init__(reporters, max_iterations, evaluator, individual_generator, target_fitness)\nself.parent_count = parent_count\nself.children_count = children_count\nself.mutation = mutation\nself.elitism = elitism\nself.crossover = crossover\nself.population = individual_generator.batch_generate(self.parent_count... | <|body_start_0|>
super().__init__(reporters, max_iterations, evaluator, individual_generator, target_fitness)
self.parent_count = parent_count
self.children_count = children_count
self.mutation = mutation
self.elitism = elitism
self.crossover = crossover
self.popu... | Evolution strategy class | EvolutionStrategy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporter... | stack_v2_sparse_classes_10k_train_003604 | 3,336 | no_license | [
{
"docstring": "Initialize hyperparamters of the algorithm. :param reporters: List of Reporter instances :param max_iterations: Max iterations of the algorithm :param evaluator: Evaluator instance :param individual_generator: Individual factory :param parent_count: mu - size of the parent population :param chil... | 3 | stack_v2_sparse_classes_30k_train_002478 | Implement the Python class `EvolutionStrategy` described below.
Class description:
Evolution strategy class
Method signatures and docstrings:
- def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None): In... | Implement the Python class `EvolutionStrategy` described below.
Class description:
Evolution strategy class
Method signatures and docstrings:
- def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None): In... | 30d87754ed22aa5aab7103d912c414f5a6150a34 | <|skeleton|>
class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporter... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EvolutionStrategy:
"""Evolution strategy class"""
def __init__(self, reporters, max_iterations, evaluator, individual_generator, parent_count, children_count, mutation, elitism=False, crossover=None, target_fitness=None):
"""Initialize hyperparamters of the algorithm. :param reporters: List of Re... | the_stack_v2_python_sparse | algorithms/evolution_strategy.py | Yabk/SF-Evolution | train | 0 |
475bf52730ecbcdabcb36c14bf5a9c089e361a53 | [
"n = 0\nfor i, c in enumerate(S):\n if c.isdigit():\n n = n * int(c)\n else:\n n += 1\nfor j in range(i, -1, -1):\n c = S[j]\n if c.isdigit():\n n //= int(c)\n K %= n\n else:\n if K == n or K == 0:\n return c\n n -= 1",
"tmp = ''\nfor c in S:\n ... | <|body_start_0|>
n = 0
for i, c in enumerate(S):
if c.isdigit():
n = n * int(c)
else:
n += 1
for j in range(i, -1, -1):
c = S[j]
if c.isdigit():
n //= int(c)
K %= n
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_0|>
def decodeAtIndex_own_MLE(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = 0
for i, c in... | stack_v2_sparse_classes_10k_train_003605 | 949 | no_license | [
{
"docstring": ":type S: str :type K: int :rtype: str",
"name": "decodeAtIndex",
"signature": "def decodeAtIndex(self, S, K)"
},
{
"docstring": ":type S: str :type K: int :rtype: str",
"name": "decodeAtIndex_own_MLE",
"signature": "def decodeAtIndex_own_MLE(self, S, K)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002470 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S, K): :type S: str :type K: int :rtype: str
- def decodeAtIndex_own_MLE(self, S, K): :type S: str :type K: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeAtIndex(self, S, K): :type S: str :type K: int :rtype: str
- def decodeAtIndex_own_MLE(self, S, K): :type S: str :type K: int :rtype: str
<|skeleton|>
class Solution:
... | 929dde1723fb2f54870c8a9badc80fc23e8400d3 | <|skeleton|>
class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_0|>
def decodeAtIndex_own_MLE(self, S, K):
""":type S: str :type K: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeAtIndex(self, S, K):
""":type S: str :type K: int :rtype: str"""
n = 0
for i, c in enumerate(S):
if c.isdigit():
n = n * int(c)
else:
n += 1
for j in range(i, -1, -1):
c = S[j]
i... | the_stack_v2_python_sparse | _algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0851_0900/LeetCode0880_DecodedStringAtIndex.py | syurskyi/Algorithms_and_Data_Structure | train | 4 | |
85b7c5dc6d142e4d24efdcab7991750d1981a662 | [
"SQL_mgr = SQL_database_manager()\nfor i in range(len(self.shapes)):\n shape = setpoint_shape + list(self.shapes[i])\n if i <= len(self.oid):\n if len(self.data) > i:\n arr = self.data[i]\n else:\n arr = np.full(shape, np.nan, order='C')\n self.data.append(arr)\n... | <|body_start_0|>
SQL_mgr = SQL_database_manager()
for i in range(len(self.shapes)):
shape = setpoint_shape + list(self.shapes[i])
if i <= len(self.oid):
if len(self.data) > i:
arr = self.data[i]
else:
arr = n... | dataclass_raw_parent | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the ... | stack_v2_sparse_classes_10k_train_003606 | 7,808 | permissive | [
{
"docstring": "generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the setpoint)",
"name": "generate_data_buffer",
"signature": "def generate_data_... | 3 | stack_v2_sparse_classes_30k_train_001301 | Implement the Python class `dataclass_raw_parent` described below.
Class description:
Implement the dataclass_raw_parent class.
Method signatures and docstrings:
- def generate_data_buffer(self, setpoint_shape=[]): generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : s... | Implement the Python class `dataclass_raw_parent` described below.
Class description:
Implement the dataclass_raw_parent class.
Method signatures and docstrings:
- def generate_data_buffer(self, setpoint_shape=[]): generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : s... | dd16192256a4a2fb084f179a5eb80cf13fe689dc | <|skeleton|>
class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class dataclass_raw_parent:
def generate_data_buffer(self, setpoint_shape=[]):
"""generate the buffers that are needed to write the data to the database. Args: setpoint_shape (list) : shape of the setpoints (if applicable) (measurent param is measured exactly the same amount of times than the setpoint)"""
... | the_stack_v2_python_sparse | core_tools/data/lib/data_class.py | stephanlphilips/core_tools | train | 1 | |
ec259df031dc0f5f6488d834a865a51182284efd | [
"logic = CourseLogic(self.auth, sid, cid)\nparams = ParamsParser(request.GET)\nlimit = params.int('limit', desc='每页最大渲染数', require=False, default=10)\npage = params.int('page', desc='当前页数', require=False, default=1)\nevaluates = PracticeEvaluateTeacherToStudent.objects.filter(author=logic.course.author).values('id'... | <|body_start_0|>
logic = CourseLogic(self.auth, sid, cid)
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, default=10)
page = params.int('page', desc='当前页数', require=False, default=1)
evaluates = PracticeEvaluateTeacherToStudent.object... | PracticeTeacherToStudentListMgetView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PracticeTeacherToStudentListMgetView:
def get(self, request, sid, cid):
"""获取老师对学生评价列表 :param request: :param sid: :param cid: :return:"""
<|body_0|>
def post(self, request, sid, cid):
"""批量获取老师对学生评价 :param request: :param sid: :param cid: :return:"""
<|body_... | stack_v2_sparse_classes_10k_train_003607 | 4,837 | no_license | [
{
"docstring": "获取老师对学生评价列表 :param request: :param sid: :param cid: :return:",
"name": "get",
"signature": "def get(self, request, sid, cid)"
},
{
"docstring": "批量获取老师对学生评价 :param request: :param sid: :param cid: :return:",
"name": "post",
"signature": "def post(self, request, sid, cid)"... | 2 | stack_v2_sparse_classes_30k_test_000334 | Implement the Python class `PracticeTeacherToStudentListMgetView` described below.
Class description:
Implement the PracticeTeacherToStudentListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid): 获取老师对学生评价列表 :param request: :param sid: :param cid: :return:
- def post(self, request, s... | Implement the Python class `PracticeTeacherToStudentListMgetView` described below.
Class description:
Implement the PracticeTeacherToStudentListMgetView class.
Method signatures and docstrings:
- def get(self, request, sid, cid): 获取老师对学生评价列表 :param request: :param sid: :param cid: :return:
- def post(self, request, s... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class PracticeTeacherToStudentListMgetView:
def get(self, request, sid, cid):
"""获取老师对学生评价列表 :param request: :param sid: :param cid: :return:"""
<|body_0|>
def post(self, request, sid, cid):
"""批量获取老师对学生评价 :param request: :param sid: :param cid: :return:"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PracticeTeacherToStudentListMgetView:
def get(self, request, sid, cid):
"""获取老师对学生评价列表 :param request: :param sid: :param cid: :return:"""
logic = CourseLogic(self.auth, sid, cid)
params = ParamsParser(request.GET)
limit = params.int('limit', desc='每页最大渲染数', require=False, defa... | the_stack_v2_python_sparse | FireHydrant/server/practice/views/evaluate/teacher_student.py | shoogoome/FireHydrant | train | 4 | |
eac0161a70cd6ae7415ac33de27bbd97916a5be8 | [
"res = 0\nflag = 0\ncount = {}\nfor i in s:\n if i in count:\n count[i] += 1\n else:\n count[i] = 1\nfor c in count.values():\n if c % 2 == 0:\n res += c\n else:\n res += c - 1\n flag = 1\nif flag == 1:\n return res + 1\nreturn res",
"letter = [chr(i) for i in ran... | <|body_start_0|>
res = 0
flag = 0
count = {}
for i in s:
if i in count:
count[i] += 1
else:
count[i] = 1
for c in count.values():
if c % 2 == 0:
res += c
else:
res += c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
flag = 0
count = {}
for i... | stack_v2_sparse_classes_10k_train_003608 | 1,286 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "longestPalindrome",
"signature": "def longestPalindrome(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004610 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindrome(self, s): :type s: str :rtype: int
- def longestPalindrome(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def longestPalindrome(self,... | c92a5ddcc56e3f69be1e6fb25e9c8ed277e57ee0 | <|skeleton|>
class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindrome(self, s):
""":type s: str :rtype: int"""
res = 0
flag = 0
count = {}
for i in s:
if i in count:
count[i] += 1
else:
count[i] = 1
for c in count.values():
if c % 2... | the_stack_v2_python_sparse | code/409#Longest Palindrome.py | EachenKuang/LeetCode | train | 28 | |
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_10k_train_003609 | 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 | null | 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_10k | 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 |
6c89dbc9f61c9fb734c5d383eabecfae4100c1d1 | [
"with open(filename, newline='') as csvfile:\n dict_list = []\n csv_data = csv.reader(csvfile)\n headers = next(csv_data, None)\n if headers[0].startswith(''):\n headers[0] = headers[0][3:]\n for row in csv_data:\n row_dict = {}\n for index, column in enumerate(headers):\n ... | <|body_start_0|>
with open(filename, newline='') as csvfile:
dict_list = []
csv_data = csv.reader(csvfile)
headers = next(csv_data, None)
if headers[0].startswith(''):
headers[0] = headers[0][3:]
for row in csv_data:
... | Meta class | Database | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Database:
"""Meta class"""
def _import_csv(self, filename):
"""Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries"""
<|body_0|>
def _add_bulk_data(self, collection, directory_name, filename):
"""If it w... | stack_v2_sparse_classes_10k_train_003610 | 7,786 | no_license | [
{
"docstring": "Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries",
"name": "_import_csv",
"signature": "def _import_csv(self, filename)"
},
{
"docstring": "If it works properly, it will handle the bulk imports from the csv files",
... | 6 | null | Implement the Python class `Database` described below.
Class description:
Meta class
Method signatures and docstrings:
- def _import_csv(self, filename): Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries
- def _add_bulk_data(self, collection, directory_nam... | Implement the Python class `Database` described below.
Class description:
Meta class
Method signatures and docstrings:
- def _import_csv(self, filename): Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries
- def _add_bulk_data(self, collection, directory_nam... | ac12beeae8aa57135bbcd03ac7a4f977fa3bdb56 | <|skeleton|>
class Database:
"""Meta class"""
def _import_csv(self, filename):
"""Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries"""
<|body_0|>
def _add_bulk_data(self, collection, directory_name, filename):
"""If it w... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Database:
"""Meta class"""
def _import_csv(self, filename):
"""Returns a list of dictionaries.One dictionary for each row of data in a csv file. :return: list of dictionaries"""
with open(filename, newline='') as csvfile:
dict_list = []
csv_data = csv.reader(csvfil... | the_stack_v2_python_sparse | students/Shirin_A/lesson10/assignment/src/database.py | UWPCE-PythonCert-ClassRepos/py220-online-201904-V2 | train | 1 |
2319f3990263870019dd1a19f229ef07d28e2d68 | [
"super().__init__(coordinator)\nself.entity_description = description\nself._attr_unique_id = f\"{coordinator.data['deviceID']}-{description.key}\"",
"if (value := self.coordinator.data.get(self.entity_description.key)) is None:\n return None\nreturn bool(value)"
] | <|body_start_0|>
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.data['deviceID']}-{description.key}"
<|end_body_0|>
<|body_start_1|>
if (value := self.coordinator.data.get(self.entity_description.key)) is None:
retur... | Representation of a Fully Kiosk Browser binary sensor. | FullyBinarySensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FullyBinarySensor:
"""Representation of a Fully Kiosk Browser binary sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None:
"""Initialize the binary sensor."""
<|body_0|>
def is_on(self) -> bool | ... | stack_v2_sparse_classes_10k_train_003611 | 2,325 | permissive | [
{
"docstring": "Initialize the binary sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None"
},
{
"docstring": "Return if the binary sensor is on.",
"name": "is_on",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_003794 | Implement the Python class `FullyBinarySensor` described below.
Class description:
Representation of a Fully Kiosk Browser binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None: Initialize the binary sens... | Implement the Python class `FullyBinarySensor` described below.
Class description:
Representation of a Fully Kiosk Browser binary sensor.
Method signatures and docstrings:
- def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None: Initialize the binary sens... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class FullyBinarySensor:
"""Representation of a Fully Kiosk Browser binary sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None:
"""Initialize the binary sensor."""
<|body_0|>
def is_on(self) -> bool | ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FullyBinarySensor:
"""Representation of a Fully Kiosk Browser binary sensor."""
def __init__(self, coordinator: FullyKioskDataUpdateCoordinator, description: BinarySensorEntityDescription) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator)
self.entity_descr... | the_stack_v2_python_sparse | homeassistant/components/fully_kiosk/binary_sensor.py | home-assistant/core | train | 35,501 |
d267fbb2880065bf54cb737b7a95791f39abb1ee | [
"self.q = []\nself.q2 = []\nself.tag = 1",
"if self.tag == 1:\n self.q.append(x)\nelse:\n self.q2.append(x)",
"if self.tag == 1:\n while len(self.q) > 1:\n t = self.q.pop(0)\n self.q2.append(t)\n self.tag = 2\n return self.q.pop(0)\nelse:\n while len(self.q2) > 1:\n t = se... | <|body_start_0|>
self.q = []
self.q2 = []
self.tag = 1
<|end_body_0|>
<|body_start_1|>
if self.tag == 1:
self.q.append(x)
else:
self.q2.append(x)
<|end_body_1|>
<|body_start_2|>
if self.tag == 1:
while len(self.q) > 1:
... | MyStack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyStack:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
<|body_1|>
def pop(self):
"""Removes the element on top of the stack and returns that... | stack_v2_sparse_classes_10k_train_003612 | 1,852 | no_license | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Push element x onto stack. :type x: int :rtype: None",
"name": "push",
"signature": "def push(self, x)"
},
{
"docstring": "Removes the element on top of... | 5 | null | Implement the Python class `MyStack` described below.
Class description:
Implement the MyStack class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def push(self, x): Push element x onto stack. :type x: int :rtype: None
- def pop(self): Removes the element on top of th... | Implement the Python class `MyStack` described below.
Class description:
Implement the MyStack class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def push(self, x): Push element x onto stack. :type x: int :rtype: None
- def pop(self): Removes the element on top of th... | fd6c8082f81bcd9eda084b347c77fd570cfbee4a | <|skeleton|>
class MyStack:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
<|body_1|>
def pop(self):
"""Removes the element on top of the stack and returns that... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MyStack:
def __init__(self):
"""Initialize your data structure here."""
self.q = []
self.q2 = []
self.tag = 1
def push(self, x):
"""Push element x onto stack. :type x: int :rtype: None"""
if self.tag == 1:
self.q.append(x)
else:
... | the_stack_v2_python_sparse | problems/225/test.py | neuxxm/leetcode | train | 0 | |
fe9bc94758b8ba4ae12d0873b8435bd1637b6c44 | [
"self.rect = Rect((0, 0), size)\nself.image = pygame.display.set_mode(size, flags, depth)\nself._opengl = flags & OPENGL\nwidgets._locals.SCREEN = self\nwidgets._locals.Font.set_fonts()",
"if attr != 'image':\n return getattr(self.image, attr)\nraise AttributeError('image')"
] | <|body_start_0|>
self.rect = Rect((0, 0), size)
self.image = pygame.display.set_mode(size, flags, depth)
self._opengl = flags & OPENGL
widgets._locals.SCREEN = self
widgets._locals.Font.set_fonts()
<|end_body_0|>
<|body_start_1|>
if attr != 'image':
return ge... | Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size. | Screen | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.di... | stack_v2_sparse_classes_10k_train_003613 | 1,201 | permissive | [
{
"docstring": "Args: size, flags, depth: Arguments for pygame.display.set_mode()",
"name": "__init__",
"signature": "def __init__(self, size, flags=0, depth=0)"
},
{
"docstring": "Redirect attribute access to self.image",
"name": "__getattr__",
"signature": "def __getattr__(self, attr)"... | 2 | null | Implement the Python class `Screen` described below.
Class description:
Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size.
Method signatures and docstrings:
- def __init__(self, size, flags=0, de... | Implement the Python class `Screen` described below.
Class description:
Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size.
Method signatures and docstrings:
- def __init__(self, size, flags=0, de... | 95cb53b664f312e0830f010c0c96be94d4a4db90 | <|skeleton|>
class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.di... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Screen:
"""Class for the screen. This must be used instead of ``pygame.display.set_mode()``. Attributes: image: The pygame.display screen. rect: ``pygame.Rect`` containing screen size."""
def __init__(self, size, flags=0, depth=0):
"""Args: size, flags, depth: Arguments for pygame.display.set_mod... | the_stack_v2_python_sparse | pygame/GUI- widgets-SGC/sgc/surface.py | furas/python-examples | train | 176 |
48c465e44c706d49317aa6a4b55332d23166d421 | [
"super(CNN, self).__init__()\nself.input_channel_count = input_channel_count\nself.output_channel_count = output_channel_count\nself.conv = nn.Conv1d(in_channels=input_channel_count, out_channels=output_channel_count, kernel_size=kernel_size)\nself.max_pool = nn.AdaptiveMaxPool1d(output_size=1)\nself.relu = nn.ReLU... | <|body_start_0|>
super(CNN, self).__init__()
self.input_channel_count = input_channel_count
self.output_channel_count = output_channel_count
self.conv = nn.Conv1d(in_channels=input_channel_count, out_channels=output_channel_count, kernel_size=kernel_size)
self.max_pool = nn.Adapt... | CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
"""CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input"""
def __init__(self, input_channel_count, output_channel_count, kernel_size=5):
"""Init HighWay Instance. @param input_channel_count: int @param output_channel_count: int @param ke... | stack_v2_sparse_classes_10k_train_003614 | 2,032 | no_license | [
{
"docstring": "Init HighWay Instance. @param input_channel_count: int @param output_channel_count: int @param kernel_size: int",
"name": "__init__",
"signature": "def __init__(self, input_channel_count, output_channel_count, kernel_size=5)"
},
{
"docstring": "Run a forward step that map a batch... | 2 | stack_v2_sparse_classes_30k_train_006959 | Implement the Python class `CNN` described below.
Class description:
CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input
Method signatures and docstrings:
- def __init__(self, input_channel_count, output_channel_count, kernel_size=5): Init HighWay Instance. @param input_chan... | Implement the Python class `CNN` described below.
Class description:
CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input
Method signatures and docstrings:
- def __init__(self, input_channel_count, output_channel_count, kernel_size=5): Init HighWay Instance. @param input_chan... | a883935d779dca3a3cc443c3fa6d6a455f21e87a | <|skeleton|>
class CNN:
"""CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input"""
def __init__(self, input_channel_count, output_channel_count, kernel_size=5):
"""Init HighWay Instance. @param input_channel_count: int @param output_channel_count: int @param ke... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CNN:
"""CNN Layer, i.e. a layer of cnn network that takes the output of convolutional network as input"""
def __init__(self, input_channel_count, output_channel_count, kernel_size=5):
"""Init HighWay Instance. @param input_channel_count: int @param output_channel_count: int @param kernel_size: in... | the_stack_v2_python_sparse | stanford_nlp/a5/cnn.py | guocongyun/ml-projects | train | 0 |
0f9c22d0619771241895bda5077b516105d52d89 | [
"self.X = X\nself.M = np.shape(X)[0]\nself.N = np.shape(X)[1]",
"x = np.zeros([self.M, self.N], dtype=np.complex)\nfor m in range(self.M):\n for n in range(self.N):\n for i in range(self.M):\n for j in range(self.N):\n x[m, n] = x[m, n] + self.X[i, j] / np.sqrt(self.M * self.N)... | <|body_start_0|>
self.X = X
self.M = np.shape(X)[0]
self.N = np.shape(X)[1]
<|end_body_0|>
<|body_start_1|>
x = np.zeros([self.M, self.N], dtype=np.complex)
for m in range(self.M):
for n in range(self.N):
for i in range(self.M):
fo... | 2-D iDFT | iDFT_2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class iDFT_2D:
"""2-D iDFT"""
def __init__(self, X):
"""Input DFT X"""
<|body_0|>
def solve1(self):
"""\\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients"""
<|body_1|>
def solve2(self):
"""\\\\\\ METHOD: Compute the iDFT of X with N^2/2 coe... | stack_v2_sparse_classes_10k_train_003615 | 4,947 | no_license | [
{
"docstring": "Input DFT X",
"name": "__init__",
"signature": "def __init__(self, X)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients",
"name": "solve1",
"signature": "def solve1(self)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the iDFT ... | 3 | stack_v2_sparse_classes_30k_train_004464 | Implement the Python class `iDFT_2D` described below.
Class description:
2-D iDFT
Method signatures and docstrings:
- def __init__(self, X): Input DFT X
- def solve1(self): \\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients
- def solve2(self): \\\\\\ METHOD: Compute the iDFT of X with N^2/2 coefficients | Implement the Python class `iDFT_2D` described below.
Class description:
2-D iDFT
Method signatures and docstrings:
- def __init__(self, X): Input DFT X
- def solve1(self): \\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients
- def solve2(self): \\\\\\ METHOD: Compute the iDFT of X with N^2/2 coefficients
<|sk... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class iDFT_2D:
"""2-D iDFT"""
def __init__(self, X):
"""Input DFT X"""
<|body_0|>
def solve1(self):
"""\\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients"""
<|body_1|>
def solve2(self):
"""\\\\\\ METHOD: Compute the iDFT of X with N^2/2 coe... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class iDFT_2D:
"""2-D iDFT"""
def __init__(self, X):
"""Input DFT X"""
self.X = X
self.M = np.shape(X)[0]
self.N = np.shape(X)[1]
def solve1(self):
"""\\\\\\ METHOD: Compute the iDFT of X with N^2 coefficients"""
x = np.zeros([self.M, self.N], dtype=np.compl... | the_stack_v2_python_sparse | 2D Signal Processing and Image De-noising/discrete_signal.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
215b74cafe6e62706a6365c119a6769207ae42ce | [
"super(FACHead, self).__init__(name=name)\nself.vid_to_hid = tf.keras.layers.Dense(vid_to_aud_txt_kwargs['d_model'], use_bias=False, name='vid_to_hid')\nself.hid_to_va = mlp_lib.ReluDenseBN(pre_bn=True, d_model=vid_to_aud_txt_kwargs['d_model'], bn_config=bn_config, use_xreplica_bn=use_xreplica_bn, name='hid_to_va')... | <|body_start_0|>
super(FACHead, self).__init__(name=name)
self.vid_to_hid = tf.keras.layers.Dense(vid_to_aud_txt_kwargs['d_model'], use_bias=False, name='vid_to_hid')
self.hid_to_va = mlp_lib.ReluDenseBN(pre_bn=True, d_model=vid_to_aud_txt_kwargs['d_model'], bn_config=bn_config, use_xreplica_bn=... | MLP-based Head to bridge audio, text and video with a FAC style. | FACHead | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_co... | stack_v2_sparse_classes_10k_train_003616 | 6,829 | permissive | [
{
"docstring": "Initialize the Fine-to-Coarse head class. Args: bn_config: batchnorm configuration args use_xreplica_bn: whether to use cross-replica bn stats or not vid_to_aud_txt_kwargs: vid2rest MLP args aud_to_vid_txt_kwargs: aud2rest MLP args txt_to_vid_aud_kwargs: txt2rest MLP args name: graph name. **kwa... | 2 | null | Implement the Python class `FACHead` described below.
Class description:
MLP-based Head to bridge audio, text and video with a FAC style.
Method signatures and docstrings:
- def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwarg... | Implement the Python class `FACHead` described below.
Class description:
MLP-based Head to bridge audio, text and video with a FAC style.
Method signatures and docstrings:
- def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwarg... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_co... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_config: batchno... | the_stack_v2_python_sparse | vatt/modeling/heads/bridge.py | Jimmy-INL/google-research | train | 1 |
53566f9a46522ec2a63a822bcef9f07dd1ae9976 | [
"if filter_name == 'Naive':\n filter_0, filter_1, filter_2 = Naive_Filter()\nelif filter_name == 'Sharpness_Center':\n filter_0, filter_1, filter_2 = Sharpness_Center_Filter()\nelif filter_name == 'Sharpness_Edge':\n filter_0, filter_1, filter_2 = Sharpness_Edge_Filter()\nelif filter_name == 'Edge_Detectio... | <|body_start_0|>
if filter_name == 'Naive':
filter_0, filter_1, filter_2 = Naive_Filter()
elif filter_name == 'Sharpness_Center':
filter_0, filter_1, filter_2 = Sharpness_Center_Filter()
elif filter_name == 'Sharpness_Edge':
filter_0, filter_1, filter_2 = Shar... | Filter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Filter:
def __init__(self, filter_name):
"""Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置"""
<|body_0|>
def do_filter(self, im_bgr):
"""执行滤镜 :param im_bgr 要处理的BGR图片 :return 处理后的BGR图片"""
<|body_1|>
def conv(self, image, filter, image_center... | stack_v2_sparse_classes_10k_train_003617 | 14,709 | no_license | [
{
"docstring": "Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置",
"name": "__init__",
"signature": "def __init__(self, filter_name)"
},
{
"docstring": "执行滤镜 :param im_bgr 要处理的BGR图片 :return 处理后的BGR图片",
"name": "do_filter",
"signature": "def do_filter(self, im_bgr)"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_004971 | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def __init__(self, filter_name): Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置
- def do_filter(self, im_bgr): 执行滤镜 :param im_bgr 要处理的BGR图片 :return 处理后的BGR图片
- def conv... | Implement the Python class `Filter` described below.
Class description:
Implement the Filter class.
Method signatures and docstrings:
- def __init__(self, filter_name): Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置
- def do_filter(self, im_bgr): 执行滤镜 :param im_bgr 要处理的BGR图片 :return 处理后的BGR图片
- def conv... | e5887ccf0a241b757dc4f9aa12bcb89456321a24 | <|skeleton|>
class Filter:
def __init__(self, filter_name):
"""Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置"""
<|body_0|>
def do_filter(self, im_bgr):
"""执行滤镜 :param im_bgr 要处理的BGR图片 :return 处理后的BGR图片"""
<|body_1|>
def conv(self, image, filter, image_center... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Filter:
def __init__(self, filter_name):
"""Choose which filter to be returned 根据用户指定的 滤波器名称,挑选对应的 滤波器配置"""
if filter_name == 'Naive':
filter_0, filter_1, filter_2 = Naive_Filter()
elif filter_name == 'Sharpness_Center':
filter_0, filter_1, filter_2 = Sharpness_... | the_stack_v2_python_sparse | common/imfiltercm.py | elthe/LearnPythonStats | train | 3 | |
3812656732651614bf1c775f7c0a756ecf21571b | [
"if type(metrics) == list:\n metrics = [m + '@' + str(n) for m in metrics for n in n_ranks]\nsuper(DiversityEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep)\nself.n_ranks = n_ranks",
"eval_results = {}\nnum_user = l... | <|body_start_0|>
if type(metrics) == list:
metrics = [m + '@' + str(n) for m in metrics for n in n_ranks]
super(DiversityEvaluation, self).__init__(sep=sep, metrics=metrics, all_but_one_eval=all_but_one_eval, verbose=verbose, as_table=as_table, table_sep=table_sep)
self.n_ranks = n_r... | DiversityEvaluation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiversityEvaluation:
def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'):
"""Class to evaluate predictions in a item recommendation (ranking) sce... | stack_v2_sparse_classes_10k_train_003618 | 14,557 | no_license | [
{
"docstring": "Class to evaluate predictions in a item recommendation (ranking) scenario :param sep: Delimiter for input files :type sep: str, default ' ' :param n_ranks: List of positions to evaluate the ranking :type n_ranks: list, default [1, 3, 5, 10] :param metrics: List of evaluation metrics :type metric... | 2 | stack_v2_sparse_classes_30k_train_005525 | Implement the Python class `DiversityEvaluation` described below.
Class description:
Implement the DiversityEvaluation class.
Method signatures and docstrings:
- def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose... | Implement the Python class `DiversityEvaluation` described below.
Class description:
Implement the DiversityEvaluation class.
Method signatures and docstrings:
- def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose... | b5f870abbe5b5e4311e8f22370af487d2570d9b6 | <|skeleton|>
class DiversityEvaluation:
def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'):
"""Class to evaluate predictions in a item recommendation (ranking) sce... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DiversityEvaluation:
def __init__(self, sep='\t', n_ranks=list([1, 3, 5, 10]), metrics=list(['GENRE_COVERAGE', 'GENRE_REDUNDANCY', 'ILD_GENRE']), all_but_one_eval=False, verbose=True, as_table=False, table_sep='\t'):
"""Class to evaluate predictions in a item recommendation (ranking) scenario :param s... | the_stack_v2_python_sparse | evaluation/diversity_evaluation.py | juarezsacenti/kg-summ-rec | train | 1 | |
1bb0e22f8d35f7fd2dd38700928af1c91c3f7001 | [
"patient_request = json.loads(request.body.decode('utf-8'))\nPatientView.validate_patient_request(patient_request)\nnew_patient_info = PatientService.add_patient(patient_request)\nreturn JsonResponse(new_patient_info)",
"pagination_args = PaginationViewUtils.get_pagination_args(request)\ncurrent_path = request.bu... | <|body_start_0|>
patient_request = json.loads(request.body.decode('utf-8'))
PatientView.validate_patient_request(patient_request)
new_patient_info = PatientService.add_patient(patient_request)
return JsonResponse(new_patient_info)
<|end_body_0|>
<|body_start_1|>
pagination_args ... | All endpoints related to patient actions | PatientView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PatientView:
"""All endpoints related to patient actions"""
def post(request):
"""Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info"""
<|body_0|>
def get(request):
"""Action when cal... | stack_v2_sparse_classes_10k_train_003619 | 7,260 | no_license | [
{
"docstring": "Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info",
"name": "post",
"signature": "def post(request)"
},
{
"docstring": "Action when calling the endpoint with GET Return list of patients :param reques... | 3 | stack_v2_sparse_classes_30k_train_000801 | Implement the Python class `PatientView` described below.
Class description:
All endpoints related to patient actions
Method signatures and docstrings:
- def post(request): Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info
- def get(requ... | Implement the Python class `PatientView` described below.
Class description:
All endpoints related to patient actions
Method signatures and docstrings:
- def post(request): Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info
- def get(requ... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class PatientView:
"""All endpoints related to patient actions"""
def post(request):
"""Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info"""
<|body_0|>
def get(request):
"""Action when cal... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PatientView:
"""All endpoints related to patient actions"""
def post(request):
"""Action when calling the endpoint with POST :param request: request for patient adding :return: json response with new patient info"""
patient_request = json.loads(request.body.decode('utf-8'))
Patien... | the_stack_v2_python_sparse | backend/martin_helder/views/patient_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
2993c58fb7b33bf4320ed9f245d41597339e7e9b | [
"super().__init__()\nif not isinstance(credentials, google.oauth2.credentials.Credentials):\n raise TypeError('Cannot get ID tokens from credentials type %s' % type(credentials))\nself._credentials = credentials\nself._request = request",
"headers = {}\nself._credentials.before_request(self._request, context.m... | <|body_start_0|>
super().__init__()
if not isinstance(credentials, google.oauth2.credentials.Credentials):
raise TypeError('Cannot get ID tokens from credentials type %s' % type(credentials))
self._credentials = credentials
self._request = request
<|end_body_0|>
<|body_start... | A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` property if available (and logs an error otherwise). See http://www.grpc.io/grpc/python/grpc.... | IdTokenAuthMetadataPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdTokenAuthMetadataPlugin:
"""A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` property if available (and logs an error... | stack_v2_sparse_classes_10k_train_003620 | 16,711 | permissive | [
{
"docstring": "Constructs an IdTokenAuthMetadataPlugin. Args: credentials (google.auth.credentials.Credentials): The credentials to add to requests. request (google.auth.transport.Request): A HTTP transport request object used to refresh credentials as needed.",
"name": "__init__",
"signature": "def __... | 2 | null | Implement the Python class `IdTokenAuthMetadataPlugin` described below.
Class description:
A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` p... | Implement the Python class `IdTokenAuthMetadataPlugin` described below.
Class description:
A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` p... | 5961c76dca0fb9bb40d146f5ce13834ac29d8ddb | <|skeleton|>
class IdTokenAuthMetadataPlugin:
"""A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` property if available (and logs an error... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IdTokenAuthMetadataPlugin:
"""A `gRPC AuthMetadataPlugin` that uses ID tokens. This works like the existing `google.auth.transport.grpc.AuthMetadataPlugin` except that instead of always using access tokens, it preferentially uses the `Credentials.id_token` property if available (and logs an error otherwise). ... | the_stack_v2_python_sparse | tensorboard/uploader/auth.py | tensorflow/tensorboard | train | 6,766 |
18aff7108ae0acf145fef485287a630f45124200 | [
"def add(n1, n2, c):\n r = n1 + n2 + c\n return (r % 10, r / 10)\ndummy = ListNode(None)\np, p1, p2 = (dummy, l1, l2)\nc = 0\nwhile p1 and p2:\n r, c = add(p1.val, p2.val, c)\n p.next = ListNode(r)\n p, p1, p2 = (p.next, p1.next, p2.next)\np1 = p1 if p1 else p2\nwhile p1:\n r, c = add(p1.val, 0, c... | <|body_start_0|>
def add(n1, n2, c):
r = n1 + n2 + c
return (r % 10, r / 10)
dummy = ListNode(None)
p, p1, p2 = (dummy, l1, l2)
c = 0
while p1 and p2:
r, c = add(p1.val, p2.val, c)
p.next = ListNode(r)
p, p1, p2 = (p.nex... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_003621 | 1,834 | no_license | [
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers",
"signature": "def addTwoNumbers(self, l1, l2)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "addTwoNumbers2",
"signature": "def addTwoNumbers2(self, l1... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addTwoNumbers(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
- def addTwoNumbers2(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode... | 33b6b68a8136109d2aaa26bb8bf9e873f995d5ab | <|skeleton|>
class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_0|>
def addTwoNumbers2(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def addTwoNumbers(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
def add(n1, n2, c):
r = n1 + n2 + c
return (r % 10, r / 10)
dummy = ListNode(None)
p, p1, p2 = (dummy, l1, l2)
c = 0
while p1 and p2:
... | the_stack_v2_python_sparse | python2/l0002_add_two_numbers.py | sprax/1337 | train | 0 | |
9f44765518ce70b7b0adc98269f254e02d652436 | [
"if request.user.has_perm(VIEW_TEAMTYPE):\n group_types = TeamType.objects.all()\n serializer = TeamTypeSerializer(group_types, many=True)\n return Response(serializer.data)\nelse:\n return Response(status=status.HTTP_401_UNAUTHORIZED)",
"if request.user.has_perm(ADD_TEAMTYPE):\n serializer = TeamT... | <|body_start_0|>
if request.user.has_perm(VIEW_TEAMTYPE):
group_types = TeamType.objects.all()
serializer = TeamTypeSerializer(group_types, many=True)
return Response(serializer.data)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)
<|end_body_0|... | # List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If the request is not valid, send HTTP 400. ... | TeamTypesList | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If ... | stack_v2_sparse_classes_10k_train_003622 | 6,650 | permissive | [
{
"docstring": "docstring.",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "docstring.",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003200 | Implement the Python class `TeamTypesList` described below.
Class description:
# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - cre... | Implement the Python class `TeamTypesList` described below.
Class description:
# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - cre... | 56511ebac83a5dc1fb8768a98bc675e88530a447 | <|skeleton|>
class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeamTypesList:
"""# List all the team types or create a new one. Parameter : request (HttpRequest) : the request coming from the front-end Return : response (Response) : the response. GET request : list all team types and return the data POST request : - create a new team type, send HTTP 201. If the request i... | the_stack_v2_python_sparse | usersmanagement/views/views_teamtypes.py | Open-CMMS/openCMMS_backend | train | 4 |
bccf7d464001b772c5ef5b2ae27506746b8ca710 | [
"if packet.sender is None:\n db = SafeJsonFile(os.path.join(self.home_dir, TOPOLOGY_DB))\n data = db.read()\n if data:\n for item in data.values():\n item['old_data'] = 1\n db.write(data)\nreturn packet",
"ret_params = {}\nupper_neighbours = self.operator.get_neighbours(NT_UPPER)... | <|body_start_0|>
if packet.sender is None:
db = SafeJsonFile(os.path.join(self.home_dir, TOPOLOGY_DB))
data = db.read()
if data:
for item in data.values():
item['old_data'] = 1
db.write(data)
return packet
<|end_body... | TopologyCognition | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyCognition:
def before_resend(self, packet):
"""In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours"... | stack_v2_sparse_classes_10k_train_003623 | 4,056 | no_license | [
{
"docstring": "In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours",
"name": "before_resend",
"signature": "def before_res... | 3 | stack_v2_sparse_classes_30k_train_000909 | Implement the Python class `TopologyCognition` described below.
Class description:
Implement the TopologyCognition class.
Method signatures and docstrings:
- def before_resend(self, packet): In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketR... | Implement the Python class `TopologyCognition` described below.
Class description:
Implement the TopologyCognition class.
Method signatures and docstrings:
- def before_resend(self, packet): In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketR... | 4d02a96e2c6e7f82cef03c7e808e390cdb1f6b6d | <|skeleton|>
class TopologyCognition:
def before_resend(self, packet):
"""In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TopologyCognition:
def before_resend(self, packet):
"""In this method should be implemented packet transformation for resend it to neighbours @params packet - object of FabnetPacketRequest class @return object of FabnetPacketRequest class or None for disabling packet resend to neigbours"""
if ... | the_stack_v2_python_sparse | fabnet/operations/topology_cognition.py | fabregas/fabnet_core | train | 0 | |
d457c9fe405a9070a851369b5dff1a65512123e8 | [
"TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)\ntreatment_report = TreatmentService.treatment_report(id_treatment)\nreturn FileResponse(treatment_report, filename=id_treatment + '_report.pdf')",
"Utils.validate_uuid(id_patient)\nUtils.validate_uuid(id_treatment_cy... | <|body_start_0|>
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
treatment_report = TreatmentService.treatment_report(id_treatment)
return FileResponse(treatment_report, filename=id_treatment + '_report.pdf')
<|end_body_0|>
<|body_start_1|>
... | All endpoints related to treatment report actions | TreatmentReportView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_... | stack_v2_sparse_classes_10k_train_003624 | 2,875 | no_license | [
{
"docstring": "Action when calling the endpoint with GET",
"name": "get",
"signature": "def get(request, id_patient, id_treatment_cycle, id_treatment)"
},
{
"docstring": "Validates the treatment information received in the request body :param id_patient: Id of the patient received :param id_tre... | 2 | stack_v2_sparse_classes_30k_train_006362 | Implement the Python class `TreatmentReportView` described below.
Class description:
All endpoints related to treatment report actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_... | Implement the Python class `TreatmentReportView` described below.
Class description:
All endpoints related to treatment report actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TreatmentReportView:
"""All endpoints related to treatment report actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
... | the_stack_v2_python_sparse | backend/martin_helder/views/treatment_report_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
e45bdd713e59a6b642a30c1d31923a205e1b1325 | [
"momentum = kwargs.pop('momentum', 0.9)\nupdate_vars = tf.trainable_variables()\nreturn tf.train.MomentumOptimizer(self.learning_rate_placeholder, momentum, use_nesterov=False).minimize(self.model.loss, var_list=update_vars)",
"learning_rate_patience = kwargs.pop('learning_rate_patience', 10)\nlearning_rate_decay... | <|body_start_0|>
momentum = kwargs.pop('momentum', 0.9)
update_vars = tf.trainable_variables()
return tf.train.MomentumOptimizer(self.learning_rate_placeholder, momentum, use_nesterov=False).minimize(self.model.loss, var_list=update_vars)
<|end_body_0|>
<|body_start_1|>
learning_rate_pa... | 모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스. | MomentumOptimizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MomentumOptimizer:
"""모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스."""
def _optimize_op(self, **kwargs):
"""경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return tf.Operation."""
<|body_0|>
def _update_learn... | stack_v2_sparse_classes_10k_train_003625 | 2,122 | no_license | [
{
"docstring": "경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return tf.Operation.",
"name": "_optimize_op",
"signature": "def _optimize_op(self, **kwargs)"
},
{
"docstring": "성능 평가 점수 상에 개선이 없을 때, 현 학습률 값을 업데이트함. :param... | 2 | stack_v2_sparse_classes_30k_train_002389 | Implement the Python class `MomentumOptimizer` described below.
Class description:
모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스.
Method signatures and docstrings:
- def _optimize_op(self, **kwargs): 경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return t... | Implement the Python class `MomentumOptimizer` described below.
Class description:
모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스.
Method signatures and docstrings:
- def _optimize_op(self, **kwargs): 경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return t... | af58878beb9f94ba4d6afd628ddb0a6ac6c41746 | <|skeleton|>
class MomentumOptimizer:
"""모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스."""
def _optimize_op(self, **kwargs):
"""경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return tf.Operation."""
<|body_0|>
def _update_learn... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MomentumOptimizer:
"""모멘텀 알고리즘을 포함한 경사 하강 optimizer 클래스."""
def _optimize_op(self, **kwargs):
"""경사 하강 업데이트를 위한 tf.train.MomentumOptimizer.minimize Op. :param kwargs: dict, optimizer의 추가 인자. - momentum: float, 모멘텀 계수. :return tf.Operation."""
momentum = kwargs.pop('momentum', 0.9)
... | the_stack_v2_python_sparse | source/optimizer/MomentumOptimizer.py | mmecoco/Workshop_AI | train | 0 |
13d9498715a8bda163701ffaea1954c796d7ebad | [
"specs = super().getInputSpecification()\nspecs.addSub(InputData.parameterInputFactory('bins', contentType=InputTypes.IntegerType))\nspecs.addSub(InputData.parameterInputFactory('variables', contentType=InputTypes.StringListType))\nspecs.addSub(InputData.parameterInputFactory('source', contentType=InputTypes.String... | <|body_start_0|>
specs = super().getInputSpecification()
specs.addSub(InputData.parameterInputFactory('bins', contentType=InputTypes.IntegerType))
specs.addSub(InputData.parameterInputFactory('variables', contentType=InputTypes.StringListType))
specs.addSub(InputData.parameterInputFactor... | Correlation | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Correlation:
def getInputSpecification(cls):
"""Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,"""
<|body_0|>
def __init__(self):
"""Constructor. @ In, None @ Out, None"""
<|body_1|>
def handleInput(se... | stack_v2_sparse_classes_10k_train_003626 | 3,441 | permissive | [
{
"docstring": "Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,",
"name": "getInputSpecification",
"signature": "def getInputSpecification(cls)"
},
{
"docstring": "Constructor. @ In, None @ Out, None",
"name": "__init__",
"signature": ... | 5 | stack_v2_sparse_classes_30k_train_004550 | Implement the Python class `Correlation` described below.
Class description:
Implement the Correlation class.
Method signatures and docstrings:
- def getInputSpecification(cls): Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,
- def __init__(self): Constructor. @ In... | Implement the Python class `Correlation` described below.
Class description:
Implement the Correlation class.
Method signatures and docstrings:
- def getInputSpecification(cls): Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,
- def __init__(self): Constructor. @ In... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class Correlation:
def getInputSpecification(cls):
"""Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,"""
<|body_0|>
def __init__(self):
"""Constructor. @ In, None @ Out, None"""
<|body_1|>
def handleInput(se... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Correlation:
def getInputSpecification(cls):
"""Define the acceptable user inputs for this class. @ In, None @ Out, specs, InputData.ParameterInput,"""
specs = super().getInputSpecification()
specs.addSub(InputData.parameterInputFactory('bins', contentType=InputTypes.IntegerType))
... | the_stack_v2_python_sparse | plugins/ExamplePlugin/src/CorrelationPlot.py | idaholab/raven | train | 201 | |
bdd16bb6870ea5a9ded39bef95448c15cdc1223b | [
"super(GraphVisualizerTimeline, self).__init__(grid, column_id, column_span)\nfor i in range(column_span):\n self._grid.setColumnStretch(self._column_id + i, 0)",
"painter = QPainter(surface)\nfor connection in self._connected_items:\n start = surface.mapFromGlobal(connection.from_item.get_attach_point_bot(... | <|body_start_0|>
super(GraphVisualizerTimeline, self).__init__(grid, column_id, column_span)
for i in range(column_span):
self._grid.setColumnStretch(self._column_id + i, 0)
<|end_body_0|>
<|body_start_1|>
painter = QPainter(surface)
for connection in self._connected_items:
... | Draw a visual column, compressed by another other column. | GraphVisualizerTimeline | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphVisualizerTimeline:
"""Draw a visual column, compressed by another other column."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerTimeline instance."""
<|body_0|>
def draw(self, surface):
"""Draw the surface."""
<... | stack_v2_sparse_classes_10k_train_003627 | 24,840 | permissive | [
{
"docstring": "Initialize a GraphVisualizerTimeline instance.",
"name": "__init__",
"signature": "def __init__(self, grid, column_id, column_span=1)"
},
{
"docstring": "Draw the surface.",
"name": "draw",
"signature": "def draw(self, surface)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005572 | Implement the Python class `GraphVisualizerTimeline` described below.
Class description:
Draw a visual column, compressed by another other column.
Method signatures and docstrings:
- def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerTimeline instance.
- def draw(self, surface): Draw the ... | Implement the Python class `GraphVisualizerTimeline` described below.
Class description:
Draw a visual column, compressed by another other column.
Method signatures and docstrings:
- def __init__(self, grid, column_id, column_span=1): Initialize a GraphVisualizerTimeline instance.
- def draw(self, surface): Draw the ... | bbcf475a4b4e85836123452053bbbf34cc44063a | <|skeleton|>
class GraphVisualizerTimeline:
"""Draw a visual column, compressed by another other column."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerTimeline instance."""
<|body_0|>
def draw(self, surface):
"""Draw the surface."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GraphVisualizerTimeline:
"""Draw a visual column, compressed by another other column."""
def __init__(self, grid, column_id, column_span=1):
"""Initialize a GraphVisualizerTimeline instance."""
super(GraphVisualizerTimeline, self).__init__(grid, column_id, column_span)
for i in ra... | the_stack_v2_python_sparse | posydon/visualization/VH_diagram/GraphVisualizer.py | POSYDON-code/POSYDON | train | 11 |
748f6671399641fc2c28caa98032679a5ed29ab9 | [
"\"\"\"测试添加购物车\"\"\"\nadd = AddGwcPage(self.driver)\nadd.going_fenlei()\nadd.add_gwc()\ndy = add.dy_add_gwc()\nself.assertEqual(dy, '1')",
"\"\"\"测试添加多个商品\"\"\"\nsort = HomePage(self.driver)\nsort.click_sort()\nadd = AddGwcPage(self.driver)\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\nadd.add_gwc()\ndy = add.dy_... | <|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
<|end_body_0|>
<|body_start_1|>
"""测试添加多个商品"""
sort = HomePage(self.driver)
sort.click_sort()
add... | AddgwcTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.g... | stack_v2_sparse_classes_10k_train_003628 | 1,517 | no_license | [
{
"docstring": "MRYX_ST_classification_004",
"name": "test_add_gwc",
"signature": "def test_add_gwc(self)"
},
{
"docstring": "MRYX_ST_classification_009",
"name": "test_add_goods",
"signature": "def test_add_goods(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006342 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009 | Implement the Python class `AddgwcTest` described below.
Class description:
Implement the AddgwcTest class.
Method signatures and docstrings:
- def test_add_gwc(self): MRYX_ST_classification_004
- def test_add_goods(self): MRYX_ST_classification_009
<|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
... | 2325c7854c5625babdb51b5c5e40fa860813a400 | <|skeleton|>
class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
<|body_0|>
def test_add_goods(self):
"""MRYX_ST_classification_009"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AddgwcTest:
def test_add_gwc(self):
"""MRYX_ST_classification_004"""
"""测试添加购物车"""
add = AddGwcPage(self.driver)
add.going_fenlei()
add.add_gwc()
dy = add.dy_add_gwc()
self.assertEqual(dy, '1')
def test_add_goods(self):
"""MRYX_ST_classifica... | the_stack_v2_python_sparse | testcase/test_add_gwc.py | danyubiao/mryx | train | 0 | |
e8e05023d5d3a4d7d689422fe3aae4b55299e097 | [
"json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME': 'sometime', 'IP_SET': {'IP': ['1.1.1.1']}}}}\nmocker.patch.object(Qualysv2, 'format_and_validate_response', return_value=json_obj)\ndummy_response = requests.Response()\nassert handle_general_result(dummy_response, 'qualys-ip-list') == {'DATETIME': 'sometime'... | <|body_start_0|>
json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME': 'sometime', 'IP_SET': {'IP': ['1.1.1.1']}}}}
mocker.patch.object(Qualysv2, 'format_and_validate_response', return_value=json_obj)
dummy_response = requests.Response()
assert handle_general_result(dummy_response, 'qu... | TestHandleGeneralResult | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
<|body_0|>
def test_handle_general... | stack_v2_sparse_classes_10k_train_003629 | 44,285 | permissive | [
{
"docstring": "Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested",
"name": "test_handle_general_result_path_exists",
"signature": "def test_handle_general_result_path_exists(self, mocker)"
},
{
... | 5 | null | Implement the Python class `TestHandleGeneralResult` described below.
Class description:
Implement the TestHandleGeneralResult class.
Method signatures and docstrings:
- def test_handle_general_result_path_exists(self, mocker): Given - response in json format - path to a specific field When - the json object is well ... | Implement the Python class `TestHandleGeneralResult` described below.
Class description:
Implement the TestHandleGeneralResult class.
Method signatures and docstrings:
- def test_handle_general_result_path_exists(self, mocker): Given - response in json format - path to a specific field When - the json object is well ... | 890def5a0e0ae8d6eaa538148249ddbc851dbb6b | <|skeleton|>
class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
<|body_0|>
def test_handle_general... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestHandleGeneralResult:
def test_handle_general_result_path_exists(self, mocker):
"""Given - response in json format - path to a specific field When - the json object is well formed - the path is correct Then - return the path requested"""
json_obj = {'IP_LIST_OUTPUT': {'RESPONSE': {'DATETIME... | the_stack_v2_python_sparse | Packs/qualys/Integrations/Qualysv2/Qualysv2_test.py | demisto/content | train | 1,023 | |
b369c93ba7777240f783e9dd5d09d8b89c9521ac | [
"issue_tracker_data = self.get('issue_tracker', {})\nparameters = issue_tracker_data.get('parameters', {})\nurl = parameters.get('url', '')\nissue_parameters = IssueParameters(parameters.get('project_key', ''), parameters.get('issue_type', ''), parameters.get('issue_labels', []), parameters.get('epic_link', ''))\nc... | <|body_start_0|>
issue_tracker_data = self.get('issue_tracker', {})
parameters = issue_tracker_data.get('parameters', {})
url = parameters.get('url', '')
issue_parameters = IssueParameters(parameters.get('project_key', ''), parameters.get('issue_type', ''), parameters.get('issue_labels',... | Subclass the shared report class to add methods specific for the API-server. | Report | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
<|body_0|>
def desired_response_time(self, status: str) -> int:
"""Return the desired... | stack_v2_sparse_classes_10k_train_003630 | 2,013 | permissive | [
{
"docstring": "Return the issue tracker of the report.",
"name": "issue_tracker",
"signature": "def issue_tracker(self) -> IssueTracker"
},
{
"docstring": "Return the desired response time for the metric status.",
"name": "desired_response_time",
"signature": "def desired_response_time(... | 3 | stack_v2_sparse_classes_30k_train_005849 | Implement the Python class `Report` described below.
Class description:
Subclass the shared report class to add methods specific for the API-server.
Method signatures and docstrings:
- def issue_tracker(self) -> IssueTracker: Return the issue tracker of the report.
- def desired_response_time(self, status: str) -> in... | Implement the Python class `Report` described below.
Class description:
Subclass the shared report class to add methods specific for the API-server.
Method signatures and docstrings:
- def issue_tracker(self) -> IssueTracker: Return the issue tracker of the report.
- def desired_response_time(self, status: str) -> in... | 5d9952bf0bd47895824fa78428d3e4f4d6b5d9b3 | <|skeleton|>
class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
<|body_0|>
def desired_response_time(self, status: str) -> int:
"""Return the desired... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Report:
"""Subclass the shared report class to add methods specific for the API-server."""
def issue_tracker(self) -> IssueTracker:
"""Return the issue tracker of the report."""
issue_tracker_data = self.get('issue_tracker', {})
parameters = issue_tracker_data.get('parameters', {}... | the_stack_v2_python_sparse | components/api_server/src/model/report.py | ICTU/quality-time | train | 43 |
1e7e14a8a86e56975286eb59d19ff9ea6f6b1e7f | [
"self.x_max = x_max\nself.x_min = x_min or 0\nresolution = resolution or 1000\nif self.x_max <= self.x_min:\n raise ValueError('x_max : {} must be larger than x_min : {}'.format(self.x_max, self.x_min))\nself.x_vector = np.linspace(self.x_min, self.x_max, num=resolution)\nself.y_vector_top = self.construct_y_vec... | <|body_start_0|>
self.x_max = x_max
self.x_min = x_min or 0
resolution = resolution or 1000
if self.x_max <= self.x_min:
raise ValueError('x_max : {} must be larger than x_min : {}'.format(self.x_max, self.x_min))
self.x_vector = np.linspace(self.x_min, self.x_max, nu... | Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis. | Geometry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geometry:
"""Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis."""
def __init__(self, x_max, x_min=None, resolution=1000, bounds_top=None, funcs_top=None, bounds_bottom=None, funcs_bottom=None):
"""Instantiate Geometry class. :param... | stack_v2_sparse_classes_10k_train_003631 | 7,819 | permissive | [
{
"docstring": "Instantiate Geometry class. :param <int> x_max: Maximum x-value [meters] :param <int> x_min: Minimum x-value [meters] :param <int> resolution: Size of the x-array :param <list> bounds_top: y upper domain bounds :param <list> funcs_top: y upper domain functions :param <list> bounds_bottom: y lowe... | 3 | stack_v2_sparse_classes_30k_train_000378 | Implement the Python class `Geometry` described below.
Class description:
Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis.
Method signatures and docstrings:
- def __init__(self, x_max, x_min=None, resolution=1000, bounds_top=None, funcs_top=None, bounds_bottom=Non... | Implement the Python class `Geometry` described below.
Class description:
Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis.
Method signatures and docstrings:
- def __init__(self, x_max, x_min=None, resolution=1000, bounds_top=None, funcs_top=None, bounds_bottom=Non... | 51ac84926d691ec80a46e877302ccbe47281f8f4 | <|skeleton|>
class Geometry:
"""Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis."""
def __init__(self, x_max, x_min=None, resolution=1000, bounds_top=None, funcs_top=None, bounds_bottom=None, funcs_bottom=None):
"""Instantiate Geometry class. :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Geometry:
"""Define a geometric domain using upper and lower y arrays. Geometry must be symmetric about the y-axis."""
def __init__(self, x_max, x_min=None, resolution=1000, bounds_top=None, funcs_top=None, bounds_bottom=None, funcs_bottom=None):
"""Instantiate Geometry class. :param <int> x_max:... | the_stack_v2_python_sparse | geometry.py | pinebai/apsCFD | train | 0 |
b5c02021cf7d835a7f8c20d673970964ad8d5440 | [
"response = self.client.get('')\nself.assertEqual(response.status_code, 200)\nself.assertTemplateUsed(response, 'home/index.html')",
"response = self.client.get('/contact/')\nself.assertEqual(response.status_code, 200)\nself.assertTemplateUsed(response, 'home/contact.html')",
"response = self.client.get('/about... | <|body_start_0|>
response = self.client.get('')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'home/index.html')
<|end_body_0|>
<|body_start_1|>
response = self.client.get('/contact/')
self.assertEqual(response.status_code, 200)
self.asser... | TestView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestView:
def test_index(self):
"""testing if the index page works and template used"""
<|body_0|>
def test_contact(self):
"""testing if the contact page works and template used"""
<|body_1|>
def test_about(self):
"""testing if the index page wor... | stack_v2_sparse_classes_10k_train_003632 | 813 | no_license | [
{
"docstring": "testing if the index page works and template used",
"name": "test_index",
"signature": "def test_index(self)"
},
{
"docstring": "testing if the contact page works and template used",
"name": "test_contact",
"signature": "def test_contact(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_005393 | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_index(self): testing if the index page works and template used
- def test_contact(self): testing if the contact page works and template used
- def test_about(self): test... | Implement the Python class `TestView` described below.
Class description:
Implement the TestView class.
Method signatures and docstrings:
- def test_index(self): testing if the index page works and template used
- def test_contact(self): testing if the contact page works and template used
- def test_about(self): test... | e61dde21f68e84c312016fd2672c138b60b76344 | <|skeleton|>
class TestView:
def test_index(self):
"""testing if the index page works and template used"""
<|body_0|>
def test_contact(self):
"""testing if the contact page works and template used"""
<|body_1|>
def test_about(self):
"""testing if the index page wor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestView:
def test_index(self):
"""testing if the index page works and template used"""
response = self.client.get('')
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'home/index.html')
def test_contact(self):
"""testing if the contact... | the_stack_v2_python_sparse | home/test_views.py | Code-Institute-Submissions/furnitart | train | 0 | |
babf78034a9a30fff341ff3da6eb4a6214f9e009 | [
"Target(id=1, user=2, type='standard', latitude=10, longitude=-10, orientation='n', shape='circle', background_color='white', alphanumeric='a', alphanumeric_color='black')\nTarget(type='qrc', latitude=10, longitude=-10, description='http://test.com')\nTarget(type='off_axis', latitude=10, longitude=-10, orientation=... | <|body_start_0|>
Target(id=1, user=2, type='standard', latitude=10, longitude=-10, orientation='n', shape='circle', background_color='white', alphanumeric='a', alphanumeric_color='black')
Target(type='qrc', latitude=10, longitude=-10, description='http://test.com')
Target(type='off_axis', latitu... | Tests the Target model for validation and serialization. | TestTarget | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestTarget:
"""Tests the Target model for validation and serialization."""
def test_valid(self):
"""Test valid inputs."""
<|body_0|>
def test_invalid(self):
"""Test invalid inputs."""
<|body_1|>
def test_serialize(self):
"""Test serialization... | stack_v2_sparse_classes_10k_train_003633 | 14,890 | permissive | [
{
"docstring": "Test valid inputs.",
"name": "test_valid",
"signature": "def test_valid(self)"
},
{
"docstring": "Test invalid inputs.",
"name": "test_invalid",
"signature": "def test_invalid(self)"
},
{
"docstring": "Test serialization.",
"name": "test_serialize",
"signa... | 4 | stack_v2_sparse_classes_30k_val_000409 | Implement the Python class `TestTarget` described below.
Class description:
Tests the Target model for validation and serialization.
Method signatures and docstrings:
- def test_valid(self): Test valid inputs.
- def test_invalid(self): Test invalid inputs.
- def test_serialize(self): Test serialization.
- def test_de... | Implement the Python class `TestTarget` described below.
Class description:
Tests the Target model for validation and serialization.
Method signatures and docstrings:
- def test_valid(self): Test valid inputs.
- def test_invalid(self): Test invalid inputs.
- def test_serialize(self): Test serialization.
- def test_de... | 509f36562fc895433fcd01da755a35dd04581025 | <|skeleton|>
class TestTarget:
"""Tests the Target model for validation and serialization."""
def test_valid(self):
"""Test valid inputs."""
<|body_0|>
def test_invalid(self):
"""Test invalid inputs."""
<|body_1|>
def test_serialize(self):
"""Test serialization... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestTarget:
"""Tests the Target model for validation and serialization."""
def test_valid(self):
"""Test valid inputs."""
Target(id=1, user=2, type='standard', latitude=10, longitude=-10, orientation='n', shape='circle', background_color='white', alphanumeric='a', alphanumeric_color='blac... | the_stack_v2_python_sparse | client/interop/types_test.py | matcheydj/interop | train | 1 |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"users = User.query.all()\nusers_list = []\nfor user in users:\n users_list.append(user.__jsonapi__())\nreturn {'data': users_list}",
"current_identity = import_user()\ndata = request.get_json()['data']\nif User.query.filter_by(username=data['attributes']['username']).first():\n api.abort(code=409, message=... | <|body_start_0|>
users = User.query.all()
users_list = []
for user in users:
users_list.append(user.__jsonapi__())
return {'data': users_list}
<|end_body_0|>
<|body_start_1|>
current_identity = import_user()
data = request.get_json()['data']
if User.q... | UsersList | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsersList:
def get(self):
"""Get users list"""
<|body_0|>
def post(self):
"""Create user"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
users = User.query.all()
users_list = []
for user in users:
users_list.append(user._... | stack_v2_sparse_classes_10k_train_003634 | 46,738 | permissive | [
{
"docstring": "Get users list",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create user",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000902 | Implement the Python class `UsersList` described below.
Class description:
Implement the UsersList class.
Method signatures and docstrings:
- def get(self): Get users list
- def post(self): Create user | Implement the Python class `UsersList` described below.
Class description:
Implement the UsersList class.
Method signatures and docstrings:
- def get(self): Get users list
- def post(self): Create user
<|skeleton|>
class UsersList:
def get(self):
"""Get users list"""
<|body_0|>
def post(sel... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class UsersList:
def get(self):
"""Get users list"""
<|body_0|>
def post(self):
"""Create user"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UsersList:
def get(self):
"""Get users list"""
users = User.query.all()
users_list = []
for user in users:
users_list.append(user.__jsonapi__())
return {'data': users_list}
def post(self):
"""Create user"""
current_identity = import_user... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 | |
79944e732c2d048d78c44fb00f8607203d9d7080 | [
"self.site = page._link.site\nself.title = page._link.title\nself.loc_title = page._link.canonical_title()\nself.can_title = page._link.ns_title()\nself.outputlang = outputlang\nif outputlang is not None:\n if not hasattr(self, 'onsite'):\n self.onsite = pywikibot.Site(outputlang, self.site.family)\n t... | <|body_start_0|>
self.site = page._link.site
self.title = page._link.title
self.loc_title = page._link.canonical_title()
self.can_title = page._link.ns_title()
self.outputlang = outputlang
if outputlang is not None:
if not hasattr(self, 'onsite'):
... | Structure with Page attributes exposed for formatting from cmd line. | Formatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default='******'):
"""Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace befor... | stack_v2_sparse_classes_10k_train_003635 | 9,907 | permissive | [
{
"docstring": "Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace before title should be translated. Page ns will be searched in Site(outputlang, page.site.family) and, if found, its custom name will be used in page.title(). @type ou... | 2 | stack_v2_sparse_classes_30k_train_007343 | Implement the Python class `Formatter` described below.
Class description:
Structure with Page attributes exposed for formatting from cmd line.
Method signatures and docstrings:
- def __init__(self, page, outputlang=None, default='******'): Initializer. @param page: the page to be formatted. @type page: Page object. ... | Implement the Python class `Formatter` described below.
Class description:
Structure with Page attributes exposed for formatting from cmd line.
Method signatures and docstrings:
- def __init__(self, page, outputlang=None, default='******'): Initializer. @param page: the page to be formatted. @type page: Page object. ... | af470904ce62cedae63d285ca15146e9168a0ee6 | <|skeleton|>
class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default='******'):
"""Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace befor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Formatter:
"""Structure with Page attributes exposed for formatting from cmd line."""
def __init__(self, page, outputlang=None, default='******'):
"""Initializer. @param page: the page to be formatted. @type page: Page object. @param outputlang: language code in which namespace before title shoul... | the_stack_v2_python_sparse | scripts/listpages.py | anisayari/pywikibot | train | 3 |
27ddaaefc9e8d1d7be94d184e14312e800e73830 | [
"if not nums:\n return False\nif k < 1:\n return False\nmax_length = max(len(nums) - k, len(nums))\nfor i in range(max_length):\n for j in range(i + 1, min(i + k + 1, len(nums))):\n if nums[i] == nums[j]:\n return True\nreturn False",
"d = {}\nfor i in range(0, min(k + 1, len(nums))):\n... | <|body_start_0|>
if not nums:
return False
if k < 1:
return False
max_length = max(len(nums) - k, len(nums))
for i in range(max_length):
for j in range(i + 1, min(i + k + 1, len(nums))):
if nums[i] == nums[j]:
return... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def __containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
def ___containsNearbyDu... | stack_v2_sparse_classes_10k_train_003636 | 3,651 | permissive | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "_containsNearbyDuplicate",
"signature": "def _containsNearbyDuplicate(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: bool",
"name": "__containsNearbyDuplicate",
"signature": "def __c... | 5 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def __containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :rtype: bool
- def __containsNearbyDuplicate(self, nums, k): :type nums: List[int] :type k: int :r... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_0|>
def __containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
<|body_1|>
def ___containsNearbyDu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _containsNearbyDuplicate(self, nums, k):
""":type nums: List[int] :type k: int :rtype: bool"""
if not nums:
return False
if k < 1:
return False
max_length = max(len(nums) - k, len(nums))
for i in range(max_length):
for j... | the_stack_v2_python_sparse | 219.contains-duplicate-ii.py | windard/leeeeee | train | 0 | |
2955a24ef7d61ddce4e07a01bdd518262cab889f | [
"differentiator.refresh()\nop = differentiator.generate_differentiable_op(sampled_op=op)\nqubit = cirq.GridQubit(0, 0)\ncircuit = util.convert_to_tensor([cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha'))])\npsums = util.convert_to_tensor([[cirq.Z(qubit)]])\nsymbol_values_array = np.array([[0.123]], dtype=np.floa... | <|body_start_0|>
differentiator.refresh()
op = differentiator.generate_differentiable_op(sampled_op=op)
qubit = cirq.GridQubit(0, 0)
circuit = util.convert_to_tensor([cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha'))])
psums = util.convert_to_tensor([[cirq.Z(qubit)]])
... | Test approximate correctness to sampled methods. | SampledGradientCorrectnessTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SampledGradientCorrectnessTest:
"""Test approximate correctness to sampled methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
<|body_0|>
def test_approx_equali... | stack_v2_sparse_classes_10k_train_003637 | 22,303 | permissive | [
{
"docstring": "Test the value of sampled differentiator with simple circuit.",
"name": "test_sampled_value_with_simple_circuit",
"signature": "def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples)"
},
{
"docstring": "Test small circuits with limited depth.",
"nam... | 3 | stack_v2_sparse_classes_30k_train_006791 | Implement the Python class `SampledGradientCorrectnessTest` described below.
Class description:
Test approximate correctness to sampled methods.
Method signatures and docstrings:
- def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples): Test the value of sampled differentiator with simple c... | Implement the Python class `SampledGradientCorrectnessTest` described below.
Class description:
Test approximate correctness to sampled methods.
Method signatures and docstrings:
- def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples): Test the value of sampled differentiator with simple c... | f56257bceb988b743790e1e480eac76fd036d4ff | <|skeleton|>
class SampledGradientCorrectnessTest:
"""Test approximate correctness to sampled methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
<|body_0|>
def test_approx_equali... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SampledGradientCorrectnessTest:
"""Test approximate correctness to sampled methods."""
def test_sampled_value_with_simple_circuit(self, differentiator, op, num_samples):
"""Test the value of sampled differentiator with simple circuit."""
differentiator.refresh()
op = differentiato... | the_stack_v2_python_sparse | tensorflow_quantum/python/differentiators/gradient_test.py | tensorflow/quantum | train | 1,799 |
fae32d7a1065bb1b86503afb26b8220aabe0a717 | [
"self.n_y = n_y\nself.n_x = n_x\nsuper().__init__(centre=centre, ell_comps=ell_comps, beta=beta)",
"hermite_y = hermite(n=self.n_y)\nhermite_x = hermite(n=self.n_x)\ny = grid[:, 0]\nx = grid[:, 1]\nshapelet_y = hermite_y(y / self.beta)\nshapelet_x = hermite_x(x / self.beta)\nreturn shapelet_y * shapelet_x * np.ex... | <|body_start_0|>
self.n_y = n_y
self.n_x = n_x
super().__init__(centre=centre, ell_comps=ell_comps, beta=beta)
<|end_body_0|>
<|body_start_1|>
hermite_y = hermite(n=self.n_y)
hermite_x = hermite(n=self.n_x)
y = grid[:, 0]
x = grid[:, 1]
shapelet_y = hermi... | ShapeletCartesianEll | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeletCartesianEll:
def __init__(self, n_y: int, n_x: int, centre: Tuple[float, float]=(0.0, 0.0), ell_comps: Tuple[float, float]=(0.0, 0.0), beta: float=1.0):
"""Shapelets where the basis function is defined according to a Cartesian (y,x) grid of coordinates. Shapelets are defined acc... | stack_v2_sparse_classes_10k_train_003638 | 4,264 | permissive | [
{
"docstring": "Shapelets where the basis function is defined according to a Cartesian (y,x) grid of coordinates. Shapelets are defined according to: https://arxiv.org/abs/astro-ph/0105178 Shapelets are are described in the context of strong lens modeling in: https://ui.adsabs.harvard.edu/abs/2016MNRAS.457.3066... | 2 | stack_v2_sparse_classes_30k_train_007010 | Implement the Python class `ShapeletCartesianEll` described below.
Class description:
Implement the ShapeletCartesianEll class.
Method signatures and docstrings:
- def __init__(self, n_y: int, n_x: int, centre: Tuple[float, float]=(0.0, 0.0), ell_comps: Tuple[float, float]=(0.0, 0.0), beta: float=1.0): Shapelets wher... | Implement the Python class `ShapeletCartesianEll` described below.
Class description:
Implement the ShapeletCartesianEll class.
Method signatures and docstrings:
- def __init__(self, n_y: int, n_x: int, centre: Tuple[float, float]=(0.0, 0.0), ell_comps: Tuple[float, float]=(0.0, 0.0), beta: float=1.0): Shapelets wher... | d1a2e400b7ac984a21d972f54e419d8783342454 | <|skeleton|>
class ShapeletCartesianEll:
def __init__(self, n_y: int, n_x: int, centre: Tuple[float, float]=(0.0, 0.0), ell_comps: Tuple[float, float]=(0.0, 0.0), beta: float=1.0):
"""Shapelets where the basis function is defined according to a Cartesian (y,x) grid of coordinates. Shapelets are defined acc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ShapeletCartesianEll:
def __init__(self, n_y: int, n_x: int, centre: Tuple[float, float]=(0.0, 0.0), ell_comps: Tuple[float, float]=(0.0, 0.0), beta: float=1.0):
"""Shapelets where the basis function is defined according to a Cartesian (y,x) grid of coordinates. Shapelets are defined according to: htt... | the_stack_v2_python_sparse | autogalaxy/profiles/light/shapelets/cartesian.py | Jammy2211/PyAutoGalaxy | train | 27 | |
307d9e22169d8470c4c8a3b1724dcb4c53f4ad14 | [
"self.e = self.double(dos.e, -1.0)\nself.g = self.double(dos.g)\nself.gz = self.double(dos.gz)\nself.cutoffInd = dos.cutoffInd\nself.cutoff = dos.cutoff\nself.de = dos.de",
"res = (multi * array).tolist()\nres.reverse()\nreturn numpy.array(res + array[1:].tolist())"
] | <|body_start_0|>
self.e = self.double(dos.e, -1.0)
self.g = self.double(dos.g)
self.gz = self.double(dos.gz)
self.cutoffInd = dos.cutoffInd
self.cutoff = dos.cutoff
self.de = dos.de
<|end_body_0|>
<|body_start_1|>
res = (multi * array).tolist()
res.revers... | Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with zeros after cutoff } cutoff = energy... | doubleDos | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with... | stack_v2_sparse_classes_10k_train_003639 | 1,265 | no_license | [
{
"docstring": "Initinitializes from an instance of class densityOfStates",
"name": "__init__",
"signature": "def __init__(self, dos)"
},
{
"docstring": "Takes an array and returns that array reflected about array[0]. If multi = 1.0, even reflection, if multi = -1.0, odd.",
"name": "double",... | 2 | stack_v2_sparse_classes_30k_train_001261 | Implement the Python class `doubleDos` described below.
Class description:
Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz... | Implement the Python class `doubleDos` described below.
Class description:
Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz... | c35814533fa1ebc410f1f11b0664b7bb95a89ecb | <|skeleton|>
class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class doubleDos:
"""Simple class to hold a phonon density of states that has been reflected about E=0 to form an even function. Members defined here: e = numpy.array{ energies } de = energy increment g = numpy.array{ density of states, with noise after cutoff } gz = numpy.array{ density of states, with zeros after ... | the_stack_v2_python_sparse | src/multiphonon2/doubleDos.py | danse-inelastic/multiphonon | train | 1 |
4b6c3485ae50f1976ab172e4a81c1791528b70a3 | [
"self.size = size\nself.queue = deque([])\nself.cur_sum = 0",
"cur_sum = 0\nif len(self.queue) < self.size:\n self.cur_sum += val\nelse:\n last_num = self.queue.popleft()\n self.cur_sum = self.cur_sum - last_num + val\nself.queue.append(val)\nreturn self.cur_sum / float(len(self.queue))"
] | <|body_start_0|>
self.size = size
self.queue = deque([])
self.cur_sum = 0
<|end_body_0|>
<|body_start_1|>
cur_sum = 0
if len(self.queue) < self.size:
self.cur_sum += val
else:
last_num = self.queue.popleft()
self.cur_sum = self.cur_sum... | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.size = size
self.queue =... | stack_v2_sparse_classes_10k_train_003640 | 674 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006550 | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | a1b14fc7ecab09a838d70e0130ece27fb0fef7fd | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.size = size
self.queue = deque([])
self.cur_sum = 0
def next(self, val):
""":type val: int :rtype: float"""
cur_sum = 0
if len(self.queue) < sel... | the_stack_v2_python_sparse | Moving_Average_from_Data_Stream.py | Superbeet/LeetCode | train | 4 | |
6023e48a5387ae6c1ee868f7b9d784c25b6d5513 | [
"self.base_uri = clean_url.clean_url(app_server, self.BASE_PATH)\nself.app_server = app_server\nself.header_factory = header_factory",
"endpoint = 'applicationLogs/search'\nuri = f'{self.base_uri}/{endpoint}'\nparams = {'expand': expand, 'level': level, 'loginId': loginid, 'machineName': machine_name, 'orderBy': ... | <|body_start_0|>
self.base_uri = clean_url.clean_url(app_server, self.BASE_PATH)
self.app_server = app_server
self.header_factory = header_factory
<|end_body_0|>
<|body_start_1|>
endpoint = 'applicationLogs/search'
uri = f'{self.base_uri}/{endpoint}'
params = {'expand': ... | This operation returns application logs, based on the data passed in the request. | ApplicationLogs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationLogs:
"""This operation returns application logs, based on the data passed in the request."""
def __init__(self, app_server, header_factory):
"""Parameters ---------- app_server: str, optional This is the FQDN of the target QNXT app server header_factory: qnxt.authenticati... | stack_v2_sparse_classes_10k_train_003641 | 33,787 | no_license | [
{
"docstring": "Parameters ---------- app_server: str, optional This is the FQDN of the target QNXT app server header_factory: qnxt.authentication.RequestHeader, required This is a callable that generates the appropriate authentication headers for QNXT API requests",
"name": "__init__",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_val_000254 | Implement the Python class `ApplicationLogs` described below.
Class description:
This operation returns application logs, based on the data passed in the request.
Method signatures and docstrings:
- def __init__(self, app_server, header_factory): Parameters ---------- app_server: str, optional This is the FQDN of the... | Implement the Python class `ApplicationLogs` described below.
Class description:
This operation returns application logs, based on the data passed in the request.
Method signatures and docstrings:
- def __init__(self, app_server, header_factory): Parameters ---------- app_server: str, optional This is the FQDN of the... | 711b83a8091a50f86c09e0ed414c0fefceb39f36 | <|skeleton|>
class ApplicationLogs:
"""This operation returns application logs, based on the data passed in the request."""
def __init__(self, app_server, header_factory):
"""Parameters ---------- app_server: str, optional This is the FQDN of the target QNXT app server header_factory: qnxt.authenticati... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApplicationLogs:
"""This operation returns application logs, based on the data passed in the request."""
def __init__(self, app_server, header_factory):
"""Parameters ---------- app_server: str, optional This is the FQDN of the target QNXT app server header_factory: qnxt.authentication.RequestHea... | the_stack_v2_python_sparse | qnxt/api/PlanIntegration.py | agenovia/QNXT-API | train | 0 |
26fd4fa80efe8df3f9ebc1ca3b6d82df6c6c10a6 | [
"super(VSFD, self).__init__()\nself.char_num = char_num\nself.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)\nself.fc1 = paddle.nn.Linear(in_features=pvam_ch, out_features=self.char_num)",
"b, t, c1 = pvam_feature.shape\nb, t, c2 = gsrm_feature.shape\ncombine_feature_ = paddle.concat([p... | <|body_start_0|>
super(VSFD, self).__init__()
self.char_num = char_num
self.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)
self.fc1 = paddle.nn.Linear(in_features=pvam_ch, out_features=self.char_num)
<|end_body_0|>
<|body_start_1|>
b, t, c1 = pvam_feat... | VSFD | VSFD | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
<|body_0|>
def forward(self, pvam_feature, gsrm_feature):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(VSFD, self).__init__()
... | stack_v2_sparse_classes_10k_train_003642 | 1,291 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, in_channels=512, pvam_ch=512, char_num=38)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, pvam_feature, gsrm_feature)"
}
] | 2 | null | Implement the Python class `VSFD` described below.
Class description:
VSFD
Method signatures and docstrings:
- def __init__(self, in_channels=512, pvam_ch=512, char_num=38): init
- def forward(self, pvam_feature, gsrm_feature): forward | Implement the Python class `VSFD` described below.
Class description:
VSFD
Method signatures and docstrings:
- def __init__(self, in_channels=512, pvam_ch=512, char_num=38): init
- def forward(self, pvam_feature, gsrm_feature): forward
<|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, ... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
<|body_0|>
def forward(self, pvam_feature, gsrm_feature):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VSFD:
"""VSFD"""
def __init__(self, in_channels=512, pvam_ch=512, char_num=38):
"""init"""
super(VSFD, self).__init__()
self.char_num = char_num
self.fc0 = paddle.nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)
self.fc1 = paddle.nn.Linear(in_features=p... | the_stack_v2_python_sparse | framework/e2e/moduletrans/diy/layer/VSFD.py | PaddlePaddle/PaddleTest | train | 42 |
8fdbae7d7714842874626febf30828970049330b | [
"self.x = np.array(x)\nself.y = np.array(y)\nself.data = np.array(data)",
"ix = np.searchsorted(self.x, x).clip(1, len(self.x) - 1)\niy = np.searchsorted(self.y, y).clip(1, len(self.y) - 1)\ndx = (x - self.x[ix - 1]) / (self.x[ix] - self.x[ix - 1])\ndy = (y - self.y[iy - 1]) / (self.y[iy] - self.y[iy - 1])\ndata1... | <|body_start_0|>
self.x = np.array(x)
self.y = np.array(y)
self.data = np.array(data)
<|end_body_0|>
<|body_start_1|>
ix = np.searchsorted(self.x, x).clip(1, len(self.x) - 1)
iy = np.searchsorted(self.y, y).clip(1, len(self.y) - 1)
dx = (x - self.x[ix - 1]) / (self.x[ix]... | Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional. | LinearInterp2D | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two... | stack_v2_sparse_classes_10k_train_003643 | 9,328 | permissive | [
{
"docstring": "x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two coordinates are x and y",
"name": "__init__",
"signature": "def __init__(self, x, y, data)"
},
{
"docstring": "Evaluate data at (x,y)",
"name... | 2 | stack_v2_sparse_classes_30k_train_006411 | Implement the Python class `LinearInterp2D` described below.
Class description:
Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional.
Method signatures and docstrings:
- def __init__(self, x, y, data): x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 o... | Implement the Python class `LinearInterp2D` described below.
Class description:
Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional.
Method signatures and docstrings:
- def __init__(self, x, y, data): x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 o... | fca7d0cd515b756233dfd530e9f779c637730bc4 | <|skeleton|>
class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearInterp2D:
"""Linear interpolation on a 2D grid. Allows values to be interpolated to be multi-dimensional."""
def __init__(self, x, y, data):
"""x : array of x coordinates y : array of y coordinates data[ix, iy, ...] : 3 or more dimensional array of data to interpolate first two coordinates ... | the_stack_v2_python_sparse | desihub/specter/py/specter/util/util.py | michaelJwilson/LBGCMB | train | 2 |
b9787fcc1519cb2e7bf64d336e68282ade85c2ff | [
"super(Postnet, self).__init__()\nself.postnet = torch.nn.ModuleList()\nfor layer in six.moves.range(n_layers - 1):\n ichans = odim if layer == 0 else n_chans\n ochans = odim if layer == n_layers - 1 else n_chans\n if use_batch_norm:\n self.postnet += [torch.nn.Sequential(torch.nn.Conv1d(ichans, och... | <|body_start_0|>
super(Postnet, self).__init__()
self.postnet = torch.nn.ModuleList()
for layer in six.moves.range(n_layers - 1):
ichans = odim if layer == 0 else n_chans
ochans = odim if layer == n_layers - 1 else n_chans
if use_batch_norm:
se... | Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which helps to compensate the de... | Postnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_10k_train_003644 | 3,105 | permissive | [
{
"docstring": "Initialize postnet module. Args: idim (int): Dimension of the inputs. odim (int): Dimension of the outputs. n_layers (int, optional): The number of layers. n_filts (int, optional): The number of filter size. n_units (int, optional): The number of filter channels. use_batch_norm (bool, optional):... | 2 | stack_v2_sparse_classes_30k_train_003964 | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | Implement the Python class `Postnet` described below.
Class description:
Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the... | 41dc231931907e8c1fa9b85c5263f87163c723a4 | <|skeleton|>
class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decode... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Postnet:
"""Postnet module for Spectrogram prediction network. This is a module of Postnet in Spectrogram prediction network, which described in `Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`_. The Postnet predicts refines the predicted Mel-filterbank of the decoder, which help... | the_stack_v2_python_sparse | modules/postnet.py | wangfn/FastSpeech2 | train | 0 |
564a24f061cb2094c7a67f1665009ddffb52b844 | [
"self.lhs = get_eval_func(columns=lhs, func=func)\nself.rhs = self.lhs if rhs is None else get_eval_func(columns=rhs)\nself.having = having",
"determinant = self.lhs.eval(df=df)\ndependent = self.rhs.eval(df=df)\ngroups = dict()\nmeta = dict()\nfor index, values in enumerate(zip(determinant, dependent)):\n val... | <|body_start_0|>
self.lhs = get_eval_func(columns=lhs, func=func)
self.rhs = self.lhs if rhs is None else get_eval_func(columns=rhs)
self.having = having
<|end_body_0|>
<|body_start_1|>
determinant = self.lhs.eval(df=df)
dependent = self.rhs.eval(df=df)
groups = dict()
... | Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation object. | Violations | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Violations:
"""Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation object."""
def __init__(self, lhs, ... | stack_v2_sparse_classes_10k_train_003645 | 7,053 | permissive | [
{
"docstring": "Initializes the Violation class with the left and right hand side key generators, and func and having callables. If no values for rhs are provided, it assumes we want to find violations in a singular set of column(s) (lhs). Parameters ---------- lhs: list or string column name(s) of the determin... | 4 | stack_v2_sparse_classes_30k_train_001961 | Implement the Python class `Violations` described below.
Class description:
Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation o... | Implement the Python class `Violations` described below.
Class description:
Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation o... | e3d0e04f90468c49f29ca53edc2feb12465c24d5 | <|skeleton|>
class Violations:
"""Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation object."""
def __init__(self, lhs, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Violations:
"""Violations class that: 1) takes the left side and right side column names 2) generates a new key from the values (func callable) 3) identifies any tuples violating specified rules (having callable) 4) and returns them as a DataFrameViolation object."""
def __init__(self, lhs, rhs=None, fun... | the_stack_v2_python_sparse | openclean/operator/map/violations.py | Denisfench/openclean-core | train | 0 |
369a3bda6190d22bc2b60b448833673d54ca405d | [
"self.key = key\nself._set_key_parms(['type'])\nself._set_prhb_parms(['type'])",
"if 'conf' not in self.__dict__:\n self.conf = self.get_view_obj(self.key)\nreturn self.conf.get('type')"
] | <|body_start_0|>
self.key = key
self._set_key_parms(['type'])
self._set_prhb_parms(['type'])
<|end_body_0|>
<|body_start_1|>
if 'conf' not in self.__dict__:
self.conf = self.get_view_obj(self.key)
return self.conf.get('type')
<|end_body_1|>
| WorkFlowEvalConfig | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkFlowEvalConfig:
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_eval_type(self):
"""get eval type ( regression, classification.. ) :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.key = ... | stack_v2_sparse_classes_10k_train_003646 | 632 | permissive | [
{
"docstring": "init key variable :param key: :return:",
"name": "__init__",
"signature": "def __init__(self, key=None)"
},
{
"docstring": "get eval type ( regression, classification.. ) :return:",
"name": "get_eval_type",
"signature": "def get_eval_type(self)"
}
] | 2 | null | Implement the Python class `WorkFlowEvalConfig` described below.
Class description:
Implement the WorkFlowEvalConfig class.
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_eval_type(self): get eval type ( regression, classification.. ) :return: | Implement the Python class `WorkFlowEvalConfig` described below.
Class description:
Implement the WorkFlowEvalConfig class.
Method signatures and docstrings:
- def __init__(self, key=None): init key variable :param key: :return:
- def get_eval_type(self): get eval type ( regression, classification.. ) :return:
<|ske... | 6ad2fbc7384e4dbe7e3e63bdb44c8ce0387f4b7f | <|skeleton|>
class WorkFlowEvalConfig:
def __init__(self, key=None):
"""init key variable :param key: :return:"""
<|body_0|>
def get_eval_type(self):
"""get eval type ( regression, classification.. ) :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkFlowEvalConfig:
def __init__(self, key=None):
"""init key variable :param key: :return:"""
self.key = key
self._set_key_parms(['type'])
self._set_prhb_parms(['type'])
def get_eval_type(self):
"""get eval type ( regression, classification.. ) :return:"""
... | the_stack_v2_python_sparse | master/workflow/evalconf/workflow_evalconf.py | yurimkoo/tensormsa | train | 1 | |
85f47f0d3e6a9c0418d427d00de354e8fc2f4223 | [
"self.wind_speed = np.ones((3, 4), dtype=np.float32)\nself.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)\nself.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)\nself.plugin = OrographicEnhancement()\nself.plugin.grid_spacing_km = 3.0",
"distance = self.plugin._get_point_distances(self.wind_... | <|body_start_0|>
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4), np.sqrt(0.84), dtype=np.float32)
self.plugin = OrographicEnhancement()
self.plugin.grid_spacing_km = 3.0
<|end_body_... | Test the _locate_source_points method | Test__locate_source_points | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
se... | stack_v2_sparse_classes_10k_train_003647 | 34,979 | permissive | [
{
"docstring": "Define input matrices and plugin",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test location of source points",
"name": "test_basic",
"signature": "def test_basic(self)"
}
] | 2 | null | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points | Implement the Python class `Test__locate_source_points` described below.
Class description:
Test the _locate_source_points method
Method signatures and docstrings:
- def setUp(self): Define input matrices and plugin
- def test_basic(self): Test location of source points
<|skeleton|>
class Test__locate_source_points:... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
<|body_0|>
def test_basic(self):
"""Test location of source points"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test__locate_source_points:
"""Test the _locate_source_points method"""
def setUp(self):
"""Define input matrices and plugin"""
self.wind_speed = np.ones((3, 4), dtype=np.float32)
self.sin_wind_dir = np.full((3, 4), 0.4, dtype=np.float32)
self.cos_wind_dir = np.full((3, 4)... | the_stack_v2_python_sparse | improver_tests/orographic_enhancement/test_OrographicEnhancement.py | metoppv/improver | train | 101 |
58f5c77553c1294baaeb9911fb1119fdba89704a | [
"self.c = capacity\nself.cc = 0\nself.h = {}\nself.m = []",
"if key in self.h:\n self.m.remove(key)\n self.m.append(key)\n return self.h[key]\nelse:\n return -1",
"if self.cc < self.c:\n self.cc += 1\n self.h.update({key: value})\n self.m.append(key)\nelse:\n self.h.update({key: value})\... | <|body_start_0|>
self.c = capacity
self.cc = 0
self.h = {}
self.m = []
<|end_body_0|>
<|body_start_1|>
if key in self.h:
self.m.remove(key)
self.m.append(key)
return self.h[key]
else:
return -1
<|end_body_1|>
<|body_start_... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_003648 | 833 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: void",
"name": "pu... | 3 | null | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: void
<|sk... | 418172cee1bf48bb2aed3b84fe8b4defd9ef4fdf | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: void"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.c = capacity
self.cc = 0
self.h = {}
self.m = []
def get(self, key):
""":type key: int :rtype: int"""
if key in self.h:
self.m.remove(key)
self.m.append(k... | the_stack_v2_python_sparse | LRU Cache.py | TianyaoHua/LeetCodeSolutions | train | 0 | |
0218e30ef9a9a7af73fefec1767155ca722cd03b | [
"self.qa_yaml_name = os.environ['qa_yaml_name']\nself.rd_yaml_path = os.environ['rd_yaml_path']\nlogger.info('###self.qa_yaml_name: {}'.format(self.qa_yaml_name))\nself.reponame = os.environ['reponame']\nself.system = os.environ['system']\nself.step = os.environ['step']\nlogger.info('###self.step: {}'.format(self.s... | <|body_start_0|>
self.qa_yaml_name = os.environ['qa_yaml_name']
self.rd_yaml_path = os.environ['rd_yaml_path']
logger.info('###self.qa_yaml_name: {}'.format(self.qa_yaml_name))
self.reponame = os.environ['reponame']
self.system = os.environ['system']
self.step = os.enviro... | 自定义环境准备 | PaddleScience_Start | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PaddleScience_Start:
"""自定义环境准备"""
def __init__(self):
"""init"""
<|body_0|>
def prepare_gpu_env(self):
"""根据操作系统获取用gpu还是cpu"""
<|body_1|>
def add_paddlescience_to_pythonpath(self):
"""paddlescience 打包路径添加到python的路径中"""
<|body_2|>
... | stack_v2_sparse_classes_10k_train_003649 | 3,716 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "根据操作系统获取用gpu还是cpu",
"name": "prepare_gpu_env",
"signature": "def prepare_gpu_env(self)"
},
{
"docstring": "paddlescience 打包路径添加到python的路径中",
"name": "add_paddlescience_to_pythonpat... | 6 | null | Implement the Python class `PaddleScience_Start` described below.
Class description:
自定义环境准备
Method signatures and docstrings:
- def __init__(self): init
- def prepare_gpu_env(self): 根据操作系统获取用gpu还是cpu
- def add_paddlescience_to_pythonpath(self): paddlescience 打包路径添加到python的路径中
- def download_datasets(self): download ... | Implement the Python class `PaddleScience_Start` described below.
Class description:
自定义环境准备
Method signatures and docstrings:
- def __init__(self): init
- def prepare_gpu_env(self): 根据操作系统获取用gpu还是cpu
- def add_paddlescience_to_pythonpath(self): paddlescience 打包路径添加到python的路径中
- def download_datasets(self): download ... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class PaddleScience_Start:
"""自定义环境准备"""
def __init__(self):
"""init"""
<|body_0|>
def prepare_gpu_env(self):
"""根据操作系统获取用gpu还是cpu"""
<|body_1|>
def add_paddlescience_to_pythonpath(self):
"""paddlescience 打包路径添加到python的路径中"""
<|body_2|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PaddleScience_Start:
"""自定义环境准备"""
def __init__(self):
"""init"""
self.qa_yaml_name = os.environ['qa_yaml_name']
self.rd_yaml_path = os.environ['rd_yaml_path']
logger.info('###self.qa_yaml_name: {}'.format(self.qa_yaml_name))
self.reponame = os.environ['reponame']
... | the_stack_v2_python_sparse | models_restruct/PaddleScience/tools/start.py | PaddlePaddle/PaddleTest | train | 42 |
56067c6f0a794af1aed6cc0a3bef410bf64255fa | [
"path = urlJoin(urls.CLIENT_LOCATION['GET_CLIENT_LOC'], macaddr)\nparams = {'offset': offset, 'limit': limit, 'units': units}\nresp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)\nreturn resp",
"path = urlJoin(urls.CLIENT_LOCATION['GET_FLOOR_CLIENTS'], floor_id, 'client_location')\nparams = {'off... | <|body_start_0|>
path = urlJoin(urls.CLIENT_LOCATION['GET_CLIENT_LOC'], macaddr)
params = {'offset': offset, 'limit': limit, 'units': units}
resp = conn.command(apiMethod='GET', apiPath=path, apiParams=params)
return resp
<|end_body_0|>
<|body_start_1|>
path = urlJoin(urls.CLIEN... | A python class to obtain client location based on visualRF floor map. | ClientLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Centr... | stack_v2_sparse_classes_10k_train_003650 | 13,713 | permissive | [
{
"docstring": "Get location of a client. This function provides output only when visualRF is configured in Aruba Central. :param conn: Instance of class:`pycentral.ArubaCentralBase` to make an API call. :type conn: class:`pycentral.ArubaCentralBase` :param macaddr: Provide a macaddr of a client. For example \"... | 2 | stack_v2_sparse_classes_30k_train_001810 | Implement the Python class `ClientLocation` described below.
Class description:
A python class to obtain client location based on visualRF floor map.
Method signatures and docstrings:
- def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of a client. This function provid... | Implement the Python class `ClientLocation` described below.
Class description:
A python class to obtain client location based on visualRF floor map.
Method signatures and docstrings:
- def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'): Get location of a client. This function provid... | d938396a18193473afbe54e6cc6697d2bd4954a7 | <|skeleton|>
class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Centr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClientLocation:
"""A python class to obtain client location based on visualRF floor map."""
def get_client_location(self, conn, macaddr: str, offset=0, limit=100, units='FEET'):
"""Get location of a client. This function provides output only when visualRF is configured in Aruba Central. :param co... | the_stack_v2_python_sparse | pycentral/visualrf.py | jayp193/pycentral | train | 0 |
e0a05eefd0fa0485116cdaafc7be800bf6e082e8 | [
"samples_lims = []\nfor sample in samples:\n LOG.debug(f\"{sample['name']}: prepare LIMS input\")\n samples_lims.append({'name': sample['name'], 'container': sample.get('container') or 'Tube', 'container_name': sample.get('container_name'), 'well_position': sample.get('well_position'), 'index_sequence': sampl... | <|body_start_0|>
samples_lims = []
for sample in samples:
LOG.debug(f"{sample['name']}: prepare LIMS input")
samples_lims.append({'name': sample['name'], 'container': sample.get('container') or 'Tube', 'container_name': sample.get('container_name'), 'well_position': sample.get('w... | LimsHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
<|body_0|>
def process_lims(self, data: dict, samples: List[dict]):
"""Process samples to add them to LIMS."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k_train_003651 | 3,155 | no_license | [
{
"docstring": "Convert order input to lims interface input.",
"name": "to_lims",
"signature": "def to_lims(customer: str, samples: List[dict]) -> List[dict]"
},
{
"docstring": "Process samples to add them to LIMS.",
"name": "process_lims",
"signature": "def process_lims(self, data: dict... | 2 | stack_v2_sparse_classes_30k_train_002984 | Implement the Python class `LimsHandler` described below.
Class description:
Implement the LimsHandler class.
Method signatures and docstrings:
- def to_lims(customer: str, samples: List[dict]) -> List[dict]: Convert order input to lims interface input.
- def process_lims(self, data: dict, samples: List[dict]): Proce... | Implement the Python class `LimsHandler` described below.
Class description:
Implement the LimsHandler class.
Method signatures and docstrings:
- def to_lims(customer: str, samples: List[dict]) -> List[dict]: Convert order input to lims interface input.
- def process_lims(self, data: dict, samples: List[dict]): Proce... | 987b422511ff0299712a59bfe523e9a35dbd3171 | <|skeleton|>
class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
<|body_0|>
def process_lims(self, data: dict, samples: List[dict]):
"""Process samples to add them to LIMS."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LimsHandler:
def to_lims(customer: str, samples: List[dict]) -> List[dict]:
"""Convert order input to lims interface input."""
samples_lims = []
for sample in samples:
LOG.debug(f"{sample['name']}: prepare LIMS input")
samples_lims.append({'name': sample['name']... | the_stack_v2_python_sparse | cg/meta/orders/lims.py | dnil/cg | train | 2 | |
5d8715dd02feff4e13919858051abeb5b6828011 | [
"self.min = np.array([-2.903534, -2.903534])\nself.value = -39.16599 * 2.0\nself.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])\nself.n = 2\nself.smooth = True\nself.info = [True, True, True]\nself.latex_name = 'Styblinski-Tang Function'\nself.latex_type = 'Other'\nself.latex_cost = '\\\\[ f(\\\\mathbf{x}) = \\\\fra... | <|body_start_0|>
self.min = np.array([-2.903534, -2.903534])
self.value = -39.16599 * 2.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.info = [True, True, True]
self.latex_name = 'Styblinski-Tang Function'
self.late... | Styblinski-Tang Function. | StyblinskiTang | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
""... | stack_v2_sparse_classes_10k_train_003652 | 1,639 | no_license | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Cost function.",
"name": "cost",
"signature": "def cost(self, x)"
},
{
"docstring": "Grad function.",
"name": "grad",
"signature": "def grad(self, x)"
},
{
"doc... | 4 | stack_v2_sparse_classes_30k_train_007146 | Implement the Python class `StyblinskiTang` described below.
Class description:
Styblinski-Tang Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function. | Implement the Python class `StyblinskiTang` described below.
Class description:
Styblinski-Tang Function.
Method signatures and docstrings:
- def __init__(self): Constructor.
- def cost(self, x): Cost function.
- def grad(self, x): Grad function.
- def hess(self, x): Hess function.
<|skeleton|>
class StyblinskiTang:... | f2a74df3ab01ac35ea8d80569da909ffa1e86af3 | <|skeleton|>
class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
<|body_0|>
def cost(self, x):
"""Cost function."""
<|body_1|>
def grad(self, x):
"""Grad function."""
<|body_2|>
def hess(self, x):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StyblinskiTang:
"""Styblinski-Tang Function."""
def __init__(self):
"""Constructor."""
self.min = np.array([-2.903534, -2.903534])
self.value = -39.16599 * 2.0
self.domain = np.array([[-5.0, 5.0], [-5.0, 5.0]])
self.n = 2
self.smooth = True
self.inf... | the_stack_v2_python_sparse | ctf/functions2d/styblinski_tang.py | cntaylor/ctf | train | 1 |
528dcbfe862fbe63aead32aaa0343a41ef9e1f92 | [
"Parametre.__init__(self, 'marquer', 'mark')\nself.aide_courte = 'marque la salle dans les routes'\nself.aide_longue = 'Cette commande ne prend aucun paramètre. Elle permet de commencer à marquer une route, ou bien d\\'en finir une. Vous devez entrer cette commande une première fois dans la salle d\\'origine de la ... | <|body_start_0|>
Parametre.__init__(self, 'marquer', 'mark')
self.aide_courte = 'marque la salle dans les routes'
self.aide_longue = 'Cette commande ne prend aucun paramètre. Elle permet de commencer à marquer une route, ou bien d\'en finir une. Vous devez entrer cette commande une première fois... | Commande 'route marquer' | PrmMarquer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmMarquer:
"""Commande 'route marquer'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Pa... | stack_v2_sparse_classes_10k_train_003653 | 3,628 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmMarquer` described below.
Class description:
Commande 'route marquer'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande | Implement the Python class `PrmMarquer` described below.
Class description:
Commande 'route marquer'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande
<|skeleton|>
class PrmMarquer:
"""Commande... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmMarquer:
"""Commande 'route marquer'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmMarquer:
"""Commande 'route marquer'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'marquer', 'mark')
self.aide_courte = 'marque la salle dans les routes'
self.aide_longue = 'Cette commande ne prend aucun paramètre. Elle permet de comm... | the_stack_v2_python_sparse | src/secondaires/route/commandes/route/marquer.py | vincent-lg/tsunami | train | 5 |
56d1e5199e2611796026b814ecf5d94bc34372cf | [
"expected_record_count = (4, 3, 12)\nexpected_error_count = (0, 0, 0)\ntup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_FILE_RENTAL)\nself.assertTupleEqual(tup_record_count, expected_record_count)\nself.assertTupleEqual(tup_error_count, expected_error_count... | <|body_start_0|>
expected_record_count = (4, 3, 12)
expected_error_count = (0, 0, 0)
tup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_FILE_RENTAL)
self.assertTupleEqual(tup_record_count, expected_record_count)
self.assert... | unit test for database.py | TestDatabase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
<|body_0|>
def test_import_data_error(self):
"""test import_data"""
<|body_1|>
def test_show_available_product(self):
"""test show_available_prod... | stack_v2_sparse_classes_10k_train_003654 | 3,286 | no_license | [
{
"docstring": "test import_data",
"name": "test_import_data",
"signature": "def test_import_data(self)"
},
{
"docstring": "test import_data",
"name": "test_import_data_error",
"signature": "def test_import_data_error(self)"
},
{
"docstring": "test show_available_product",
"n... | 4 | null | Implement the Python class `TestDatabase` described below.
Class description:
unit test for database.py
Method signatures and docstrings:
- def test_import_data(self): test import_data
- def test_import_data_error(self): test import_data
- def test_show_available_product(self): test show_available_product
- def test_... | Implement the Python class `TestDatabase` described below.
Class description:
unit test for database.py
Method signatures and docstrings:
- def test_import_data(self): test import_data
- def test_import_data_error(self): test import_data
- def test_show_available_product(self): test show_available_product
- def test_... | 5dac60f39e3909ff05b26721d602ed20f14d6be3 | <|skeleton|>
class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
<|body_0|>
def test_import_data_error(self):
"""test import_data"""
<|body_1|>
def test_show_available_product(self):
"""test show_available_prod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestDatabase:
"""unit test for database.py"""
def test_import_data(self):
"""test import_data"""
expected_record_count = (4, 3, 12)
expected_error_count = (0, 0, 0)
tup_record_count, tup_error_count = import_data(DATA_FILE_PATH, DATA_FILE_PRODUCT, DATA_FILE_CUSTOMER, DATA_... | the_stack_v2_python_sparse | students/ttlarson/lesson05/assignment/test_database.py | JavaRod/SP_Python220B_2019 | train | 1 |
4e839ba3808743ba8c8785079521bbfa02a0e34f | [
"data = {}\nid = request.GET.get('id', None)\nindicator_factor_id = request.GET.get('indicator_factor_id', None)\nif id is not None:\n data['id'] = id\nif indicator_factor_id is not None:\n data['indicator_factor_id'] = indicator_factor_id\nbasis_templates = BasisTemplate.objects.filter(**data)\nserializer = ... | <|body_start_0|>
data = {}
id = request.GET.get('id', None)
indicator_factor_id = request.GET.get('indicator_factor_id', None)
if id is not None:
data['id'] = id
if indicator_factor_id is not None:
data['indicator_factor_id'] = indicator_factor_id
... | 评价依据模版view | BasisTemplates | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BasisTemplates:
"""评价依据模版view"""
def get(self, request):
"""查询评价依据模版"""
<|body_0|>
def put(self, request):
"""修改评价依据模版"""
<|body_1|>
def post(self, request):
"""增加评价依据模版"""
<|body_2|>
def delete(self, request):
"""删除评价依据模... | stack_v2_sparse_classes_10k_train_003655 | 15,061 | permissive | [
{
"docstring": "查询评价依据模版",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改评价依据模版",
"name": "put",
"signature": "def put(self, request)"
},
{
"docstring": "增加评价依据模版",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring"... | 4 | stack_v2_sparse_classes_30k_train_004243 | Implement the Python class `BasisTemplates` described below.
Class description:
评价依据模版view
Method signatures and docstrings:
- def get(self, request): 查询评价依据模版
- def put(self, request): 修改评价依据模版
- def post(self, request): 增加评价依据模版
- def delete(self, request): 删除评价依据模版 | Implement the Python class `BasisTemplates` described below.
Class description:
评价依据模版view
Method signatures and docstrings:
- def get(self, request): 查询评价依据模版
- def put(self, request): 修改评价依据模版
- def post(self, request): 增加评价依据模版
- def delete(self, request): 删除评价依据模版
<|skeleton|>
class BasisTemplates:
"""评价依据模版... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class BasisTemplates:
"""评价依据模版view"""
def get(self, request):
"""查询评价依据模版"""
<|body_0|>
def put(self, request):
"""修改评价依据模版"""
<|body_1|>
def post(self, request):
"""增加评价依据模版"""
<|body_2|>
def delete(self, request):
"""删除评价依据模... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BasisTemplates:
"""评价依据模版view"""
def get(self, request):
"""查询评价依据模版"""
data = {}
id = request.GET.get('id', None)
indicator_factor_id = request.GET.get('indicator_factor_id', None)
if id is not None:
data['id'] = id
if indicator_factor_id is no... | the_stack_v2_python_sparse | plan/views.py | MIXISAMA/MIS-backend | train | 0 |
e864327a837f59188aa01a10d763c0827779d836 | [
"self.is_training = is_training\nself.use_bfloat16 = use_bfloat16\nself.saturate_uint8 = saturate_uint8\nself.scale_and_center = scale_and_center\nself.use_default_augment = use_default_augment\nself.batch_size = batch_size\nself.augmentation = augmentation\nself.num_classes = NUM_CLASSES\nself.num_images = SPLIT_T... | <|body_start_0|>
self.is_training = is_training
self.use_bfloat16 = use_bfloat16
self.saturate_uint8 = saturate_uint8
self.scale_and_center = scale_and_center
self.use_default_augment = use_default_augment
self.batch_size = batch_size
self.augmentation = augmentat... | Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation data is in the same format bu... | ImageNetInput | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_10k_train_003656 | 16,434 | permissive | [
{
"docstring": "Initialize ImageNetInput. Args: split: data split, either 'train' or 'test'. is_training: `bool` for whether the input is for training. batch_size: The global batch size to use. augmentation: callable which performs augmentation on images. use_bfloat16: If True, use bfloat16 precision; else use ... | 4 | stack_v2_sparse_classes_30k_train_003969 | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | Implement the Python class `ImageNetInput` described below.
Class description:
Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-0000... | f8b7f184b91d6144927c7c4b34f7d9c0313f8a39 | <|skeleton|>
class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ImageNetInput:
"""Generates ImageNet input_fn for training or evaluation. The training data is assumed to be in TFRecord format with keys as specified in the dataset_parser below, sharded across 1024 files, named sequentially: train-00000-of-01024 train-00001-of-01024 ... train-01023-of-01024 The validation d... | the_stack_v2_python_sparse | imagenet/datasets/imagenet.py | paulxiong/fixmatch | train | 1 |
d466752c6e4c1e57fe2d4f37259e514e3087e930 | [
"super(CodeEntryBox, self).__init__()\nself.id = id\nself.alert_layer = alert_layer",
"self.get_buffer().insert_text(position, new_text, length)\nnext_box = self.alert_layer.get_entry_box(self.id + 1)\nif next_box is not None:\n next_box.grab_focus()\nelse:\n self.alert_layer.confirm_code()\nreturn position... | <|body_start_0|>
super(CodeEntryBox, self).__init__()
self.id = id
self.alert_layer = alert_layer
<|end_body_0|>
<|body_start_1|>
self.get_buffer().insert_text(position, new_text, length)
next_box = self.alert_layer.get_entry_box(self.id + 1)
if next_box is not None:
... | Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation provided by Gtk.Editable, which is call... | CodeEntryBox | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation... | stack_v2_sparse_classes_10k_train_003657 | 7,836 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, alert_layer=None, id=None)"
},
{
"docstring": "Overrides the default handler for insert_text signals.",
"name": "do_insert_text",
"signature": "def do_insert_text(self, new_text, length, position)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005943 | Implement the Python class `CodeEntryBox` described below.
Class description:
Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This fun... | Implement the Python class `CodeEntryBox` described below.
Class description:
Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This fun... | a63f338c4ee791f9dbf9c2791d1dc8e6326d32f2 | <|skeleton|>
class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CodeEntryBox:
"""Custom GTK Entry box: Python bindings for GTK throw a warning when connecting to the insert_text signal on an Entry box. This stems from bug 644927 in the pygobject implementation and arises due to its handling of in/out parameters. This function overrides the base implementation provided by ... | the_stack_v2_python_sparse | interface/notifications/AlertAuthorization.py | mccolm-robotics/ClaverMessageBoard | train | 0 |
bdeccc9fef18eb5aad5d0bf1f75585064b1d3013 | [
"from pyramid.testing import DummySecurityPolicy\npolicy = DummySecurityPolicy(userid, groupids, permissive, remember_result, forget_result)\nself.registry.registerUtility(policy, IAuthorizationPolicy)\nself.registry.registerUtility(policy, IAuthenticationPolicy)\nreturn policy",
"class DummyTraverserFactory:\n\n... | <|body_start_0|>
from pyramid.testing import DummySecurityPolicy
policy = DummySecurityPolicy(userid, groupids, permissive, remember_result, forget_result)
self.registry.registerUtility(policy, IAuthorizationPolicy)
self.registry.registerUtility(policy, IAuthenticationPolicy)
ret... | TestingConfiguratorMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestingConfiguratorMixin:
def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None):
"""Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`aut... | stack_v2_sparse_classes_10k_train_003658 | 7,302 | permissive | [
{
"docstring": "Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`authorization policy`. The behavior of the registered :term:`authorization policy` depends on the ``permissive`` argument. If ``permissive`` is true, a permiss... | 4 | stack_v2_sparse_classes_30k_train_001187 | Implement the Python class `TestingConfiguratorMixin` described below.
Class description:
Implement the TestingConfiguratorMixin class.
Method signatures and docstrings:
- def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): Unit/integration testing he... | Implement the Python class `TestingConfiguratorMixin` described below.
Class description:
Implement the TestingConfiguratorMixin class.
Method signatures and docstrings:
- def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None): Unit/integration testing he... | 8d08bb85fcbc28800c2c9b35f370d8cc0813dac9 | <|skeleton|>
class TestingConfiguratorMixin:
def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None):
"""Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`aut... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestingConfiguratorMixin:
def testing_securitypolicy(self, userid=None, groupids=(), permissive=True, remember_result=None, forget_result=None):
"""Unit/integration testing helper: Registers a pair of faux :app:`Pyramid` security policies: a :term:`authentication policy` and a :term:`authorization pol... | the_stack_v2_python_sparse | venv/Lib/site-packages/pyramid/config/testing.py | supermax03/Port-Scanner-as-a-Service-2 | train | 0 | |
f1bbda7ddd2306db1412e9be4e0b784f9a65e5bd | [
"def _val_check(val, name):\n if val < 0 or val > 255:\n raise ValueError(f'Invalid {name} value. Should be 0~255. ({val})')\n_val_check(red, 'RED')\n_val_check(green, 'GREEN')\n_val_check(blue, 'BLUE')\nreturn Color(red * 65536 + green * 256 + blue)",
"if not re.match('#?[0-9A-Fa-f]{6}', hex_str):\n ... | <|body_start_0|>
def _val_check(val, name):
if val < 0 or val > 255:
raise ValueError(f'Invalid {name} value. Should be 0~255. ({val})')
_val_check(red, 'RED')
_val_check(green, 'GREEN')
_val_check(blue, 'BLUE')
return Color(red * 65536 + green * 256 +... | Factory class to generate :class:`Color`. | ColorFactory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColorFactory:
"""Factory class to generate :class:`Color`."""
def from_rgb(red: int, green: int, blue: int) -> Color:
"""Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid"""
... | stack_v2_sparse_classes_10k_train_003659 | 4,009 | permissive | [
{
"docstring": "Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid",
"name": "from_rgb",
"signature": "def from_rgb(red: int, green: int, blue: int) -> Color"
},
{
"docstring": "Generate a :clas... | 2 | stack_v2_sparse_classes_30k_train_003769 | Implement the Python class `ColorFactory` described below.
Class description:
Factory class to generate :class:`Color`.
Method signatures and docstrings:
- def from_rgb(red: int, green: int, blue: int) -> Color: Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueErr... | Implement the Python class `ColorFactory` described below.
Class description:
Factory class to generate :class:`Color`.
Method signatures and docstrings:
- def from_rgb(red: int, green: int, blue: int) -> Color: Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueErr... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class ColorFactory:
"""Factory class to generate :class:`Color`."""
def from_rgb(red: int, green: int, blue: int) -> Color:
"""Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ColorFactory:
"""Factory class to generate :class:`Color`."""
def from_rgb(red: int, green: int, blue: int) -> Color:
"""Generate a :class:`Color` from RGB. :return: a `Color` with using the provided RGB values :raises ValueError: any of `red`, `green` or `blue` is invalid"""
def _val_che... | the_stack_v2_python_sparse | extutils/color.py | RxJellyBot/Jelly-Bot | train | 5 |
c0a86a17a14e0e7ce30c8f49cd241e537dc88345 | [
"self.winners, self.times = ([], times)\nvote_count, counts = (0, collections.defaultdict(int))\nfor person in persons:\n counts[person] += 1\n if counts[person] >= vote_count:\n vote_count = counts[person]\n winner = person\n self.winners.append(winner)",
"i, j = (0, len(self.times))\nwhil... | <|body_start_0|>
self.winners, self.times = ([], times)
vote_count, counts = (0, collections.defaultdict(int))
for person in persons:
counts[person] += 1
if counts[person] >= vote_count:
vote_count = counts[person]
winner = person
... | TopVotedCandidate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.winners, self.times = ([], times... | stack_v2_sparse_classes_10k_train_003660 | 823 | no_license | [
{
"docstring": ":type persons: List[int] :type times: List[int]",
"name": "__init__",
"signature": "def __init__(self, persons, times)"
},
{
"docstring": ":type t: int :rtype: int",
"name": "q",
"signature": "def q(self, t)"
}
] | 2 | null | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int | Implement the Python class `TopVotedCandidate` described below.
Class description:
Implement the TopVotedCandidate class.
Method signatures and docstrings:
- def __init__(self, persons, times): :type persons: List[int] :type times: List[int]
- def q(self, t): :type t: int :rtype: int
<|skeleton|>
class TopVotedCandi... | fa1ed20d266b9c226f10fdb64528ffae0a595aa4 | <|skeleton|>
class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
<|body_0|>
def q(self, t):
""":type t: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TopVotedCandidate:
def __init__(self, persons, times):
""":type persons: List[int] :type times: List[int]"""
self.winners, self.times = ([], times)
vote_count, counts = (0, collections.defaultdict(int))
for person in persons:
counts[person] += 1
if count... | the_stack_v2_python_sparse | medium_911. Online Election.py | sdksfo/leetcode | train | 0 | |
176c0080fda8414ca1ca820cddbc5d7f1ed8950c | [
"super(GeonamesTestCase, self).setUp()\nself._admin = self.model('user').createUser('admin', 'password', 'admin', 'user', 'admin@example.com', admin=True)\nself._user = self.model('user').createUser('minervauser', 'password', 'minerva', 'user', 'minervauser@example.com')",
"params = {'parentType': 'user', 'parent... | <|body_start_0|>
super(GeonamesTestCase, self).setUp()
self._admin = self.model('user').createUser('admin', 'password', 'admin', 'user', 'admin@example.com', admin=True)
self._user = self.model('user').createUser('minervauser', 'password', 'minerva', 'user', 'minervauser@example.com')
<|end_body... | Tests of the minerva geonames API endpoints. | GeonamesTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeonamesTestCase:
"""Tests of the minerva geonames API endpoints."""
def setUp(self):
"""Set up the test case with a user."""
<|body_0|>
def test_geocode(self):
"""Test importing the geonames database and geocoding."""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_003661 | 4,048 | no_license | [
{
"docstring": "Set up the test case with a user.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test importing the geonames database and geocoding.",
"name": "test_geocode",
"signature": "def test_geocode(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002889 | Implement the Python class `GeonamesTestCase` described below.
Class description:
Tests of the minerva geonames API endpoints.
Method signatures and docstrings:
- def setUp(self): Set up the test case with a user.
- def test_geocode(self): Test importing the geonames database and geocoding. | Implement the Python class `GeonamesTestCase` described below.
Class description:
Tests of the minerva geonames API endpoints.
Method signatures and docstrings:
- def setUp(self): Set up the test case with a user.
- def test_geocode(self): Test importing the geonames database and geocoding.
<|skeleton|>
class Geonam... | 878d3aa26781439914871a54bbb27412a7a4719e | <|skeleton|>
class GeonamesTestCase:
"""Tests of the minerva geonames API endpoints."""
def setUp(self):
"""Set up the test case with a user."""
<|body_0|>
def test_geocode(self):
"""Test importing the geonames database and geocoding."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GeonamesTestCase:
"""Tests of the minerva geonames API endpoints."""
def setUp(self):
"""Set up the test case with a user."""
super(GeonamesTestCase, self).setUp()
self._admin = self.model('user').createUser('admin', 'password', 'admin', 'user', 'admin@example.com', admin=True)
... | the_stack_v2_python_sparse | plugin_tests/geonames_test.py | justincampbell/minerva | train | 0 |
f4d8b32220926433d2d1a23a2e1371ff284c648b | [
"super(SwinTransformerStage, self).__init__()\nself.use_checkpoint: bool = use_checkpoint\nself.downscale: bool = downscale\nself.downsample: nn.Module = PatchMerging(in_channels=in_channels) if downscale else nn.Identity()\nself.input_resolution: Tuple[int, int] = (input_resolution[0] // 2, input_resolution[1] // ... | <|body_start_0|>
super(SwinTransformerStage, self).__init__()
self.use_checkpoint: bool = use_checkpoint
self.downscale: bool = downscale
self.downsample: nn.Module = PatchMerging(in_channels=in_channels) if downscale else nn.Identity()
self.input_resolution: Tuple[int, int] = (i... | This class implements a stage of the Swin transformer including multiple layers. | SwinTransformerStage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwinTransformerStage:
"""This class implements a stage of the Swin transformer including multiple layers."""
def __init__(self, in_channels: int, depth: int, downscale: bool, input_resolution: Tuple[int, int], number_of_heads: int, window_size: int=7, ff_feature_ratio: int=4, dropout: float=... | stack_v2_sparse_classes_10k_train_003662 | 41,159 | no_license | [
{
"docstring": "Constructor method :param in_channels: (int) Number of input channels :param depth: (int) Depth of the stage (number of layers) :param downscale: (bool) If true input is downsampled (see Fig. 3 or V1 paper) :param input_resolution: (Tuple[int, int]) Input resolution :param number_of_heads: (int)... | 3 | stack_v2_sparse_classes_30k_train_005441 | Implement the Python class `SwinTransformerStage` described below.
Class description:
This class implements a stage of the Swin transformer including multiple layers.
Method signatures and docstrings:
- def __init__(self, in_channels: int, depth: int, downscale: bool, input_resolution: Tuple[int, int], number_of_head... | Implement the Python class `SwinTransformerStage` described below.
Class description:
This class implements a stage of the Swin transformer including multiple layers.
Method signatures and docstrings:
- def __init__(self, in_channels: int, depth: int, downscale: bool, input_resolution: Tuple[int, int], number_of_head... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SwinTransformerStage:
"""This class implements a stage of the Swin transformer including multiple layers."""
def __init__(self, in_channels: int, depth: int, downscale: bool, input_resolution: Tuple[int, int], number_of_heads: int, window_size: int=7, ff_feature_ratio: int=4, dropout: float=... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SwinTransformerStage:
"""This class implements a stage of the Swin transformer including multiple layers."""
def __init__(self, in_channels: int, depth: int, downscale: bool, input_resolution: Tuple[int, int], number_of_heads: int, window_size: int=7, ff_feature_ratio: int=4, dropout: float=0.0, dropout_... | the_stack_v2_python_sparse | generated/test_ChristophReich1996_Swin_Transformer_V2.py | jansel/pytorch-jit-paritybench | train | 35 |
3c1b24f676dcfbc58ceb690124dabc73519c4914 | [
"self._parameters = parameters\nif not hasattr(self, '_mapper'):\n self._mapper = OCPProviderMap(provider=self.provider, report_type=parameters.report_type)\nif parameters.get_filter('enabled') is None:\n parameters.set_filter(**{'enabled': True})\nsuper().__init__(parameters)",
"filter_map = deepcopy(TagQu... | <|body_start_0|>
self._parameters = parameters
if not hasattr(self, '_mapper'):
self._mapper = OCPProviderMap(provider=self.provider, report_type=parameters.report_type)
if parameters.get_filter('enabled') is None:
parameters.set_filter(**{'enabled': True})
super(... | Handles tag queries and responses for OCP. | OCPTagQueryHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPTagQueryHandler:
"""Handles tag queries and responses for OCP."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_10k_train_003663 | 4,620 | permissive | [
{
"docstring": "Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query",
"name": "__init__",
"signature": "def __init__(self, parameters)"
},
{
"docstring": "Establish which filter map to use based on tag API.",
"name": "filter_map",
"signature... | 2 | null | Implement the Python class `OCPTagQueryHandler` described below.
Class description:
Handles tag queries and responses for OCP.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | Implement the Python class `OCPTagQueryHandler` described below.
Class description:
Handles tag queries and responses for OCP.
Method signatures and docstrings:
- def __init__(self, parameters): Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query
- def filter_map(self): ... | 0416e5216eb1ec4b41c8dd4999adde218b1ab2e1 | <|skeleton|>
class OCPTagQueryHandler:
"""Handles tag queries and responses for OCP."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
<|body_0|>
def filter_map(self):
"""Establish which filte... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OCPTagQueryHandler:
"""Handles tag queries and responses for OCP."""
def __init__(self, parameters):
"""Establish AWS report query handler. Args: parameters (QueryParameters): parameter object for query"""
self._parameters = parameters
if not hasattr(self, '_mapper'):
... | the_stack_v2_python_sparse | koku/api/tags/ocp/queries.py | project-koku/koku | train | 225 |
5fb0b698b9051fbda07caa7376a96c5c9d1227cd | [
"self.data = nums[0:]\nself.size = int(math.sqrt(len(nums)))\nself.block = [0] * int(math.ceil(len(nums) / float(self.size)))\nfor i in range(0, len(nums)):\n self.block[i / self.size] += nums[i]",
"delta = val - self.data[i]\nself.block[i / self.size] += delta\nself.data[i] = val",
"start = i / self.size\ne... | <|body_start_0|>
self.data = nums[0:]
self.size = int(math.sqrt(len(nums)))
self.block = [0] * int(math.ceil(len(nums) / float(self.size)))
for i in range(0, len(nums)):
self.block[i / self.size] += nums[i]
<|end_body_0|>
<|body_start_1|>
delta = val - self.data[i]
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k_train_003664 | 1,240 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_006067 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.data = nums[0:]
self.size = int(math.sqrt(len(nums)))
self.block = [0] * int(math.ceil(len(nums) / float(self.size)))
for i in range(0, len(nums)):
self.block[i / self.size] += nums[i]
... | the_stack_v2_python_sparse | 2019/segment_tree/range_sum_query_mutable_307_new.py | yehongyu/acode | train | 0 | |
cc3d18bf9ef6e89f6122a6df06bc337f2051547c | [
"try:\n ec = self.tags.get('ec', 0)\n self.set_tag('ec', ec + 1)\n if tags is not None and isinstance(tags, dict):\n for key in tags:\n self.set_tag(key, tags[key])\nexcept Exception:\n logger.debug('span.mark_as_errored', exc_info=True)",
"try:\n ec = self.tags.get('ec', None)\n ... | <|body_start_0|>
try:
ec = self.tags.get('ec', 0)
self.set_tag('ec', ec + 1)
if tags is not None and isinstance(tags, dict):
for key in tags:
self.set_tag(key, tags[key])
except Exception:
logger.debug('span.mark_as_erro... | InstanaSpan | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
<|body_0|>
def assure_errored(self):
"""Make sure that this span is marked as errored. @return: None"""
<|body_1|>
def log_e... | stack_v2_sparse_classes_10k_train_003665 | 24,069 | permissive | [
{
"docstring": "Mark this span as errored. @param tags: optional tags to add to the span",
"name": "mark_as_errored",
"signature": "def mark_as_errored(self, tags=None)"
},
{
"docstring": "Make sure that this span is marked as errored. @return: None",
"name": "assure_errored",
"signature... | 3 | stack_v2_sparse_classes_30k_train_002237 | Implement the Python class `InstanaSpan` described below.
Class description:
Implement the InstanaSpan class.
Method signatures and docstrings:
- def mark_as_errored(self, tags=None): Mark this span as errored. @param tags: optional tags to add to the span
- def assure_errored(self): Make sure that this span is marke... | Implement the Python class `InstanaSpan` described below.
Class description:
Implement the InstanaSpan class.
Method signatures and docstrings:
- def mark_as_errored(self, tags=None): Mark this span as errored. @param tags: optional tags to add to the span
- def assure_errored(self): Make sure that this span is marke... | 4b2d90baf67db3b923c23564590dabe89a0e41d2 | <|skeleton|>
class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
<|body_0|>
def assure_errored(self):
"""Make sure that this span is marked as errored. @return: None"""
<|body_1|>
def log_e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InstanaSpan:
def mark_as_errored(self, tags=None):
"""Mark this span as errored. @param tags: optional tags to add to the span"""
try:
ec = self.tags.get('ec', 0)
self.set_tag('ec', ec + 1)
if tags is not None and isinstance(tags, dict):
for ... | the_stack_v2_python_sparse | instana/span.py | instana/python-sensor | train | 69 | |
3c3f6a27224c40abf98bdb64034754a9725023fd | [
"for i in ProjectInfo.objects.filter(type=1):\n i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)\n self.assertEqual(i.output_configs(), i_type2.output_configs())\n i_type3 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=3)\n self.assertEqual(i.output_confi... | <|body_start_0|>
for i in ProjectInfo.objects.filter(type=1):
i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)
self.assertEqual(i.output_configs(), i_type2.output_configs())
i_type3 = ProjectInfo.objects.get(items=i.items, platform=i.platform, typ... | ProjectInfoTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
<|body_0|>
def test_configs_exist(self):
"""测试配置文件是否存在"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
for i in ProjectInfo.objects.filter(type=1):
i_type2 = Proje... | stack_v2_sparse_classes_10k_train_003666 | 925 | no_license | [
{
"docstring": "测试type 1\u0002\u0003 类型配置文件一致",
"name": "test_configs_equal",
"signature": "def test_configs_equal(self)"
},
{
"docstring": "测试配置文件是否存在",
"name": "test_configs_exist",
"signature": "def test_configs_exist(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004514 | Implement the Python class `ProjectInfoTests` described below.
Class description:
Implement the ProjectInfoTests class.
Method signatures and docstrings:
- def test_configs_equal(self): 测试type 1 类型配置文件一致
- def test_configs_exist(self): 测试配置文件是否存在 | Implement the Python class `ProjectInfoTests` described below.
Class description:
Implement the ProjectInfoTests class.
Method signatures and docstrings:
- def test_configs_equal(self): 测试type 1 类型配置文件一致
- def test_configs_exist(self): 测试配置文件是否存在
<|skeleton|>
class ProjectInfoTests:
def test_configs_equal(sel... | 87cebc5fbc52bfa50a3e457772c48a5fc74c446f | <|skeleton|>
class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
<|body_0|>
def test_configs_exist(self):
"""测试配置文件是否存在"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProjectInfoTests:
def test_configs_equal(self):
"""测试type 1 类型配置文件一致"""
for i in ProjectInfo.objects.filter(type=1):
i_type2 = ProjectInfo.objects.get(items=i.items, platform=i.platform, type=2)
self.assertEqual(i.output_configs(), i_type2.output_configs())
... | the_stack_v2_python_sparse | cmdb/tests.py | chuan-yk/deployment | train | 0 | |
83f4cf4434c7f1f39f73c79968fd883a11f70aff | [
"parser = parent.add_parser('rm', help='Delete pod and container(s)')\nparser.add_flag('--all', '-a', help='Remove all pods.')\nparser.add_flag('--force', '-f', help='Stop and remove container(s) then delete pod.')\nparser.add_argument('pod', nargs='*', help='Pod to remove. Or, use --all')\nparser.set_defaults(clas... | <|body_start_0|>
parser = parent.add_parser('rm', help='Delete pod and container(s)')
parser.add_flag('--all', '-a', help='Remove all pods.')
parser.add_flag('--force', '-f', help='Stop and remove container(s) then delete pod.')
parser.add_argument('pod', nargs='*', help='Pod to remove. ... | Class for removing pod and containers from storage. | RemovePod | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RemovePod:
"""Class for removing pod and containers from storage."""
def subparser(cls, parent):
"""Add Pod Rm command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct RemovePod object."""
<|body_1|>
def remove(self):
""... | stack_v2_sparse_classes_10k_train_003667 | 1,791 | permissive | [
{
"docstring": "Add Pod Rm command to parent parser.",
"name": "subparser",
"signature": "def subparser(cls, parent)"
},
{
"docstring": "Construct RemovePod object.",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Remove pod and container(s).",
... | 3 | stack_v2_sparse_classes_30k_train_006894 | Implement the Python class `RemovePod` described below.
Class description:
Class for removing pod and containers from storage.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Rm command to parent parser.
- def __init__(self, args): Construct RemovePod object.
- def remove(self): Remove pod and... | Implement the Python class `RemovePod` described below.
Class description:
Class for removing pod and containers from storage.
Method signatures and docstrings:
- def subparser(cls, parent): Add Pod Rm command to parent parser.
- def __init__(self, args): Construct RemovePod object.
- def remove(self): Remove pod and... | 94a46127cb0db2b6187186788a941ec72af476dd | <|skeleton|>
class RemovePod:
"""Class for removing pod and containers from storage."""
def subparser(cls, parent):
"""Add Pod Rm command to parent parser."""
<|body_0|>
def __init__(self, args):
"""Construct RemovePod object."""
<|body_1|>
def remove(self):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RemovePod:
"""Class for removing pod and containers from storage."""
def subparser(cls, parent):
"""Add Pod Rm command to parent parser."""
parser = parent.add_parser('rm', help='Delete pod and container(s)')
parser.add_flag('--all', '-a', help='Remove all pods.')
parser.a... | the_stack_v2_python_sparse | pypodman/pypodman/lib/actions/pod/remove_parser.py | 4383/python-podman | train | 0 |
c1ed945590b8e6007dc6137ecad43fdbab680693 | [
"super(EncodingDetectFilter, self).__init__(builder)\nself._normalize = self.builder.decoder.normalize\nself._meta = self._normalize('meta')",
"normalize = self._normalize\niname = normalize(name)\nif iname == self._meta:\n adict = dict([(normalize(key), val) for key, val in attr])\n value = str(adict.get(n... | <|body_start_0|>
super(EncodingDetectFilter, self).__init__(builder)
self._normalize = self.builder.decoder.normalize
self._meta = self._normalize('meta')
<|end_body_0|>
<|body_start_1|>
normalize = self._normalize
iname = normalize(name)
if iname == self._meta:
... | Extract template encoding and pass it properly to the builder | EncodingDetectFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncodingDetectFilter:
"""Extract template encoding and pass it properly to the builder"""
def __init__(self, builder):
"""Initialization"""
<|body_0|>
def handle_starttag(self, name, attr, closed, data):
"""Extract encoding from HTML meta element Here are samples... | stack_v2_sparse_classes_10k_train_003668 | 6,907 | permissive | [
{
"docstring": "Initialization",
"name": "__init__",
"signature": "def __init__(self, builder)"
},
{
"docstring": "Extract encoding from HTML meta element Here are samples for the expected formats:: <meta charset=\"utf-8\"> <!-- HTML5 --> <meta http-equiv=\"Content-Type\" content=\"text/html; ch... | 3 | stack_v2_sparse_classes_30k_train_004439 | Implement the Python class `EncodingDetectFilter` described below.
Class description:
Extract template encoding and pass it properly to the builder
Method signatures and docstrings:
- def __init__(self, builder): Initialization
- def handle_starttag(self, name, attr, closed, data): Extract encoding from HTML meta ele... | Implement the Python class `EncodingDetectFilter` described below.
Class description:
Extract template encoding and pass it properly to the builder
Method signatures and docstrings:
- def __init__(self, builder): Initialization
- def handle_starttag(self, name, attr, closed, data): Extract encoding from HTML meta ele... | 65a93080281f9ce5c0379e9dbb111f14965a8613 | <|skeleton|>
class EncodingDetectFilter:
"""Extract template encoding and pass it properly to the builder"""
def __init__(self, builder):
"""Initialization"""
<|body_0|>
def handle_starttag(self, name, attr, closed, data):
"""Extract encoding from HTML meta element Here are samples... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncodingDetectFilter:
"""Extract template encoding and pass it properly to the builder"""
def __init__(self, builder):
"""Initialization"""
super(EncodingDetectFilter, self).__init__(builder)
self._normalize = self.builder.decoder.normalize
self._meta = self._normalize('me... | the_stack_v2_python_sparse | tdi/markup/soup/filters.py | ndparker/tdi | train | 4 |
b1d87e445e67c953078d22c2f059a49f67b39851 | [
"\"\"\":field\n The name of the visual material associated with this cloth material.\n \"\"\"\nself.visual_material: str = visual_material\n':field\\n The texture scale of the visual material.\\n '\nself.texture_scale: Dict[str, float] = texture_scale\n':field\\n The smoothness va... | <|body_start_0|>
""":field
The name of the visual material associated with this cloth material.
"""
self.visual_material: str = visual_material
':field\n The texture scale of the visual material.\n '
self.texture_scale: Dict[str, float] = tex... | An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html). | ClothMaterial | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClothMaterial:
"""An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html)."""
def __init__(self, visual_material: str, texture_scale: Dict[str, float], visual_smoothness: float=0, stretching_scale: float=1.0, stretch_compliance: ... | stack_v2_sparse_classes_10k_train_003669 | 4,062 | permissive | [
{
"docstring": ":param visual_material: The name of the visual material associated with this cloth material. :param texture_scale: The texture scale of the visual material. :param visual_smoothness: The smoothness value of the visual material. :param stretching_scale: The scale factor for the rest length of eac... | 2 | null | Implement the Python class `ClothMaterial` described below.
Class description:
An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html).
Method signatures and docstrings:
- def __init__(self, visual_material: str, texture_scale: Dict[str, float], visual_sm... | Implement the Python class `ClothMaterial` described below.
Class description:
An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html).
Method signatures and docstrings:
- def __init__(self, visual_material: str, texture_scale: Dict[str, float], visual_sm... | 9df96fba455b327bb360d8dd5886d8754046c690 | <|skeleton|>
class ClothMaterial:
"""An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html)."""
def __init__(self, visual_material: str, texture_scale: Dict[str, float], visual_smoothness: float=0, stretching_scale: float=1.0, stretch_compliance: ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ClothMaterial:
"""An Obi cloth material. For more information, [read this](http://obi.virtualmethodstudio.com/tutorials/clothsetup.html)."""
def __init__(self, visual_material: str, texture_scale: Dict[str, float], visual_smoothness: float=0, stretching_scale: float=1.0, stretch_compliance: float=0, max_... | the_stack_v2_python_sparse | Python/tdw/obi_data/cloth/cloth_material.py | threedworld-mit/tdw | train | 427 |
811f7225620ea1acfcea001b0435cb9f38c36f60 | [
"strings = ['Abc123,./=-0jkf', '']\nfor s in strings:\n result = sol[101].isUniqueA(s)\n self.assertTrue(result)\n result = sol[101].isUniqueB(s)\n self.assertTrue(result)",
"strings = ['Abc123,./=-03jkf', ' ']\nfor s in strings:\n result = sol[101].isUniqueA(s)\n self.assertFalse(result)\n ... | <|body_start_0|>
strings = ['Abc123,./=-0jkf', '']
for s in strings:
result = sol[101].isUniqueA(s)
self.assertTrue(result)
result = sol[101].isUniqueB(s)
self.assertTrue(result)
<|end_body_0|>
<|body_start_1|>
strings = ['Abc123,./=-03jkf', ' ']... | Tests for: isUniqueA, isUniqueB | S0101TestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S0101TestCase:
"""Tests for: isUniqueA, isUniqueB"""
def test_1_uniq(self):
"""Check unique string."""
<|body_0|>
def test_2_nonuniq(self):
"""Check non-unique string."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
strings = ['Abc123,./=-0jkf',... | stack_v2_sparse_classes_10k_train_003670 | 6,651 | no_license | [
{
"docstring": "Check unique string.",
"name": "test_1_uniq",
"signature": "def test_1_uniq(self)"
},
{
"docstring": "Check non-unique string.",
"name": "test_2_nonuniq",
"signature": "def test_2_nonuniq(self)"
}
] | 2 | null | Implement the Python class `S0101TestCase` described below.
Class description:
Tests for: isUniqueA, isUniqueB
Method signatures and docstrings:
- def test_1_uniq(self): Check unique string.
- def test_2_nonuniq(self): Check non-unique string. | Implement the Python class `S0101TestCase` described below.
Class description:
Tests for: isUniqueA, isUniqueB
Method signatures and docstrings:
- def test_1_uniq(self): Check unique string.
- def test_2_nonuniq(self): Check non-unique string.
<|skeleton|>
class S0101TestCase:
"""Tests for: isUniqueA, isUniqueB"... | c27f19fac14b4acef8c631ad5569e1a5c29e9e1f | <|skeleton|>
class S0101TestCase:
"""Tests for: isUniqueA, isUniqueB"""
def test_1_uniq(self):
"""Check unique string."""
<|body_0|>
def test_2_nonuniq(self):
"""Check non-unique string."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class S0101TestCase:
"""Tests for: isUniqueA, isUniqueB"""
def test_1_uniq(self):
"""Check unique string."""
strings = ['Abc123,./=-0jkf', '']
for s in strings:
result = sol[101].isUniqueA(s)
self.assertTrue(result)
result = sol[101].isUniqueB(s)
... | the_stack_v2_python_sparse | Chapter 1 - Arrays and Strings/test.py | liseyko/CtCI | train | 0 |
384726029f9bf08f99578ef841034fb6cf11569b | [
"Parametre.__init__(self, 'chasser', 'hunt')\nself.schema = '<nom_familier>'\nself.aide_courte = 'demande au fammilier de chasser'\nself.aide_longue = \"Cette commande permet d'ordonner à un familier de chasser. Un familier carnivore a besoin de recevoir cet ordre pour chercher du petit gibier avant de se nourrir. ... | <|body_start_0|>
Parametre.__init__(self, 'chasser', 'hunt')
self.schema = '<nom_familier>'
self.aide_courte = 'demande au fammilier de chasser'
self.aide_longue = "Cette commande permet d'ordonner à un familier de chasser. Un familier carnivore a besoin de recevoir cet ordre pour cherch... | Commande 'familier chasser'. | PrmChasser | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Parametr... | stack_v2_sparse_classes_10k_train_003671 | 4,209 | permissive | [
{
"docstring": "Constructeur du paramètre",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Interprétation du paramètre",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | null | Implement the Python class `PrmChasser` described below.
Class description:
Commande 'familier chasser'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre | Implement the Python class `PrmChasser` described below.
Class description:
Commande 'familier chasser'.
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre
- def interpreter(self, personnage, dic_masques): Interprétation du paramètre
<|skeleton|>
class PrmChasser:
"""Commande 'fami... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PrmChasser:
"""Commande 'familier chasser'."""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, 'chasser', 'hunt')
self.schema = '<nom_familier>'
self.aide_courte = 'demande au fammilier de chasser'
self.aide_longue = "Cette commande per... | the_stack_v2_python_sparse | src/secondaires/familier/commandes/familier/chasser.py | vincent-lg/tsunami | train | 5 |
07a02f8fc8a72acdc9378ee9e07d393823442960 | [
"self._lock = allocate_lock()\nself._loaded = {}\nPictureManager.MANAGER = self",
"resource_wrapper = ResourceWrapper(name=name)\nstart_new_thread(self.load_picture_asynchronously, (resource_wrapper,))\nreturn resource_wrapper",
"try:\n logging.debug('Begin loading picture ' + resource_wrapper.name)\n sel... | <|body_start_0|>
self._lock = allocate_lock()
self._loaded = {}
PictureManager.MANAGER = self
<|end_body_0|>
<|body_start_1|>
resource_wrapper = ResourceWrapper(name=name)
start_new_thread(self.load_picture_asynchronously, (resource_wrapper,))
return resource_wrapper
<|e... | The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture. | PictureManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
... | stack_v2_sparse_classes_10k_train_003672 | 2,624 | no_license | [
{
"docstring": "Generates a new instance of this class. Generates a new instance of this class and sets the field information.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Loads the picture. This method loads the picture with the given name. Calling this method star... | 4 | stack_v2_sparse_classes_30k_train_006260 | Implement the Python class `PictureManager` described below.
Class description:
The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded pic... | Implement the Python class `PictureManager` described below.
Class description:
The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded pic... | 0308785a51bf61d9a4fec2d8370540df502b8178 | <|skeleton|>
class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PictureManager:
"""The picture manager class. An instance of this class represents a picture manager. This manager loads pictures asynchronously. Attributes: _lock: A lock for controlling asynchronous access. _loaded: A dictionary containing every loaded picture."""
def __init__(self):
"""Generat... | the_stack_v2_python_sparse | resources/pictures/picture_manager.py | donhilion/JumpAndRun | train | 0 |
8f31ed944aa942639b0b7975aa33d03dddfbdc7d | [
"self.auth = ('api', api_key)\nself.api_url = f'https://api.mailgun.net/v3/{domain}'\nself.sender = f'{sender_name} <noreply@{domain}>'",
"data['from'] = self.sender\ntry:\n return requests.post(f'{self.api_url}/messages', auth=self.auth, data=data)\nexcept (requests.HTTPError, requests.ConnectionError):\n ... | <|body_start_0|>
self.auth = ('api', api_key)
self.api_url = f'https://api.mailgun.net/v3/{domain}'
self.sender = f'{sender_name} <noreply@{domain}>'
<|end_body_0|>
<|body_start_1|>
data['from'] = self.sender
try:
return requests.post(f'{self.api_url}/messages', auth... | Send a mail through the Mailgun API. | Mailer | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mailer:
"""Send a mail through the Mailgun API."""
def __init__(self, domain: str, api_key: str, sender_name: str) -> None:
"""Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param ... | stack_v2_sparse_classes_10k_train_003673 | 1,385 | permissive | [
{
"docstring": "Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param sender_name: name of the person sending the email :type sender_name: str",
"name": "__init__",
"signature": "def __init__(self, dom... | 2 | stack_v2_sparse_classes_30k_train_005889 | Implement the Python class `Mailer` described below.
Class description:
Send a mail through the Mailgun API.
Method signatures and docstrings:
- def __init__(self, domain: str, api_key: str, sender_name: str) -> None: Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_k... | Implement the Python class `Mailer` described below.
Class description:
Send a mail through the Mailgun API.
Method signatures and docstrings:
- def __init__(self, domain: str, api_key: str, sender_name: str) -> None: Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_k... | cd28d87ae7dbb37b40c549fb2312896603809385 | <|skeleton|>
class Mailer:
"""Send a mail through the Mailgun API."""
def __init__(self, domain: str, api_key: str, sender_name: str) -> None:
"""Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Mailer:
"""Send a mail through the Mailgun API."""
def __init__(self, domain: str, api_key: str, sender_name: str) -> None:
"""Initialize the Mailer class. :param domain: Domain name of the sender :type domain: str :param api_key: API key of the Mailgun API :type api_key: str :param sender_name: ... | the_stack_v2_python_sparse | mailer.py | CCExtractor/sample-platform | train | 30 |
063e8a7d4a93dda1d9e1bd8322c73a7f2654cd9a | [
"self.header = {'Cache-Control': 'no-cache ', 'content-type': 'application/json'}\nself.data = '{}'\nself.api_url = f'{airflow_base_url}/api/experimental'\nself.dag_url = f'{self.api_url}/dags'",
"request_url = f'{self.dag_url}/{job_id}/paused/{str(not unpause)}'\nresponse = requests.get(request_url, headers=self... | <|body_start_0|>
self.header = {'Cache-Control': 'no-cache ', 'content-type': 'application/json'}
self.data = '{}'
self.api_url = f'{airflow_base_url}/api/experimental'
self.dag_url = f'{self.api_url}/dags'
<|end_body_0|>
<|body_start_1|>
request_url = f'{self.dag_url}/{job_id}/... | This class handles REST requests to the Airflow instance. | AirflowRestConnection | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AirflowRestConnection:
"""This class handles REST requests to the Airflow instance."""
def __init__(self, airflow_base_url: str) -> None:
"""Initialise Airflow REST connection service"""
<|body_0|>
def unpause_dag(self, job_id: str, unpause: bool=True) -> bool:
"... | stack_v2_sparse_classes_10k_train_003674 | 3,084 | permissive | [
{
"docstring": "Initialise Airflow REST connection service",
"name": "__init__",
"signature": "def __init__(self, airflow_base_url: str) -> None"
},
{
"docstring": "Pause/unpause dag",
"name": "unpause_dag",
"signature": "def unpause_dag(self, job_id: str, unpause: bool=True) -> bool"
... | 5 | stack_v2_sparse_classes_30k_train_006646 | Implement the Python class `AirflowRestConnection` described below.
Class description:
This class handles REST requests to the Airflow instance.
Method signatures and docstrings:
- def __init__(self, airflow_base_url: str) -> None: Initialise Airflow REST connection service
- def unpause_dag(self, job_id: str, unpaus... | Implement the Python class `AirflowRestConnection` described below.
Class description:
This class handles REST requests to the Airflow instance.
Method signatures and docstrings:
- def __init__(self, airflow_base_url: str) -> None: Initialise Airflow REST connection service
- def unpause_dag(self, job_id: str, unpaus... | 4890f05a2394dfd27b324f07c5f25222702941ad | <|skeleton|>
class AirflowRestConnection:
"""This class handles REST requests to the Airflow instance."""
def __init__(self, airflow_base_url: str) -> None:
"""Initialise Airflow REST connection service"""
<|body_0|>
def unpause_dag(self, job_id: str, unpause: bool=True) -> bool:
"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AirflowRestConnection:
"""This class handles REST requests to the Airflow instance."""
def __init__(self, airflow_base_url: str) -> None:
"""Initialise Airflow REST connection service"""
self.header = {'Cache-Control': 'no-cache ', 'content-type': 'application/json'}
self.data = '... | the_stack_v2_python_sparse | services/jobs/jobs/dependencies/airflow_conn.py | bgoesswe/openeo-openshift-driver | train | 0 |
2a845448eb653775a56b847a7086e5def4ce1a4b | [
"self._write = write\nself._bufsize = bufsize\nself._wbuf = BytesIO()\nself._buflen = 0",
"line = pkt_line(data)\nline_len = len(line)\nover = self._buflen + line_len - self._bufsize\nif over >= 0:\n start = line_len - over\n self._wbuf.write(line[:start])\n self.flush()\nelse:\n start = 0\nsaved = li... | <|body_start_0|>
self._write = write
self._bufsize = bufsize
self._wbuf = BytesIO()
self._buflen = 0
<|end_body_0|>
<|body_start_1|>
line = pkt_line(data)
line_len = len(line)
over = self._buflen + line_len - self._bufsize
if over >= 0:
start ... | Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size. | BufferedPktLineWriter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BufferedPktLineWriter:
"""Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size."""
... | stack_v2_sparse_classes_10k_train_003675 | 17,727 | permissive | [
{
"docstring": "Initialize the BufferedPktLineWriter. :param write: A write callback for the underlying writer. :param bufsize: The internal buffer size, including length prefixes.",
"name": "__init__",
"signature": "def __init__(self, write, bufsize=65515)"
},
{
"docstring": "Write data, wrappi... | 3 | stack_v2_sparse_classes_30k_train_000102 | Implement the Python class `BufferedPktLineWriter` described below.
Class description:
Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length ... | Implement the Python class `BufferedPktLineWriter` described below.
Class description:
Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length ... | d59c99dcdcd280d7eec36a693dd80f8c8c831ea2 | <|skeleton|>
class BufferedPktLineWriter:
"""Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BufferedPktLineWriter:
"""Writer that wraps its data in pkt-lines and has an independent buffer. Consecutive calls to write() wrap the data in a pkt-line and then buffers it until enough lines have been written such that their total length (including length prefix) reach the buffer size."""
def __init__(... | the_stack_v2_python_sparse | modules/dbnd/src/dbnd/_vendor/dulwich/protocol.py | databand-ai/dbnd | train | 257 |
b48b3e974502844fdaa550616e7897dff20d0d27 | [
"M = len(nums1)\nN = len(nums2)\nif (N + M) % 2 == 0:\n K1 = (M + N) / 2\n K2 = (M + N) / 2 + 1\n val1 = self.find_k_Largest(nums1, nums2, K1)\n val2 = self.find_k_Largest(nums1, nums2, K2)\n return (val1 + val2) / 2.0\nelse:\n K = (M + N - 1) / 2 + 1\n return self.find_k_Largest(nums1, nums2, ... | <|body_start_0|>
M = len(nums1)
N = len(nums2)
if (N + M) % 2 == 0:
K1 = (M + N) / 2
K2 = (M + N) / 2 + 1
val1 = self.find_k_Largest(nums1, nums2, K1)
val2 = self.find_k_Largest(nums1, nums2, K2)
return (val1 + val2) / 2.0
else:... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def find_k_Largest(self, nums1, nums2, k):
"""if len(nums1) > k: nums1 = list(nums1[:k]) if len(nums2) > k: nums2 = list(nums2[:k])"... | stack_v2_sparse_classes_10k_train_003676 | 1,672 | permissive | [
{
"docstring": ":type nums1: List[int] :type nums2: List[int] :rtype: float",
"name": "findMedianSortedArrays",
"signature": "def findMedianSortedArrays(self, nums1, nums2)"
},
{
"docstring": "if len(nums1) > k: nums1 = list(nums1[:k]) if len(nums2) > k: nums2 = list(nums2[:k])",
"name": "fi... | 2 | stack_v2_sparse_classes_30k_train_005366 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def find_k_Largest(self, nums1, nums2, k): if len(nums1) > k: nums1 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMedianSortedArrays(self, nums1, nums2): :type nums1: List[int] :type nums2: List[int] :rtype: float
- def find_k_Largest(self, nums1, nums2, k): if len(nums1) > k: nums1 ... | c8633ea7a36d97e4b5e45f33f8c339660e9c2d87 | <|skeleton|>
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
<|body_0|>
def find_k_Largest(self, nums1, nums2, k):
"""if len(nums1) > k: nums1 = list(nums1[:k]) if len(nums2) > k: nums2 = list(nums2[:k])"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
""":type nums1: List[int] :type nums2: List[int] :rtype: float"""
M = len(nums1)
N = len(nums2)
if (N + M) % 2 == 0:
K1 = (M + N) / 2
K2 = (M + N) / 2 + 1
val1 = self.find_k_Largest(nu... | the_stack_v2_python_sparse | Algorithms/#4 Median of Two Sorted Arrays/PythonCode.py | yingcuhk/LeetCode | train | 3 | |
ba5e1d4f0bd54b5de85d6830601869c65aa2bd2c | [
"curnum = 0\ncurstring = ''\nstack = []\nfor char in s:\n if char == '[':\n stack.append(curstring)\n stack.append(curnum)\n curstring = ''\n curnum = 0\n elif char == ']':\n prenum = stack.pop()\n prestring = stack.pop()\n curstring = prestring + prenum * curs... | <|body_start_0|>
curnum = 0
curstring = ''
stack = []
for char in s:
if char == '[':
stack.append(curstring)
stack.append(curnum)
curstring = ''
curnum = 0
elif char == ']':
prenum = s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def decodeString_failed(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
curnum = 0
curstring = ''
stack = []
... | stack_v2_sparse_classes_10k_train_003677 | 2,478 | no_license | [
{
"docstring": ":type s: str :rtype: str",
"name": "decodeString",
"signature": "def decodeString(self, s)"
},
{
"docstring": ":type s: str :rtype: str",
"name": "decodeString_failed",
"signature": "def decodeString_failed(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000046 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s): :type s: str :rtype: str
- def decodeString_failed(self, s): :type s: str :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString(self, s): :type s: str :rtype: str
- def decodeString_failed(self, s): :type s: str :rtype: str
<|skeleton|>
class Solution:
def decodeString(self, s):
... | 93266095329e2e8e949a72371b88b07382a60e0d | <|skeleton|>
class Solution:
def decodeString(self, s):
""":type s: str :rtype: str"""
<|body_0|>
def decodeString_failed(self, s):
""":type s: str :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeString(self, s):
""":type s: str :rtype: str"""
curnum = 0
curstring = ''
stack = []
for char in s:
if char == '[':
stack.append(curstring)
stack.append(curnum)
curstring = ''
... | the_stack_v2_python_sparse | decodeString.py | shivangi-prog/leetcode | train | 0 | |
e26a2843d3a6f3a121b0e217070f5cfa6bddf605 | [
"self.vec2d = vec2d\nself.r = 0\nself.c = 0",
"ret = self.vec2d[self.r][self.c]\nself.c += 1\nreturn ret",
"while self.r < len(self.vec2d):\n if self.c < len(self.vec2d[self.r]):\n return True\n self.r += 1\n self.c = 0\nreturn False"
] | <|body_start_0|>
self.vec2d = vec2d
self.r = 0
self.c = 0
<|end_body_0|>
<|body_start_1|>
ret = self.vec2d[self.r][self.c]
self.c += 1
return ret
<|end_body_1|>
<|body_start_2|>
while self.r < len(self.vec2d):
if self.c < len(self.vec2d[self.r]):
... | Vector2D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_003678 | 1,140 | no_license | [
{
"docstring": "Initialize your data structure here. :type vec2d: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, vec2d)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",... | 3 | null | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool | Implement the Python class `Vector2D` described below.
Class description:
Implement the Vector2D class.
Method signatures and docstrings:
- def __init__(self, vec2d): Initialize your data structure here. :type vec2d: List[List[int]]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bool
<|skeleton|>
class V... | 9190d3d178f1733aa226973757ee7e045b7bab00 | <|skeleton|>
class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Vector2D:
def __init__(self, vec2d):
"""Initialize your data structure here. :type vec2d: List[List[int]]"""
self.vec2d = vec2d
self.r = 0
self.c = 0
def next(self):
""":rtype: int"""
ret = self.vec2d[self.r][self.c]
self.c += 1
return ret
... | the_stack_v2_python_sparse | Flatten2DVector.py | ellinx/LC-python | train | 1 | |
42b7a0649aa3139970e87a4a25ab0400c011e289 | [
"query = {}\nif related_rule_id:\n query['rule__id'] = related_rule_id\nqueryset = ScheduledTask.filter(**query).prefetch_related('rule').offset(offset).limit(limit).order_by('-created_at')\nreturn await ScheduledTask_Pydantic.from_queryset(queryset)",
"task = await ScheduledTask.get(id=task_id)\nif task is No... | <|body_start_0|>
query = {}
if related_rule_id:
query['rule__id'] = related_rule_id
queryset = ScheduledTask.filter(**query).prefetch_related('rule').offset(offset).limit(limit).order_by('-created_at')
return await ScheduledTask_Pydantic.from_queryset(queryset)
<|end_body_0|>... | ScheduledTaskRepository | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduledTaskRepository:
async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]:
"""Get the list of scheduled tasks. :return: list of scheduled tasks"""
<|body_0|>
async def delete(task_id):
"""Delete a scheduled task. :return: None"... | stack_v2_sparse_classes_10k_train_003679 | 1,095 | permissive | [
{
"docstring": "Get the list of scheduled tasks. :return: list of scheduled tasks",
"name": "get",
"signature": "async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]"
},
{
"docstring": "Delete a scheduled task. :return: None",
"name": "delete",
"signat... | 2 | stack_v2_sparse_classes_30k_train_000665 | Implement the Python class `ScheduledTaskRepository` described below.
Class description:
Implement the ScheduledTaskRepository class.
Method signatures and docstrings:
- async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]: Get the list of scheduled tasks. :return: list of schedule... | Implement the Python class `ScheduledTaskRepository` described below.
Class description:
Implement the ScheduledTaskRepository class.
Method signatures and docstrings:
- async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]: Get the list of scheduled tasks. :return: list of schedule... | ac3a15014ad3c3bdac523a6550934a06653cfba1 | <|skeleton|>
class ScheduledTaskRepository:
async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]:
"""Get the list of scheduled tasks. :return: list of scheduled tasks"""
<|body_0|>
async def delete(task_id):
"""Delete a scheduled task. :return: None"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScheduledTaskRepository:
async def get(offset: int, limit: int, related_rule_id: int=None) -> List[ScheduledTask]:
"""Get the list of scheduled tasks. :return: list of scheduled tasks"""
query = {}
if related_rule_id:
query['rule__id'] = related_rule_id
queryset = S... | the_stack_v2_python_sparse | packages/task-scheduler/task_scheduler/repositories/scheduled_task_handler.py | matiasbavera/romi-dashboard | train | 0 | |
bdcaaf34f2bd9299074a819b6d6601139de0fff0 | [
"self._loop = loop or asyncio.get_event_loop()\nself._periodic_callable = callback\nself._start_at = start_at or datetime.datetime.now()\nself._period = period\nself._timerhandle: Optional[TimerHandle] = None\nself._exception_callback = exception_callback",
"self._schedule_call()\ntry:\n self._periodic_callabl... | <|body_start_0|>
self._loop = loop or asyncio.get_event_loop()
self._periodic_callable = callback
self._start_at = start_at or datetime.datetime.now()
self._period = period
self._timerhandle: Optional[TimerHandle] = None
self._exception_callback = exception_callback
<|end... | Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio. | PeriodicCaller | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeriodicCaller:
"""Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio."""
def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exception_callback: Optional[Callable[[Callable, Exception], None]]=Non... | stack_v2_sparse_classes_10k_train_003680 | 19,352 | permissive | [
{
"docstring": "Init periodic caller. :param callback: function to call periodically :param period: period in seconds. :param start_at: optional first call datetime :param exception_callback: optional handler to call on exception raised. :param loop: optional asyncio event loop",
"name": "__init__",
"si... | 5 | null | Implement the Python class `PeriodicCaller` described below.
Class description:
Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio.
Method signatures and docstrings:
- def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exc... | Implement the Python class `PeriodicCaller` described below.
Class description:
Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio.
Method signatures and docstrings:
- def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exc... | bec49adaeba661d8d0f03ac9935dc89f39d95a0d | <|skeleton|>
class PeriodicCaller:
"""Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio."""
def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exception_callback: Optional[Callable[[Callable, Exception], None]]=Non... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PeriodicCaller:
"""Schedule a periodic call of callable using event loop. Used for periodic function run using asyncio."""
def __init__(self, callback: Callable, period: float, start_at: Optional[datetime.datetime]=None, exception_callback: Optional[Callable[[Callable, Exception], None]]=None, loop: Opti... | the_stack_v2_python_sparse | aea/helpers/async_utils.py | fetchai/agents-aea | train | 192 |
1b32a71943ebd0ab60af7f4131810d85a084db2a | [
"if value_renderer_class is None:\n value_renderer_class = Value\nreturn super(List, cls).from_value_iterable(value_iterable=value_iterable, value_renderer_class=value_renderer_class, frame_renderer_class=frame_renderer_class, **listkwargs)",
"css_classes = super(List, self).get_base_css_classes_list()\ncss_cl... | <|body_start_0|>
if value_renderer_class is None:
value_renderer_class = Value
return super(List, cls).from_value_iterable(value_iterable=value_iterable, value_renderer_class=value_renderer_class, frame_renderer_class=frame_renderer_class, **listkwargs)
<|end_body_0|>
<|body_start_1|>
... | Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`. | List | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewh... | stack_v2_sparse_classes_10k_train_003681 | 2,880 | permissive | [
{
"docstring": "Overrides :meth:`.cradmin_legacy.viewhelpers.listbuilder.base.List.from_value_iterable` to set :class:`.Value` as the default ``value_renderer_class``.",
"name": "from_value_iterable",
"signature": "def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_cl... | 2 | stack_v2_sparse_classes_30k_train_001836 | Implement the Python class `List` described below.
Class description:
Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`.
Method signatures and docstrings:
- def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=No... | Implement the Python class `List` described below.
Class description:
Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`.
Method signatures and docstrings:
- def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=No... | 31a9d114a2aed6cf1e54dac2e6a096c3503b4e3c | <|skeleton|>
class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class List:
"""Renders a list for previewing selection in :class:`cradmin_legacy.viewhelpers.multiselect2.manytomanywidget.Widget`."""
def from_value_iterable(cls, value_iterable, value_renderer_class=None, frame_renderer_class=None, **listkwargs):
"""Overrides :meth:`.cradmin_legacy.viewhelpers.listbu... | the_stack_v2_python_sparse | cradmin_legacy/viewhelpers/multiselect2/widget_preview_renderer.py | appressoas/cradmin_legacy | train | 0 |
48bb8791f69ba205edf419dc497c15e0a2852744 | [
"n = len(s)\ndp = [[0 for _ in range(n)] for _ in range(n)]\nfor left in range(n - 1, -1, -1):\n dp[left][left] = 1\n for right in range(left + 1, n):\n if s[left] == s[right]:\n dp[left][right] = dp[left + 1][right - 1] + 2\n else:\n dp[left][right] = max(dp[left + 1][righ... | <|body_start_0|>
n = len(s)
dp = [[0 for _ in range(n)] for _ in range(n)]
for left in range(n - 1, -1, -1):
dp[left][left] = 1
for right in range(left + 1, n):
if s[left] == s[right]:
dp[left][right] = dp[left + 1][right - 1] + 2
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
"""AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :return:"""
<|body_0|>
def longestPalindromeSubseq2(self, s: str) -> int:
"""86 ... | stack_v2_sparse_classes_10k_train_003682 | 1,724 | permissive | [
{
"docstring": "AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :return:",
"name": "longestPalindromeSubseq",
"signature": "def longestPalindromeSubseq(self, s: str) -> int"
},
{
"docstring": "86 / 86 test cases passed, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeSubseq(self, s: str) -> int: AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :ret... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestPalindromeSubseq(self, s: str) -> int: AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :ret... | 4dd1e54d8d08f7e6590bc76abd08ecaacaf775e5 | <|skeleton|>
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
"""AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :return:"""
<|body_0|>
def longestPalindromeSubseq2(self, s: str) -> int:
"""86 ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
"""AC: 05/05/2022 Runtime: 2385 ms, faster than 46.10% Memory Usage: 31.4 MB, less than 46.41% 1 <= s.length <= 1000 :param s: :return:"""
n = len(s)
dp = [[0 for _ in range(n)] for _ in range(n)]
for left in range(n -... | the_stack_v2_python_sparse | src/516-LongestPalindromicSubsequence.py | Jiezhi/myleetcode | train | 1 | |
8154bf856ea7c7b9578c63f59ccffd17b566d746 | [
"super().__init__()\nself.multioutputWrapper = True\nimport sklearn\nimport sklearn.ensemble\nself.model = sklearn.ensemble.BaggingRegressor",
"specs = super().getInputSpecification()\nspecs.description = 'The \\\\xmlNode{BaggingRegressor} is an ensemble meta-estimator that fits base regressors each on random sub... | <|body_start_0|>
super().__init__()
self.multioutputWrapper = True
import sklearn
import sklearn.ensemble
self.model = sklearn.ensemble.BaggingRegressor
<|end_body_0|>
<|body_start_1|>
specs = super().getInputSpecification()
specs.description = 'The \\xmlNode{Bag... | A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the... | BaggingRegressor | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaggingRegressor:
"""A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator ... | stack_v2_sparse_classes_10k_train_003683 | 8,307 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 4 | null | Implement the Python class `BaggingRegressor` described below.
Class description:
A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a f... | Implement the Python class `BaggingRegressor` described below.
Class description:
A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a f... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class BaggingRegressor:
"""A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaggingRegressor:
"""A Bagging Regressor A Bagging regressor is an ensemble meta-estimator that fits base regressors each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/Ensemble/BaggingRegressor.py | idaholab/raven | train | 201 |
1a97c51cb6c8ec32847aa86cae3f67543fe1e36d | [
"def _doLogin(soapStub):\n si = vim.ServiceInstance('ServiceInstance', soapStub)\n sm = si.content.sessionManager\n if not sm.currentSession:\n si.content.sessionManager.Login(username, password, locale)\nreturn _doLogin",
"def _doLogin(soapStub):\n si = vim.ServiceInstance('ServiceInstance', s... | <|body_start_0|>
def _doLogin(soapStub):
si = vim.ServiceInstance('ServiceInstance', soapStub)
sm = si.content.sessionManager
if not sm.currentSession:
si.content.sessionManager.Login(username, password, locale)
return _doLogin
<|end_body_0|>
<|body_s... | A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information. | VimSessionOrientedStub | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VimSessionOrientedStub:
"""A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information."""
def makeUserLoginMethod(username, password, locale=None):
"""Return a function that will call the vim.SessionManager.Login() method with... | stack_v2_sparse_classes_10k_train_003684 | 38,725 | permissive | [
{
"docstring": "Return a function that will call the vim.SessionManager.Login() method with the given parameters. The result of this function can be passed as the \"loginMethod\" to a SessionOrientedStub constructor.",
"name": "makeUserLoginMethod",
"signature": "def makeUserLoginMethod(username, passwo... | 4 | stack_v2_sparse_classes_30k_train_001408 | Implement the Python class `VimSessionOrientedStub` described below.
Class description:
A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information.
Method signatures and docstrings:
- def makeUserLoginMethod(username, password, locale=None): Return a function ... | Implement the Python class `VimSessionOrientedStub` described below.
Class description:
A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information.
Method signatures and docstrings:
- def makeUserLoginMethod(username, password, locale=None): Return a function ... | f0fe4e279cebdfdbca5bfce699063d15b1d3bd1d | <|skeleton|>
class VimSessionOrientedStub:
"""A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information."""
def makeUserLoginMethod(username, password, locale=None):
"""Return a function that will call the vim.SessionManager.Login() method with... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VimSessionOrientedStub:
"""A vim-specific SessionOrientedStub. See the SessionOrientedStub class in pyVmomi/SoapAdapter.py for more information."""
def makeUserLoginMethod(username, password, locale=None):
"""Return a function that will call the vim.SessionManager.Login() method with the given pa... | the_stack_v2_python_sparse | pyVim/connect.py | vmware/pyvmomi | train | 2,122 |
ac4ab8f5b25e63e45c83a2d17f875724737d7fae | [
"prev = None\nwhile head:\n cur = head\n head = head.next\n cur.next = prev\n prev = cur\nreturn prev",
"prev = None\nwhile head:\n nh = head.next\n head.next = prev\n prev = head\n head = nh\nreturn prev",
"def reverse(node):\n prev = None\n while node:\n nextNode = node.ne... | <|body_start_0|>
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
<|end_body_0|>
<|body_start_1|>
prev = None
while head:
nh = head.next
head.next = prev
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def rewrite2(self, head):
""":type head: ListNode :rtype: ListNode"""
... | stack_v2_sparse_classes_10k_train_003685 | 1,896 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "reverseList",
"signature": "def reverseList(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "rewrite",
"signature": "def rewrite(self, head)"
},
{
"docstring": ":type head: ListNode :... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def rewrite(self, head): :type head: ListNode :rtype: ListNode
- def rewrite2(self, head): :type head: ListNo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseList(self, head): :type head: ListNode :rtype: ListNode
- def rewrite(self, head): :type head: ListNode :rtype: ListNode
- def rewrite2(self, head): :type head: ListNo... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def rewrite(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_1|>
def rewrite2(self, head):
""":type head: ListNode :rtype: ListNode"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def reverseList(self, head):
""":type head: ListNode :rtype: ListNode"""
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
def rewrite(self, head):
""":type head: Lis... | the_stack_v2_python_sparse | co_uber/206_Reverse_Linked_List.py | vsdrun/lc_public | train | 6 | |
9aadfc02f47751f9d1b2fd6f4582573a3a9d934a | [
"url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'\nreq = urllib2.Request(url)\nf = urllib2.urlopen(req)\nsoup = BeautifulSoup(f)\ntable = soup.find('table', attrs={'class': 'contenido'})\nbanks = []\nfor row in table.findAll('tr')[2:]:\n banks.append([td.ge... | <|body_start_0|>
url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'
req = urllib2.Request(url)
f = urllib2.urlopen(req)
soup = BeautifulSoup(f)
table = soup.find('table', attrs={'class': 'contenido'})
banks = []
... | Banks | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
<|body_0|>
def get_values(banks_list):
""":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco""... | stack_v2_sparse_classes_10k_train_003686 | 1,626 | no_license | [
{
"docstring": "Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping",
"name": "get_banks_list",
"signature": "def get_banks_list()"
},
{
"docstring": ":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco",
"n... | 2 | stack_v2_sparse_classes_30k_train_002726 | Implement the Python class `Banks` described below.
Class description:
Implement the Banks class.
Method signatures and docstrings:
- def get_banks_list(): Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping
- def get_values(banks_list): :param banks_list: Lista de bancos. :ret... | Implement the Python class `Banks` described below.
Class description:
Implement the Banks class.
Method signatures and docstrings:
- def get_banks_list(): Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping
- def get_values(banks_list): :param banks_list: Lista de bancos. :ret... | 1a60305c457c84cae6de9481efc9ca5c459038f6 | <|skeleton|>
class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
<|body_0|>
def get_values(banks_list):
""":param banks_list: Lista de bancos. :return: Lista de diccionarios con los valores de cada banco""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Banks:
def get_banks_list():
"""Obtiene la lista de bancos desde AFIP utilizando la libreria BeautifulSoup para webscraping"""
url = 'http://www.afip.gov.ar/genericos/emisorasGarantias/formularioCompa%C3%B1ias.asp?completo=1&ent=3'
req = urllib2.Request(url)
f = urllib2.urlopen... | the_stack_v2_python_sparse | l10n_ar_api/padron/banks.py | MarcoKlemenc/l10n_ar_api | train | 0 | |
64a23c081038a7d6e11e263dc1ee8549f1d23fd8 | [
"super().__init__()\nself._accept_input = accept_input\nself._default_measure = default_measure\nself._in_place = in_place",
"try:\n return BasicEngine.is_available(self, cmd)\nexcept LastEngineException:\n return True",
"if self.is_last_engine and cmd.gate == Measure:\n if get_control_count(cmd) != 0:... | <|body_start_0|>
super().__init__()
self._accept_input = accept_input
self._default_measure = default_measure
self._in_place = in_place
<|end_body_0|>
<|body_start_1|>
try:
return BasicEngine.is_available(self, cmd)
except LastEngineException:
ret... | Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine. | CommandPrinter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
""... | stack_v2_sparse_classes_10k_train_003687 | 4,917 | permissive | [
{
"docstring": "Initialize a CommandPrinter. Args: accept_input (bool): If accept_input is true, the printer queries the user to input measurement results if the CommandPrinter is the last engine. Otherwise, all measurements yield default_measure. default_measure (bool): Default measurement result (if accept_in... | 4 | stack_v2_sparse_classes_30k_train_000142 | Implement the Python class `CommandPrinter` described below.
Class description:
Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine.
Method signatures and docstrings:
- def __init__(self, a... | Implement the Python class `CommandPrinter` described below.
Class description:
Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine.
Method signatures and docstrings:
- def __init__(self, a... | 67c660ca18725d23ab0b261a45e34873b6a58d03 | <|skeleton|>
class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommandPrinter:
"""Compiler engine that prints command to the standard output. CommandPrinter is a compiler engine which prints commands to stdout prior to sending them on to the next compiler engine."""
def __init__(self, accept_input=True, default_measure=False, in_place=False):
"""Initialize a... | the_stack_v2_python_sparse | projectq/backends/_printer.py | ProjectQ-Framework/ProjectQ | train | 886 |
43fe3211ab8df19c10531980f8434b516fec1a4e | [
"super().__init__()\nself.n_heads = n_heads\nself.down_kv = down_kv\nw_norm = w_norm_dispatch(w_norm)\nself.q_proj = w_norm(nn.Conv1d(C_in_q, C_qk, 1))\nself.k_proj = w_norm(nn.Conv1d(C_in_kv, C_qk, 1))\nself.v_proj = w_norm(nn.Conv1d(C_in_kv, C_v, 1))\nself.out = w_norm(nn.Conv2d(C_v, C_v, 1))\nif scale:\n self... | <|body_start_0|>
super().__init__()
self.n_heads = n_heads
self.down_kv = down_kv
w_norm = w_norm_dispatch(w_norm)
self.q_proj = w_norm(nn.Conv1d(C_in_q, C_qk, 1))
self.k_proj = w_norm(nn.Conv1d(C_in_kv, C_qk, 1))
self.v_proj = w_norm(nn.Conv1d(C_in_kv, C_v, 1))
... | Attention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None):
"""Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner v... | stack_v2_sparse_classes_10k_train_003688 | 37,491 | no_license | [
{
"docstring": "Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, which same as output dim down_kv: Area attention for lightweight self-attention w/ mean pooling. rel_pos_size: height & width for rel... | 2 | null | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None): Args: C_in_q: query source (encoder feature x) C_in_kv:... | Implement the Python class `Attention` described below.
Class description:
Implement the Attention class.
Method signatures and docstrings:
- def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None): Args: C_in_q: query source (encoder feature x) C_in_kv:... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class Attention:
def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None):
"""Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Attention:
def __init__(self, C_in_q, C_in_kv, C_qk, C_v, w_norm='none', scale=False, n_heads=1, down_kv=False, rel_pos_size=None):
"""Args: C_in_q: query source (encoder feature x) C_in_kv: key/value source (decoder feature y) C_qk: inner query/key dim, which should be same C_v: inner value dim, whic... | the_stack_v2_python_sparse | generated/test_clovaai_dmfont.py | jansel/pytorch-jit-paritybench | train | 35 | |
d9764da633d7d0165f274e36e493ce62af080c72 | [
"super().__init__()\nself.embed_dim, self.n_heads, self.head_dim = (embed_dim, n_heads, head_dim)\nself.qk_layer_norms = qk_layer_norms\nself.context_layer_norm = nn.LayerNorm(self.embed_dim)\nself.latents_layer_norm = nn.LayerNorm(self.embed_dim)\nif self.qk_layer_norms:\n self.q_layer_norm = nn.LayerNorm(self.... | <|body_start_0|>
super().__init__()
self.embed_dim, self.n_heads, self.head_dim = (embed_dim, n_heads, head_dim)
self.qk_layer_norms = qk_layer_norms
self.context_layer_norm = nn.LayerNorm(self.embed_dim)
self.latents_layer_norm = nn.LayerNorm(self.embed_dim)
if self.qk_l... | IdeficsPerceiverAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdeficsPerceiverAttention:
def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None:
"""Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`"""
<|body_0|>
def forward(self, context: tor... | stack_v2_sparse_classes_10k_train_003689 | 9,432 | permissive | [
{
"docstring": "Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`",
"name": "__init__",
"signature": "def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None"
},
{
"docstring": "Runs Perceiver Self-Atte... | 2 | null | Implement the Python class `IdeficsPerceiverAttention` described below.
Class description:
Implement the IdeficsPerceiverAttention class.
Method signatures and docstrings:
- def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None: Perceiver Cross-Attention Module --> let long-for... | Implement the Python class `IdeficsPerceiverAttention` described below.
Class description:
Implement the IdeficsPerceiverAttention class.
Method signatures and docstrings:
- def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None: Perceiver Cross-Attention Module --> let long-for... | 4fa0aff21ee083d0197a898cdf17ff476fae2ac3 | <|skeleton|>
class IdeficsPerceiverAttention:
def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None:
"""Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`"""
<|body_0|>
def forward(self, context: tor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IdeficsPerceiverAttention:
def __init__(self, embed_dim: int, n_heads: int, head_dim: int, qk_layer_norms: bool) -> None:
"""Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`"""
super().__init__()
self.embed_dim, self.n_heads, sel... | the_stack_v2_python_sparse | src/transformers/models/idefics/perceiver.py | huggingface/transformers | train | 102,193 | |
7010ab9e510a09cd4a08a29ec9004c514cfc0ff5 | [
"self.to_address = to_address\nself.from_address = from_address\nif template_type is None:\n self.content = content\n self.subject = subject\nelse:\n template = get_email_template(template_type)\n self.subject = template.subject\n self.content = template.content\n for key in parameters:\n i... | <|body_start_0|>
self.to_address = to_address
self.from_address = from_address
if template_type is None:
self.content = content
self.subject = subject
else:
template = get_email_template(template_type)
self.subject = template.subject
... | An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of the email content: A string containing the content of the email Class Attrib... | SesEmail | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SesEmail:
"""An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of the email content: A string containing t... | stack_v2_sparse_classes_10k_train_003690 | 3,877 | permissive | [
{
"docstring": "Creates an email object to be sent Args: to_address: Email is sent to this address from_address: This will appear as the sender, must be an address verified through S3 for cloud version content: Body of email subject: Subject line of email template_type: What type of template to use to fill in t... | 2 | null | Implement the Python class `SesEmail` described below.
Class description:
An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of t... | Implement the Python class `SesEmail` described below.
Class description:
An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of t... | b12c73976fd7eb5728eda90e56e053759c733c35 | <|skeleton|>
class SesEmail:
"""An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of the email content: A string containing t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SesEmail:
"""An email object that can be sent to a user Attributes: to_address: A string containing the address to send the email to from_address: A string containing the address the email is being sent from subject: A string containing the subject line of the email content: A string containing the content of... | the_stack_v2_python_sparse | dataactbroker/handlers/aws/sesEmail.py | fedspendingtransparency/data-act-broker-backend | train | 55 |
033e5cd1ea8ddb9f25f7f8bc26c1dd398ef19233 | [
"self.approx = approx\nself.divisor = divisor\nself.force_fma = force_fma\nif force_fma:\n self.error = FusedMultiplyAdd(divisor, approx, 1.0, specifier=FusedMultiplyAdd.SubtractNegate)\n self.new_approx = FusedMultiplyAdd(self.error, self.approx, self.approx, specifier=FusedMultiplyAdd.Standard)\nelse:\n ... | <|body_start_0|>
self.approx = approx
self.divisor = divisor
self.force_fma = force_fma
if force_fma:
self.error = FusedMultiplyAdd(divisor, approx, 1.0, specifier=FusedMultiplyAdd.SubtractNegate)
self.new_approx = FusedMultiplyAdd(self.error, self.approx, self.ap... | Newton-Raphson iteration generator | NR_Iteration | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NR_Iteration:
"""Newton-Raphson iteration generator"""
def __init__(self, approx, divisor, force_fma=False):
"""@param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the use of Fused Multiply and Add"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_003691 | 33,449 | permissive | [
{
"docstring": "@param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the use of Fused Multiply and Add",
"name": "__init__",
"signature": "def __init__(self, approx, divisor, force_fma=False)"
},
{
"docstring": "generate a hint rule to he... | 2 | stack_v2_sparse_classes_30k_train_000755 | Implement the Python class `NR_Iteration` described below.
Class description:
Newton-Raphson iteration generator
Method signatures and docstrings:
- def __init__(self, approx, divisor, force_fma=False): @param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the ... | Implement the Python class `NR_Iteration` described below.
Class description:
Newton-Raphson iteration generator
Method signatures and docstrings:
- def __init__(self, approx, divisor, force_fma=False): @param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the ... | f96b1bc33a1cffd14cc322a770835cc7435de599 | <|skeleton|>
class NR_Iteration:
"""Newton-Raphson iteration generator"""
def __init__(self, approx, divisor, force_fma=False):
"""@param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the use of Fused Multiply and Add"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NR_Iteration:
"""Newton-Raphson iteration generator"""
def __init__(self, approx, divisor, force_fma=False):
"""@param approx initial approximation of 1.0 / @p divisor @param divisor reciprocal input @param force_fma force the use of Fused Multiply and Add"""
self.approx = approx
... | the_stack_v2_python_sparse | metalibm_functions/ml_div.py | metalibm/metalibm | train | 23 |
5e8b9932734bec2eac26839189e7c997956ec95b | [
"if self.request.version == 'v6':\n return WorkspaceSerializerV6\nelif self.request.version == 'v7':\n return WorkspaceSerializerV6",
"if request.version == 'v6':\n return self._list_v6(request)\nelif request.version == 'v7':\n return self._list_v6(request)\nraise Http404()",
"started = rest_util.pa... | <|body_start_0|>
if self.request.version == 'v6':
return WorkspaceSerializerV6
elif self.request.version == 'v7':
return WorkspaceSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self._list_v6(request)
elif request.versi... | This view is the endpoint for retrieving the list of all workspaces. | WorkspacesView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkspacesView:
"""This view is the endpoint for retrieving the list of all workspaces."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def list(self, request):
"""Retrieves the... | stack_v2_sparse_classes_10k_train_003692 | 19,677 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Retrieves the list of all workspaces and returns it in JSON form :param request: the HTTP GET reque... | 5 | stack_v2_sparse_classes_30k_train_004857 | Implement the Python class `WorkspacesView` described below.
Class description:
This view is the endpoint for retrieving the list of all workspaces.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, re... | Implement the Python class `WorkspacesView` described below.
Class description:
This view is the endpoint for retrieving the list of all workspaces.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of the REST API
- def list(self, re... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class WorkspacesView:
"""This view is the endpoint for retrieving the list of all workspaces."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
<|body_0|>
def list(self, request):
"""Retrieves the... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class WorkspacesView:
"""This view is the endpoint for retrieving the list of all workspaces."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API"""
if self.request.version == 'v6':
return WorkspaceSerializerV6
... | the_stack_v2_python_sparse | scale/storage/views.py | kfconsultant/scale | train | 0 |
fb24cec1aa24f392fb95df2a52f84369e87c5a90 | [
"employee = Employee.objects.get(user=request.auth.user)\nbug_priority = BugPriority.objects.get(pk=request.data['priority'])\nbug_type = BugType.objects.get(pk=request.data['type'])\nbug = Bug()\nbug.title = request.data['title']\nbug.description = request.data['description']\nbug.entry_date = request.data['entry_... | <|body_start_0|>
employee = Employee.objects.get(user=request.auth.user)
bug_priority = BugPriority.objects.get(pk=request.data['priority'])
bug_type = BugType.objects.get(pk=request.data['type'])
bug = Bug()
bug.title = request.data['title']
bug.description = request.dat... | Bugbo bugs/tikcets | BugView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket Returns: Response -- J... | stack_v2_sparse_classes_10k_train_003693 | 6,207 | no_license | [
{
"docstring": "Handle POST operations Returns: Response -- JSON serialized bug/ticket instance",
"name": "create",
"signature": "def create(self, request)"
},
{
"docstring": "Handle GET requests for single bug/ticket Returns: Response -- JSON serialized bug instance",
"name": "retrieve",
... | 6 | stack_v2_sparse_classes_30k_train_001066 | Implement the Python class `BugView` described below.
Class description:
Bugbo bugs/tikcets
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug/ticket instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket R... | Implement the Python class `BugView` described below.
Class description:
Bugbo bugs/tikcets
Method signatures and docstrings:
- def create(self, request): Handle POST operations Returns: Response -- JSON serialized bug/ticket instance
- def retrieve(self, request, pk=None): Handle GET requests for single bug/ticket R... | 2a74a967bf891d5ddd212f371abef1bf72ebb327 | <|skeleton|>
class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Handle GET requests for single bug/ticket Returns: Response -- J... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BugView:
"""Bugbo bugs/tikcets"""
def create(self, request):
"""Handle POST operations Returns: Response -- JSON serialized bug/ticket instance"""
employee = Employee.objects.get(user=request.auth.user)
bug_priority = BugPriority.objects.get(pk=request.data['priority'])
bu... | the_stack_v2_python_sparse | bugboapi/views/bug.py | S-L-Murphey/Bugbo-server | train | 1 |
0502dec3ca366127bbf437470e1ee00a72dedbad | [
"x = start + 1\ny = end + 1\nz = 2 * x\nwhile z <= y:\n if z <= end and nums[z - 1] < nums[z]:\n z += 1\n if nums[x - 1] < nums[z - 1]:\n nums[x - 1], nums[z - 1] = (nums[z - 1], nums[x - 1])\n x = z\n z = x * 2\n else:\n break",
"n = len(nums)\nsub_roots = n // 2\nfor ... | <|body_start_0|>
x = start + 1
y = end + 1
z = 2 * x
while z <= y:
if z <= end and nums[z - 1] < nums[z]:
z += 1
if nums[x - 1] < nums[z - 1]:
nums[x - 1], nums[z - 1] = (nums[z - 1], nums[x - 1])
x = z
... | Solution4 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
<|body_0|>
def findKthLargest(self, nums: List[int], k: int) -> int:
"""priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zh... | stack_v2_sparse_classes_10k_train_003694 | 11,869 | no_license | [
{
"docstring": "max heap",
"name": "sift_down",
"signature": "def sift_down(self, nums, start, end)"
},
{
"docstring": "priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode-/ 912... | 2 | stack_v2_sparse_classes_30k_train_007105 | Implement the Python class `Solution4` described below.
Class description:
Implement the Solution4 class.
Method signatures and docstrings:
- def sift_down(self, nums, start, end): max heap
- def findKthLargest(self, nums: List[int], k: int) -> int: priority queue, heap sort solution; similar to https://leetcode-cn.c... | Implement the Python class `Solution4` described below.
Class description:
Implement the Solution4 class.
Method signatures and docstrings:
- def sift_down(self, nums, start, end): max heap
- def findKthLargest(self, nums: List[int], k: int) -> int: priority queue, heap sort solution; similar to https://leetcode-cn.c... | 3ea03cd8b1fa507553ebee4fd765c4cc4b5814b6 | <|skeleton|>
class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
<|body_0|>
def findKthLargest(self, nums: List[int], k: int) -> int:
"""priority queue, heap sort solution; similar to https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zh... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution4:
def sift_down(self, nums, start, end):
"""max heap"""
x = start + 1
y = end + 1
z = 2 * x
while z <= y:
if z <= end and nums[z - 1] < nums[z]:
z += 1
if nums[x - 1] < nums[z - 1]:
nums[x - 1], nums[z - 1... | the_stack_v2_python_sparse | Kth_Largest_Element_in_an_Array_215.py | jay6413682/Leetcode | train | 0 | |
83b90a0c45cac5449281001cdfbe5fe513e5e3e4 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwini_gdukuray_justini_utdesai')\nurlNumFirms = 'https://www.mbda.gov/csv_data_export?year=2012&industry=All%20Sectors%20%280%29&minority_group=Total%20Minority&metr... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwini_gdukuray_justini_utdesai')
urlNumFirms = 'https://www.mbda.gov/csv_data_export?year=2012&industry=All%20Sector... | mbdaData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_10k_train_003695 | 5,207 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `mbdaData` described below.
Class description:
Implement the mbdaData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | Implement the Python class `mbdaData` described below.
Class description:
Implement the mbdaData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwin... | the_stack_v2_python_sparse | ashwini_gdukuray_justini_utdesai/mbdaData.py | maximega/course-2019-spr-proj | train | 2 | |
90f118203d5556bd5e4753ac63b74a1273e43c7f | [
"for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j]:\n return True\nreturn False",
"nums = sorted(nums)\nfor i in range(1, len(nums)):\n if nums[i] == nums[i - 1]:\n return True\nreturn False",
"distinct_nums = set()\nfor number in nums:\n if... | <|body_start_0|>
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
<|end_body_0|>
<|body_start_1|>
nums = sorted(nums)
for i in range(1, len(nums)):
if nums[i] == nums[... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplciateOptimized(self, nums):
"""Time N lg N Memory 1 :type nums: List[int] :rtype: bool"""
<|body_1|>
d... | stack_v2_sparse_classes_10k_train_003696 | 1,217 | permissive | [
{
"docstring": "Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool",
"name": "containsDuplicate",
"signature": "def containsDuplicate(self, nums)"
},
{
"docstring": "Time N lg N Memory 1 :type nums: List[int] :rtype: bool",
"name": "containsDuplciateOptimized",
"si... | 3 | stack_v2_sparse_classes_30k_test_000036 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool
- def containsDuplciateOptimized(self, nums): Time N lg N Memory 1 :t... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def containsDuplicate(self, nums): Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool
- def containsDuplciateOptimized(self, nums): Time N lg N Memory 1 :t... | d2ffcccede5d1543aea48f18a39cdbd3d83e3ed8 | <|skeleton|>
class Solution:
def containsDuplicate(self, nums):
"""Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool"""
<|body_0|>
def containsDuplciateOptimized(self, nums):
"""Time N lg N Memory 1 :type nums: List[int] :rtype: bool"""
<|body_1|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def containsDuplicate(self, nums):
"""Brute Force Solution Time N^2, Space 1 :type nums: List[int] :rtype: bool"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] == nums[j]:
return True
return False
... | the_stack_v2_python_sparse | arrays/find_duplicates.py | kandarpck/leetcode | train | 0 | |
18d0197d5e7f99f59394ce50735a3f99f7c55b26 | [
"dp = [[0 for _ in range(n)] for _ in range(m)]\nfor i in range(m):\n dp[i][0] = 1\nfor j in range(n):\n dp[0][j] = 1\nfor i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\nprint(dp)\nreturn dp[-1][-1]",
"dp = [1] * n\nfor i in range(1, m):\n for j in range(1, ... | <|body_start_0|>
dp = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][j] = 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
print(dp)
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:"""
<|body_0|>
def uniquePaths1(self, m: int, n: int) -> int:
"""根据观察,当前坐标的值只与左边和上面的值相关,和其他无关 :param m: :pa... | stack_v2_sparse_classes_10k_train_003697 | 1,665 | no_license | [
{
"docstring": "动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:",
"name": "uniquePaths",
"signature": "def uniquePaths(self, m: int, n: int) -> int"
},
{
"docstring": "根据观察,当前坐标的值只与左边和上面的值相关,和其他无关 :param m: :param n: :return:",
"name": "u... | 2 | stack_v2_sparse_classes_30k_train_001296 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: 动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:
- def uniquePaths1(self, m: in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def uniquePaths(self, m: int, n: int) -> int: 动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:
- def uniquePaths1(self, m: in... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:"""
<|body_0|>
def uniquePaths1(self, m: int, n: int) -> int:
"""根据观察,当前坐标的值只与左边和上面的值相关,和其他无关 :param m: :pa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
"""动态规划, 空间复杂度O(M * N) 时间复杂度O(M * N) dp[i][j] = dp[i - 1][j] + dp[i][j - 1] :param m: :param n: :return:"""
dp = [[0 for _ in range(n)] for _ in range(m)]
for i in range(m):
dp[i][0] = 1
for j in range(n):
... | the_stack_v2_python_sparse | datastructure/dp_exercise/UniquePaths.py | yinhuax/leet_code | train | 0 | |
fc81fb393f4f7f5882c899edf6023835c1620716 | [
"databases = self.process(path)\nqafile = os.path.join(path, 'questions.db')\ndb2qa = DB2QA()\ndb2qa(databases, qafile)",
"for source in Execute.SOURCES:\n spath = os.path.join(path, source)\n decompress = Decompress()\n decompress(spath)\n posts = os.path.join(spath, 'Posts.xml')\n filtered = os.p... | <|body_start_0|>
databases = self.process(path)
qafile = os.path.join(path, 'questions.db')
db2qa = DB2QA()
db2qa(databases, qafile)
<|end_body_0|>
<|body_start_1|>
for source in Execute.SOURCES:
spath = os.path.join(path, source)
decompress = Decompress(... | Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps. | Execute | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Execute:
"""Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps."""
def __call__(self, path):
"""Converts a directory of raw sources to a single output questions database. Args: path: base directory path"""
<|body_0|>
def proces... | stack_v2_sparse_classes_10k_train_003698 | 2,735 | permissive | [
{
"docstring": "Converts a directory of raw sources to a single output questions database. Args: path: base directory path",
"name": "__call__",
"signature": "def __call__(self, path)"
},
{
"docstring": "Iterates through each source and converts raw xml to SQLite databases. Returns a list of out... | 2 | stack_v2_sparse_classes_30k_train_000168 | Implement the Python class `Execute` described below.
Class description:
Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps.
Method signatures and docstrings:
- def __call__(self, path): Converts a directory of raw sources to a single output questions database. Args: path: ... | Implement the Python class `Execute` described below.
Class description:
Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps.
Method signatures and docstrings:
- def __call__(self, path): Converts a directory of raw sources to a single output questions database. Args: path: ... | f398344a4d4bb9dc196a34a504b3d728f71a53ac | <|skeleton|>
class Execute:
"""Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps."""
def __call__(self, path):
"""Converts a directory of raw sources to a single output questions database. Args: path: base directory path"""
<|body_0|>
def proces... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Execute:
"""Main execution method to build a consolidated questions.db file from Stack Exchange Data Dumps."""
def __call__(self, path):
"""Converts a directory of raw sources to a single output questions database. Args: path: base directory path"""
databases = self.process(path)
... | the_stack_v2_python_sparse | src/python/codequestion/etl/stackexchange/execute.py | neuml/codequestion | train | 458 |
8a2345ac252bf0af7c8b7282b8b49e7ddb68b175 | [
"self.backup_run = backup_run\nself.copy_runs = copy_runs\nself.is_paused = is_paused\nself.next_protection_run_time_usecs = next_protection_run_time_usecs\nself.protected_source_uid = protected_source_uid\nself.protection_source = protection_source\nself.source_parameters = source_parameters",
"if dictionary is ... | <|body_start_0|>
self.backup_run = backup_run
self.copy_runs = copy_runs
self.is_paused = is_paused
self.next_protection_run_time_usecs = next_protection_run_time_usecs
self.protected_source_uid = protected_source_uid
self.protection_source = protection_source
sel... | Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRun): Specifies details about the last Backup task. A Back... | ProtectedSourceSummary | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRun): Sp... | stack_v2_sparse_classes_10k_train_003699 | 4,952 | permissive | [
{
"docstring": "Constructor for the ProtectedSourceSummary class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, copy_runs=None, is_paused=None, next_protection_run_time_usecs=None, protected_source_uid=None, protection_source=None, source_parameters=None)"
},
{
"docstrin... | 2 | null | Implement the Python class `ProtectedSourceSummary` described below.
Class description:
Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO.... | Implement the Python class `ProtectedSourceSummary` described below.
Class description:
Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO.... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRun): Sp... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRun): Specifies detai... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protected_source_summary.py | cohesity/management-sdk-python | train | 24 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.