blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e5dc3fb926e7f931721067670acc4475e897e388 | [
"self.word_indices = defaultdict(list)\nfor i, word in enumerate(words):\n self.word_indices[word].append(i)",
"i1 = self.word_indices[word1]\ni2 = self.word_indices[word2]\ndistance = float('inf')\np1, p2 = (0, 0)\nwhile p1 < len(i1) and p2 < len(i2):\n distance = min(distance, abs(i1[p1] - i2[p2]))\n i... | <|body_start_0|>
self.word_indices = defaultdict(list)
for i, word in enumerate(words):
self.word_indices[word].append(i)
<|end_body_0|>
<|body_start_1|>
i1 = self.word_indices[word1]
i2 = self.word_indices[word2]
distance = float('inf')
p1, p2 = (0, 0)
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_026000 | 1,743 | no_license | [
{
"docstring": "initialize your data structure here. :type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": "Adds a word into the data structure. :type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortes... | 2 | null | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): initialize your data structure here. :type words: List[str]
- def shortest(self, word1, word2): Adds a word into the data structure. :type word... | 05e0beff0047f0ad399d0b46d625bb8d3459814e | <|skeleton|>
class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
"""Adds a word into the data structure. :type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
"""initialize your data structure here. :type words: List[str]"""
self.word_indices = defaultdict(list)
for i, word in enumerate(words):
self.word_indices[word].append(i)
def shortest(self, word1, word2):
"""Adds a word ... | the_stack_v2_python_sparse | python_1_to_1000/244_Shortest_Word_Distance_II.py | jakehoare/leetcode | train | 58 | |
ff706d7f94b3053e70c5b4f9fc5e189f073a1099 | [
"try:\n cql = 'Match p=(:Teacher{id:%s})-[r:学术合作]-(:Teacher) return NODES(p) as nodes, RELATIONSHIPS(p) as relationship' % teacher_id\n back = NeoOperator.graph.run(cql).data()\n return back\nexcept Exception as e:\n print(e)",
"try:\n cql = 'Match p=(:Teacher{id:%s}) return NODES(p) as nodes, RELA... | <|body_start_0|>
try:
cql = 'Match p=(:Teacher{id:%s})-[r:学术合作]-(:Teacher) return NODES(p) as nodes, RELATIONSHIPS(p) as relationship' % teacher_id
back = NeoOperator.graph.run(cql).data()
return back
except Exception as e:
print(e)
<|end_body_0|>
<|body_... | NeoOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NeoOperator:
def get_ego_net(cls, teacher_id):
"""根据教师id获取个人中心网络 :param teacher_id: :return: [ { "nodes": [Node tyep element, Node type element2], "relationship": [] },... ]"""
<|body_0|>
def get_this_teacher_net(cls, teacher_id):
"""根据教师的id获取与其团队中的其他教师id :return:"""... | stack_v2_sparse_classes_36k_train_026001 | 12,353 | no_license | [
{
"docstring": "根据教师id获取个人中心网络 :param teacher_id: :return: [ { \"nodes\": [Node tyep element, Node type element2], \"relationship\": [] },... ]",
"name": "get_ego_net",
"signature": "def get_ego_net(cls, teacher_id)"
},
{
"docstring": "根据教师的id获取与其团队中的其他教师id :return:",
"name": "get_this_teach... | 4 | stack_v2_sparse_classes_30k_train_005584 | Implement the Python class `NeoOperator` described below.
Class description:
Implement the NeoOperator class.
Method signatures and docstrings:
- def get_ego_net(cls, teacher_id): 根据教师id获取个人中心网络 :param teacher_id: :return: [ { "nodes": [Node tyep element, Node type element2], "relationship": [] },... ]
- def get_this... | Implement the Python class `NeoOperator` described below.
Class description:
Implement the NeoOperator class.
Method signatures and docstrings:
- def get_ego_net(cls, teacher_id): 根据教师id获取个人中心网络 :param teacher_id: :return: [ { "nodes": [Node tyep element, Node type element2], "relationship": [] },... ]
- def get_this... | 5965015345c1878fbd6860a3cdca344fb088aa1b | <|skeleton|>
class NeoOperator:
def get_ego_net(cls, teacher_id):
"""根据教师id获取个人中心网络 :param teacher_id: :return: [ { "nodes": [Node tyep element, Node type element2], "relationship": [] },... ]"""
<|body_0|>
def get_this_teacher_net(cls, teacher_id):
"""根据教师的id获取与其团队中的其他教师id :return:"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NeoOperator:
def get_ego_net(cls, teacher_id):
"""根据教师id获取个人中心网络 :param teacher_id: :return: [ { "nodes": [Node tyep element, Node type element2], "relationship": [] },... ]"""
try:
cql = 'Match p=(:Teacher{id:%s})-[r:学术合作]-(:Teacher) return NODES(p) as nodes, RELATIONSHIPS(p) as r... | the_stack_v2_python_sparse | web/utils/Ego_net.py | zhangshuo1996/school_profile | train | 0 | |
4cdcd2254e219ca22f778cf162069424188aa01a | [
"super().__init__()\nself.x_dim = x_dim\nself.key_dim = key_dim\nself.value_dim = value_dim\nself.attention_type = attention_type\nif key_hidden_dims is None:\n self.key_hidden_dims = [self.key_dim]\nelse:\n self.key_hidden_dims = key_hidden_dims\nself.key_transform = VanillaNN(self.x_dim, self.key_dim, hidde... | <|body_start_0|>
super().__init__()
self.x_dim = x_dim
self.key_dim = key_dim
self.value_dim = value_dim
self.attention_type = attention_type
if key_hidden_dims is None:
self.key_hidden_dims = [self.key_dim]
else:
self.key_hidden_dims = key... | CrossAttentionNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossAttentionNN:
def __init__(self, x_dim, key_dim, value_dim, attention_type, key_hidden_dims=None):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linea... | stack_v2_sparse_classes_36k_train_026002 | 16,175 | no_license | [
{
"docstring": ":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linearity: Non-linear activation function to apply after each linear transformation, e.g. relu or tanh.",
"name": "... | 2 | stack_v2_sparse_classes_30k_train_006935 | Implement the Python class `CrossAttentionNN` described below.
Class description:
Implement the CrossAttentionNN class.
Method signatures and docstrings:
- def __init__(self, x_dim, key_dim, value_dim, attention_type, key_hidden_dims=None): :param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimen... | Implement the Python class `CrossAttentionNN` described below.
Class description:
Implement the CrossAttentionNN class.
Method signatures and docstrings:
- def __init__(self, x_dim, key_dim, value_dim, attention_type, key_hidden_dims=None): :param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimen... | de60f831ee082ab2ae232c498cf2755da7c14c27 | <|skeleton|>
class CrossAttentionNN:
def __init__(self, x_dim, key_dim, value_dim, attention_type, key_hidden_dims=None):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossAttentionNN:
def __init__(self, x_dim, key_dim, value_dim, attention_type, key_hidden_dims=None):
""":param in_dim: (int) Dimensionality of the input. :param out_dim: (int) Dimensionality of the output. :param hidden_dims: (list of ints) Architecture of the network. :param non_linearity: Non-line... | the_stack_v2_python_sparse | models/networks/np_networks.py | PenelopeJones/neural_processes | train | 4 | |
6fed6ccadd4f760eb1943f9f67e2976817678c36 | [
"if len(graph_dict) == 1:\n graph = list(graph_dict.values())[0]\n self._normal_node_map = graph.normal_node_map\n self._node_id_map_name = graph.node_id_map_name\n self._const_node_temp_cache = graph.const_node_temp_cache\n self._parameter_node_temp_cache = graph.parameter_node_temp_cache\n self.... | <|body_start_0|>
if len(graph_dict) == 1:
graph = list(graph_dict.values())[0]
self._normal_node_map = graph.normal_node_map
self._node_id_map_name = graph.node_id_map_name
self._const_node_temp_cache = graph.const_node_temp_cache
self._parameter_node_... | The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph. | DebuggerMultiGraph | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
<|body_0|>
def _add_gra... | stack_v2_sparse_classes_36k_train_026003 | 4,342 | permissive | [
{
"docstring": "Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict.",
"name": "add_graph",
"signature": "def add_graph(self, graph_dict)"
},
{
"docstring": "Add graph scope to the inputs and outputs in node",
"name": "_add_graph_scope",
"signat... | 2 | stack_v2_sparse_classes_30k_train_007974 | Implement the Python class `DebuggerMultiGraph` described below.
Class description:
The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph.
Method signatures and docstrings:
- def add_graph(self, graph_dict): Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, gr... | Implement the Python class `DebuggerMultiGraph` described below.
Class description:
The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph.
Method signatures and docstrings:
- def add_graph(self, graph_dict): Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, gr... | a774d893fb2f21dbc3edb5cd89f9e6eec274ebf1 | <|skeleton|>
class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
<|body_0|>
def _add_gra... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DebuggerMultiGraph:
"""The `DebuggerMultiGraph` object provides interfaces to describe a debugger multigraph."""
def add_graph(self, graph_dict):
"""Add graphs to DebuggerMultiGraph. Args: graph_dict (dict): The <graph_name, graph_object> dict."""
if len(graph_dict) == 1:
grap... | the_stack_v2_python_sparse | mindinsight/debugger/stream_cache/debugger_multigraph.py | mindspore-ai/mindinsight | train | 224 |
d58c2ceeae1a93b620158b02b44ec9ddfbee8ee1 | [
"self.simcoal_dir = simcoal_dir\nself.os_name = os.name\ndir_contents = os.listdir(self.simcoal_dir)\nself.bin_name = 'simcoal2'\nif self.bin_name not in dir_contents:\n dir_contents = [x.lower() for x in dir_contents]\nif self.bin_name not in dir_contents:\n self.bin_name += '.exe'\nif self.bin_name not in d... | <|body_start_0|>
self.simcoal_dir = simcoal_dir
self.os_name = os.name
dir_contents = os.listdir(self.simcoal_dir)
self.bin_name = 'simcoal2'
if self.bin_name not in dir_contents:
dir_contents = [x.lower() for x in dir_contents]
if self.bin_name not in dir_con... | SimCoalController | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimCoalController:
def __init__(self, simcoal_dir):
"""Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence and executability of binaries."""
<|body_0|>
def run_simcoal(self, par_file, num_sims, ploydi='... | stack_v2_sparse_classes_36k_train_026004 | 11,968 | permissive | [
{
"docstring": "Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence and executability of binaries.",
"name": "__init__",
"signature": "def __init__(self, simcoal_dir)"
},
{
"docstring": "Executes SimCoal.",
"name": "run... | 2 | stack_v2_sparse_classes_30k_train_007893 | Implement the Python class `SimCoalController` described below.
Class description:
Implement the SimCoalController class.
Method signatures and docstrings:
- def __init__(self, simcoal_dir): Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence an... | Implement the Python class `SimCoalController` described below.
Class description:
Implement the SimCoalController class.
Method signatures and docstrings:
- def __init__(self, simcoal_dir): Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence an... | 2632aa3484ef64c9539c4885026b705b737f6d1e | <|skeleton|>
class SimCoalController:
def __init__(self, simcoal_dir):
"""Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence and executability of binaries."""
<|body_0|>
def run_simcoal(self, par_file, num_sims, ploydi='... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimCoalController:
def __init__(self, simcoal_dir):
"""Initializes the controller. (DEPRECATED) simcoal_dir is the directory where simcoal is. The initializer checks for existence and executability of binaries."""
self.simcoal_dir = simcoal_dir
self.os_name = os.name
dir_conten... | the_stack_v2_python_sparse | resources/usr/local/lib/python2.7/dist-packages/Bio/PopGen/SimCoal/Controller.py | edawson/parliament2 | train | 0 | |
b02ae622b23c37bc236e4dbf86e6838c7678f4fa | [
"base_rest = BaseRestApi()\nusers = users if isinstance(users, list) else [users]\nresult = base_rest.request('POST', RC.REST_OBJ_USER, RC.USER_CREATE_LIST, params=users)\nreturn result['status_code']",
"base_rest = BaseRestApi()\nresult = base_rest.request('GET', RC.REST_OBJ_USER, user_name)\nif expected_error:\... | <|body_start_0|>
base_rest = BaseRestApi()
users = users if isinstance(users, list) else [users]
result = base_rest.request('POST', RC.REST_OBJ_USER, RC.USER_CREATE_LIST, params=users)
return result['status_code']
<|end_body_0|>
<|body_start_1|>
base_rest = BaseRestApi()
... | Provide Rest API for User rest object | UserRest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
<|body_0|>
def get(user_name, expected_error=False):
"""Get user entry :param... | stack_v2_sparse_classes_36k_train_026005 | 1,981 | no_license | [
{
"docstring": "Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int",
"name": "create",
"signature": "def create(users)"
},
{
"docstring": "Get user entry :param user_name: user name :type user_name: str :param expected_error: :type expected... | 4 | stack_v2_sparse_classes_30k_train_017716 | Implement the Python class `UserRest` described below.
Class description:
Provide Rest API for User rest object
Method signatures and docstrings:
- def create(users): Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int
- def get(user_name, expected_error=False): ... | Implement the Python class `UserRest` described below.
Class description:
Provide Rest API for User rest object
Method signatures and docstrings:
- def create(users): Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int
- def get(user_name, expected_error=False): ... | 341cad07bf93fdbb8b353ce98315051f773202f5 | <|skeleton|>
class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
<|body_0|>
def get(user_name, expected_error=False):
"""Get user entry :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserRest:
"""Provide Rest API for User rest object"""
def create(users):
"""Create user or users :param users: list of users bodies :type users: list :returns: status code :type: int"""
base_rest = BaseRestApi()
users = users if isinstance(users, list) else [users]
result ... | the_stack_v2_python_sparse | modules/rest_functions/user_rest.py | Pir-4/CloudmoreTask | train | 0 |
2ff53b3b2bdd3c5fa1d0df2fdc27b87d11a23f7b | [
"self.pos_from = p_pos_from\nself.rename_tuple_list = []\nself.was_renamed_tuple_list = []",
"local_folder_files = os.listdir('.')\nsorted(local_folder_files)\nfor filename_from in local_folder_files:\n ext = ''\n if filename_from.find('.') > -1:\n ext = filename_from.split('.')[-1]\n tam_ext_with... | <|body_start_0|>
self.pos_from = p_pos_from
self.rename_tuple_list = []
self.was_renamed_tuple_list = []
<|end_body_0|>
<|body_start_1|>
local_folder_files = os.listdir('.')
sorted(local_folder_files)
for filename_from in local_folder_files:
ext = ''
... | Renamer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Renamer:
def __init__(self, p_pos_from=None):
""":param p_pos_from:"""
<|body_0|>
def gather_renamepairs_ifany(self):
""":return:"""
<|body_1|>
def confirm_renames(self):
""":return:"""
<|body_2|>
def rename_pairs(self):
""":... | stack_v2_sparse_classes_36k_train_026006 | 2,449 | no_license | [
{
"docstring": ":param p_pos_from:",
"name": "__init__",
"signature": "def __init__(self, p_pos_from=None)"
},
{
"docstring": ":return:",
"name": "gather_renamepairs_ifany",
"signature": "def gather_renamepairs_ifany(self)"
},
{
"docstring": ":return:",
"name": "confirm_renam... | 6 | null | Implement the Python class `Renamer` described below.
Class description:
Implement the Renamer class.
Method signatures and docstrings:
- def __init__(self, p_pos_from=None): :param p_pos_from:
- def gather_renamepairs_ifany(self): :return:
- def confirm_renames(self): :return:
- def rename_pairs(self): :param self: ... | Implement the Python class `Renamer` described below.
Class description:
Implement the Renamer class.
Method signatures and docstrings:
- def __init__(self, p_pos_from=None): :param p_pos_from:
- def gather_renamepairs_ifany(self): :return:
- def confirm_renames(self): :return:
- def rename_pairs(self): :param self: ... | b4c5642c8d5843846d529630f8d93a7103676539 | <|skeleton|>
class Renamer:
def __init__(self, p_pos_from=None):
""":param p_pos_from:"""
<|body_0|>
def gather_renamepairs_ifany(self):
""":return:"""
<|body_1|>
def confirm_renames(self):
""":return:"""
<|body_2|>
def rename_pairs(self):
""":... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Renamer:
def __init__(self, p_pos_from=None):
""":param p_pos_from:"""
self.pos_from = p_pos_from
self.rename_tuple_list = []
self.was_renamed_tuple_list = []
def gather_renamepairs_ifany(self):
""":return:"""
local_folder_files = os.listdir('.')
so... | the_stack_v2_python_sparse | renameCleanEndingAtPos.py | alclass/bin | train | 0 | |
df39886a838e2822e7513f9d3f1156a602380029 | [
"self.eff_file = r.TFile.Open(eff_file)\nself.effs = get_effs(self.eff_file, eff_type)\nself.eta_binning = get_eta_binning(self.effs)",
"eta_bin = self._find_eta_bin(np.abs(eta))\nif eta_bin is not None:\n return self.effs[eta_bin].Eval(pt)\nreturn -1",
"for i in xrange(len(self.eta_binning) - 1):\n if et... | <|body_start_0|>
self.eff_file = r.TFile.Open(eff_file)
self.effs = get_effs(self.eff_file, eff_type)
self.eta_binning = get_eta_binning(self.effs)
<|end_body_0|>
<|body_start_1|>
eta_bin = self._find_eta_bin(np.abs(eta))
if eta_bin is not None:
return self.effs[eta_... | Class providing interface to easily obtain single muon and photon efficiencies | EfficiencyProvider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EfficiencyProvider:
"""Class providing interface to easily obtain single muon and photon efficiencies"""
def __init__(self, eff_file, eff_type):
"""Args: eff_file (str): name of the ROOT file where the efficiencies are stored eff_type (str): either 'photon' or 'muon' depending on whi... | stack_v2_sparse_classes_36k_train_026007 | 11,087 | no_license | [
{
"docstring": "Args: eff_file (str): name of the ROOT file where the efficiencies are stored eff_type (str): either 'photon' or 'muon' depending on which efficiencies are desired",
"name": "__init__",
"signature": "def __init__(self, eff_file, eff_type)"
},
{
"docstring": "Evaluate the efficien... | 3 | null | Implement the Python class `EfficiencyProvider` described below.
Class description:
Class providing interface to easily obtain single muon and photon efficiencies
Method signatures and docstrings:
- def __init__(self, eff_file, eff_type): Args: eff_file (str): name of the ROOT file where the efficiencies are stored e... | Implement the Python class `EfficiencyProvider` described below.
Class description:
Class providing interface to easily obtain single muon and photon efficiencies
Method signatures and docstrings:
- def __init__(self, eff_file, eff_type): Args: eff_file (str): name of the ROOT file where the efficiencies are stored e... | 9f3ac9dd9ce72a824660bde0224fead511259225 | <|skeleton|>
class EfficiencyProvider:
"""Class providing interface to easily obtain single muon and photon efficiencies"""
def __init__(self, eff_file, eff_type):
"""Args: eff_file (str): name of the ROOT file where the efficiencies are stored eff_type (str): either 'photon' or 'muon' depending on whi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EfficiencyProvider:
"""Class providing interface to easily obtain single muon and photon efficiencies"""
def __init__(self, eff_file, eff_type):
"""Args: eff_file (str): name of the ROOT file where the efficiencies are stored eff_type (str): either 'photon' or 'muon' depending on which efficienci... | the_stack_v2_python_sparse | python/utils/EfficiencyProvider.py | tmadlener/chib_chic_polFW | train | 1 |
af7725b18d5e20d2abc76a87d531d538be1095ec | [
"self.name = name\nif name is None:\n self.name = ''.join([str(i) for i in np.random.randint(5)])\nself.incomingRelation = incomingRelation\nself.incomingNodes = incomingNodes\nself.autoFill = autofill\nself.hidden = hidden",
"if self.name not in values:\n if self.autoFill is not None:\n if self.auto... | <|body_start_0|>
self.name = name
if name is None:
self.name = ''.join([str(i) for i in np.random.randint(5)])
self.incomingRelation = incomingRelation
self.incomingNodes = incomingNodes
self.autoFill = autofill
self.hidden = hidden
<|end_body_0|>
<|body_star... | CausalNode | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CausalNode:
def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False):
"""Provide outgoing as a list of nodes. Name must be unique in the network."""
<|body_0|>
def simulate(self, values, rnn=False):
"""Computes own value. As... | stack_v2_sparse_classes_36k_train_026008 | 13,980 | no_license | [
{
"docstring": "Provide outgoing as a list of nodes. Name must be unique in the network.",
"name": "__init__",
"signature": "def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False)"
},
{
"docstring": "Computes own value. Assumes all required variables ... | 2 | stack_v2_sparse_classes_30k_train_003790 | Implement the Python class `CausalNode` described below.
Class description:
Implement the CausalNode class.
Method signatures and docstrings:
- def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False): Provide outgoing as a list of nodes. Name must be unique in the network.
... | Implement the Python class `CausalNode` described below.
Class description:
Implement the CausalNode class.
Method signatures and docstrings:
- def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False): Provide outgoing as a list of nodes. Name must be unique in the network.
... | 2b2ff49a6a6fe60c7e77b45d6c81b21e9b75034d | <|skeleton|>
class CausalNode:
def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False):
"""Provide outgoing as a list of nodes. Name must be unique in the network."""
<|body_0|>
def simulate(self, values, rnn=False):
"""Computes own value. As... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CausalNode:
def __init__(self, name=None, incomingRelation=None, incomingNodes=[], autofill=None, hidden=False):
"""Provide outgoing as a list of nodes. Name must be unique in the network."""
self.name = name
if name is None:
self.name = ''.join([str(i) for i in np.random.r... | the_stack_v2_python_sparse | causal/CausalNode.py | rjbruin/causal-discovery-with-lstm | train | 3 | |
f1bc2066fd2dc359f4e52a32cf3bf3df18e09e5e | [
"if butler is not None:\n self.log.warn('Ignoring butler')\nreturn datakey",
"config_kw = self.extract_config_vals(dict(template_file=None, css_file=None, plot_report_action=None, overwrite=None))\nfull_input = os.path.join(self.config.indir, self.config.teststand)\nwrite_run_report(data, full_input, self.conf... | <|body_start_0|>
if butler is not None:
self.log.warn('Ignoring butler')
return datakey
<|end_body_0|>
<|body_start_1|>
config_kw = self.extract_config_vals(dict(template_file=None, css_file=None, plot_report_action=None, overwrite=None))
full_input = os.path.join(self.confi... | Produce a static html report for one run | ReportRunTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReportRunTask:
"""Produce a static html report for one run"""
def get_data(self, butler, datakey, **kwargs):
"""Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or other id that defines the data to analyze kwargs Used to over... | stack_v2_sparse_classes_36k_train_026009 | 9,532 | permissive | [
{
"docstring": "Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or other id that defines the data to analyze kwargs Used to override default configuration Returns ------- retval : `dict` Dictionary mapping input data by raft, slot and file type",
"... | 2 | stack_v2_sparse_classes_30k_train_014623 | Implement the Python class `ReportRunTask` described below.
Class description:
Produce a static html report for one run
Method signatures and docstrings:
- def get_data(self, butler, datakey, **kwargs): Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or othe... | Implement the Python class `ReportRunTask` described below.
Class description:
Produce a static html report for one run
Method signatures and docstrings:
- def get_data(self, butler, datakey, **kwargs): Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or othe... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class ReportRunTask:
"""Produce a static html report for one run"""
def get_data(self, butler, datakey, **kwargs):
"""Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or other id that defines the data to analyze kwargs Used to over... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ReportRunTask:
"""Produce a static html report for one run"""
def get_data(self, butler, datakey, **kwargs):
"""Function to get the data Parameters ---------- butler : `Butler` The data butler datakey : `str` Run number or other id that defines the data to analyze kwargs Used to override default ... | the_stack_v2_python_sparse | python/lsst/eo_utils/base/report_task.py | lsst-camera-dh/EO-utilities | train | 2 |
c4c99da4678bbc66262b97261134950d3e3dcf38 | [
"self.a_weights = [w[0]]\nfor k in w[1:]:\n self.a_weights.append(self.a_weights[-1] + k)\nprint(self.a_weights)",
"i = random.randrange(self.a_weights[-1]) + 1\nleft = 0\nright = len(self.a_weights) - 1\nwhile left < right:\n mid = (left + right) // 2\n if self.a_weights[mid] == i:\n return mid\n... | <|body_start_0|>
self.a_weights = [w[0]]
for k in w[1:]:
self.a_weights.append(self.a_weights[-1] + k)
print(self.a_weights)
<|end_body_0|>
<|body_start_1|>
i = random.randrange(self.a_weights[-1]) + 1
left = 0
right = len(self.a_weights) - 1
while le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.a_weights = [w[0]]
for k in w[1:]:
self.a_weights.append(self.a_weights... | stack_v2_sparse_classes_36k_train_026010 | 1,521 | no_license | [
{
"docstring": ":type w: List[int]",
"name": "__init__",
"signature": "def __init__(self, w)"
},
{
"docstring": ":rtype: int",
"name": "pickIndex",
"signature": "def pickIndex(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, w): :type w: List[int]
- def pickIndex(self): :rtype: int
<|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|... | 696a25f8597e2a5bc5ab788924418d6423160af1 | <|skeleton|>
class Solution:
def __init__(self, w):
""":type w: List[int]"""
<|body_0|>
def pickIndex(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def __init__(self, w):
""":type w: List[int]"""
self.a_weights = [w[0]]
for k in w[1:]:
self.a_weights.append(self.a_weights[-1] + k)
print(self.a_weights)
def pickIndex(self):
""":rtype: int"""
i = random.randrange(self.a_weights[-1])... | the_stack_v2_python_sparse | p_y/528_random_pick_with_weight.py | tooyoungtoosimplesometimesnaive/probable-octo-potato | train | 0 | |
6175bfb9a5042c5c720e91a0d0b4e19d6160cc37 | [
"LOGGER.info('=' * 72)\nLOGGER.error('RECEIVED AN ERROR.')\nLOGGER.error('Message headers:\\n%s', headers)\nLOGGER.error('Message body:\\n%s', message)",
"LOGGER.info('=' * 72)\nLOGGER.info('Message headers:\\n%s', headers)\nLOGGER.info('Message body:\\n%s', message)"
] | <|body_start_0|>
LOGGER.info('=' * 72)
LOGGER.error('RECEIVED AN ERROR.')
LOGGER.error('Message headers:\n%s', headers)
LOGGER.error('Message body:\n%s', message)
<|end_body_0|>
<|body_start_1|>
LOGGER.info('=' * 72)
LOGGER.info('Message headers:\n%s', headers)
L... | CIListener handler Class | CIListener | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CIListener:
"""CIListener handler Class"""
def on_error(self, headers, message):
"""Handler on error"""
<|body_0|>
def on_message(self, headers, message):
"""Handler on message"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
LOGGER.info('=' * 72... | stack_v2_sparse_classes_36k_train_026011 | 2,537 | no_license | [
{
"docstring": "Handler on error",
"name": "on_error",
"signature": "def on_error(self, headers, message)"
},
{
"docstring": "Handler on message",
"name": "on_message",
"signature": "def on_message(self, headers, message)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015296 | Implement the Python class `CIListener` described below.
Class description:
CIListener handler Class
Method signatures and docstrings:
- def on_error(self, headers, message): Handler on error
- def on_message(self, headers, message): Handler on message | Implement the Python class `CIListener` described below.
Class description:
CIListener handler Class
Method signatures and docstrings:
- def on_error(self, headers, message): Handler on error
- def on_message(self, headers, message): Handler on message
<|skeleton|>
class CIListener:
"""CIListener handler Class""... | aa459e9d77b87fbbcb0552e340785b8caffea6ce | <|skeleton|>
class CIListener:
"""CIListener handler Class"""
def on_error(self, headers, message):
"""Handler on error"""
<|body_0|>
def on_message(self, headers, message):
"""Handler on message"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CIListener:
"""CIListener handler Class"""
def on_error(self, headers, message):
"""Handler on error"""
LOGGER.info('=' * 72)
LOGGER.error('RECEIVED AN ERROR.')
LOGGER.error('Message headers:\n%s', headers)
LOGGER.error('Message body:\n%s', message)
def on_mes... | the_stack_v2_python_sparse | libvirt-ci/libvirt_ci/commands/subscribe.py | weikunzz/test_cases | train | 0 |
3a7fba60888ce0bb0b58b355a8f7a27d4794115a | [
"mx = -float('inf')\nmn = float('inf')\nstack = []\nfor i, n in enumerate(nums):\n x = -float('inf')\n y = None\n while stack and stack[-1][0] > n:\n m, j = stack.pop()\n if m > x:\n x = m\n y = j\n mn = min(mn, j)\n mx = max(mx, i)\n stack.append((n, i)... | <|body_start_0|>
mx = -float('inf')
mn = float('inf')
stack = []
for i, n in enumerate(nums):
x = -float('inf')
y = None
while stack and stack[-1][0] > n:
m, j = stack.pop()
if m > x:
x = m
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""12/15/2020 16:17"""
<|body_0|>
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""12/15/2020 16:52"""
<|body_1|>
def findUnsortedSubarray(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_36k_train_026012 | 3,322 | no_license | [
{
"docstring": "12/15/2020 16:17",
"name": "findUnsortedSubarray",
"signature": "def findUnsortedSubarray(self, nums: List[int]) -> int"
},
{
"docstring": "12/15/2020 16:52",
"name": "findUnsortedSubarray",
"signature": "def findUnsortedSubarray(self, nums: List[int]) -> int"
},
{
... | 3 | stack_v2_sparse_classes_30k_train_017981 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: 12/15/2020 16:17
- def findUnsortedSubarray(self, nums: List[int]) -> int: 12/15/2020 16:52
- def findUnsortedSubarray(sel... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray(self, nums: List[int]) -> int: 12/15/2020 16:17
- def findUnsortedSubarray(self, nums: List[int]) -> int: 12/15/2020 16:52
- def findUnsortedSubarray(sel... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""12/15/2020 16:17"""
<|body_0|>
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""12/15/2020 16:52"""
<|body_1|>
def findUnsortedSubarray(self, nums: List[int]) -> int:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
"""12/15/2020 16:17"""
mx = -float('inf')
mn = float('inf')
stack = []
for i, n in enumerate(nums):
x = -float('inf')
y = None
while stack and stack[-1][0] > n:
... | the_stack_v2_python_sparse | leetcode/solved/581_Shortest_Unsorted_Continuous_Subarray/solution.py | sungminoh/algorithms | train | 0 | |
f8ab6dcf4a39eff0f4c7b2efc0bc778cc6549fcd | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"s_expanded = tf.expand_dims(input=s_prev, axis=1)\ninputs = self.U(s_expanded)\nhidden = self.W(hidden_states)\nscore = self.V(tf.nn.tanh(inputs + hidden))\nattention_weights = t... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
s_expanded = tf.expand_dims(input=s_prev, axis=1)
inputs = self.U(s_expanded)
hidden ... | Class to encode for machine translation: | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Class to encode for machine translation:"""
def __init__(self, units):
"""Class constructor :param units: an integer representing the number of hidden units in the alignment model"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This func... | stack_v2_sparse_classes_36k_train_026013 | 1,654 | no_license | [
{
"docstring": "Class constructor :param units: an integer representing the number of hidden units in the alignment model",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "This function performs the embedding :param s_prev: a tensor of shape (batch, units) contain... | 2 | stack_v2_sparse_classes_30k_val_000365 | Implement the Python class `SelfAttention` described below.
Class description:
Class to encode for machine translation:
Method signatures and docstrings:
- def __init__(self, units): Class constructor :param units: an integer representing the number of hidden units in the alignment model
- def call(self, s_prev, hidd... | Implement the Python class `SelfAttention` described below.
Class description:
Class to encode for machine translation:
Method signatures and docstrings:
- def __init__(self, units): Class constructor :param units: an integer representing the number of hidden units in the alignment model
- def call(self, s_prev, hidd... | 856ee36006c2ff656877d592c2ddb7c941d63780 | <|skeleton|>
class SelfAttention:
"""Class to encode for machine translation:"""
def __init__(self, units):
"""Class constructor :param units: an integer representing the number of hidden units in the alignment model"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""This func... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Class to encode for machine translation:"""
def __init__(self, units):
"""Class constructor :param units: an integer representing the number of hidden units in the alignment model"""
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.ker... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | garimasinghgryffindor/holbertonschool-machine_learning | train | 0 |
bd4e9bd5fa99ae3f31eeb99e60615c067f8daf18 | [
"def dt_conv(dt):\n return pd.datetime.strptime(dt, self._dt_fmt)\ndf = pd.read_csv(agt_file, sep=self._sep, converters={0: dt_conv}, names=['timestamp'] + list(self._columns), nrows=nr_lines)\ndf.set_index('timestamp', inplace=True)\nself._current_line += nr_lines\nreturn df",
"line = agt_file.readline().rstr... | <|body_start_0|>
def dt_conv(dt):
return pd.datetime.strptime(dt, self._dt_fmt)
df = pd.read_csv(agt_file, sep=self._sep, converters={0: dt_conv}, names=['timestamp'] + list(self._columns), nrows=nr_lines)
df.set_index('timestamp', inplace=True)
self._current_line += nr_lines... | Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored. | AgtPandasParser | [
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
<|body_0|>
def _par... | stack_v2_sparse_classes_36k_train_026014 | 6,235 | permissive | [
{
"docstring": "read data using pandas methods",
"name": "_read_data",
"signature": "def _read_data(self, agt_file, nr_lines)"
},
{
"docstring": "parse footer, i.e., file content after data.",
"name": "_parse_footer",
"signature": "def _parse_footer(self, agt_file)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009874 | Implement the Python class `AgtPandasParser` described below.
Class description:
Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored.
Method signatures and docstrings:
- def _read_data(self, agt_file, nr_lines): read data... | Implement the Python class `AgtPandasParser` described below.
Class description:
Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored.
Method signatures and docstrings:
- def _read_data(self, agt_file, nr_lines): read data... | e748466a2af9f3388a8b0ed091aa061dbfc752d6 | <|skeleton|>
class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
<|body_0|>
def _par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AgtPandasParser:
"""Parser for agt files that contain sensor data, i.e., timestamps, temerature, and pressure. These files also contain meta-inforamtion that is ignored."""
def _read_data(self, agt_file, nr_lines):
"""read data using pandas methods"""
def dt_conv(dt):
return p... | the_stack_v2_python_sparse | Python/DataFormats/agt_parser.py | gjbex/training-material | train | 130 |
558d56f7b12cc69848044feba82b7a4fb63f1586 | [
"self.cube = set_up_variable_cube(np.ones((5, 5), dtype=np.float32), spatial_grid='equalarea')\nself.cube.data[2, 2] = 0\nself.large_cube = set_up_variable_cube(np.ones((10, 10), dtype=np.float32), spatial_grid='equalarea')\nself.large_cube.coord(axis='y').points = np.linspace(0, 900000, 10, dtype=np.float32)\nself... | <|body_start_0|>
self.cube = set_up_variable_cube(np.ones((5, 5), dtype=np.float32), spatial_grid='equalarea')
self.cube.data[2, 2] = 0
self.large_cube = set_up_variable_cube(np.ones((10, 10), dtype=np.float32), spatial_grid='equalarea')
self.large_cube.coord(axis='y').points = np.linspa... | Test a halo is removed from the cube data. | Test_remove_halo_from_cube | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_remove_halo_from_cube:
"""Test a halo is removed from the cube data."""
def setUp(self):
"""Set up a cube."""
<|body_0|>
def test_basic(self):
"""Test that removing a halo of points from the data on a cube has worked as intended."""
<|body_1|>
d... | stack_v2_sparse_classes_36k_train_026015 | 25,212 | permissive | [
{
"docstring": "Set up a cube.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test that removing a halo of points from the data on a cube has worked as intended.",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test that removin... | 4 | null | Implement the Python class `Test_remove_halo_from_cube` described below.
Class description:
Test a halo is removed from the cube data.
Method signatures and docstrings:
- def setUp(self): Set up a cube.
- def test_basic(self): Test that removing a halo of points from the data on a cube has worked as intended.
- def t... | Implement the Python class `Test_remove_halo_from_cube` described below.
Class description:
Test a halo is removed from the cube data.
Method signatures and docstrings:
- def setUp(self): Set up a cube.
- def test_basic(self): Test that removing a halo of points from the data on a cube has worked as intended.
- def t... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_remove_halo_from_cube:
"""Test a halo is removed from the cube data."""
def setUp(self):
"""Set up a cube."""
<|body_0|>
def test_basic(self):
"""Test that removing a halo of points from the data on a cube has worked as intended."""
<|body_1|>
d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_remove_halo_from_cube:
"""Test a halo is removed from the cube data."""
def setUp(self):
"""Set up a cube."""
self.cube = set_up_variable_cube(np.ones((5, 5), dtype=np.float32), spatial_grid='equalarea')
self.cube.data[2, 2] = 0
self.large_cube = set_up_variable_cube(... | the_stack_v2_python_sparse | improver_tests/utilities/test_pad_spatial.py | metoppv/improver | train | 101 |
4054cc7bb6b26dd8ee148fdd4f6089390f14e197 | [
"self.id = lot_id\nself.city = city\nself.streets = []\nself.parcels = []\nself.sides_of_street = []\nself.house_numbers = []\nself.building = None\nself.landmark = None\nself.positions_in_parcel = []\nself.neighboring_lots = set()\nself.house_number = None\nself.address = None\nself.street_address_is_on = None\nse... | <|body_start_0|>
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self.house_numbers = []
self.building = None
self.landmark = None
self.positions_in_parcel = []
self.neighboring_lots = set()
... | A lot on a block in a city, upon which buildings and houses get erected. | Lot | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_026016 | 29,613 | no_license | [
{
"docstring": "Initialize a Lot object.",
"name": "__init__",
"signature": "def __init__(self, lot_id, city)"
},
{
"docstring": "Return the number of people living/working on the lot.",
"name": "population",
"signature": "def population(self)"
},
{
"docstring": "Attribute to thi... | 5 | stack_v2_sparse_classes_30k_train_016316 | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | Implement the Python class `Lot` described below.
Class description:
A lot on a block in a city, upon which buildings and houses get erected.
Method signatures and docstrings:
- def __init__(self, lot_id, city): Initialize a Lot object.
- def population(self): Return the number of people living/working on the lot.
- ... | 78a9df3ff66d4956f817397c82be0b4e4176e73d | <|skeleton|>
class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
<|body_0|>
def population(self):
"""Return the number of people living/working on the lot."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lot:
"""A lot on a block in a city, upon which buildings and houses get erected."""
def __init__(self, lot_id, city):
"""Initialize a Lot object."""
self.id = lot_id
self.city = city
self.streets = []
self.parcels = []
self.sides_of_street = []
self... | the_stack_v2_python_sparse | places/city_planning.py | hanok2/national_pastime | train | 1 |
472df18d637aa0934f1c429b563458c569cfe601 | [
"if nums is None:\n return 0\nself.ret = 0\n\ndef maxCoins_bt(nums, coins):\n n = len(nums)\n if n == 1:\n self.ret = max(nums[-1] + coins, self.ret)\n return\n nums.insert(0, 1)\n nums.append(1)\n for i in range(1, n):\n cur = nums[i]\n tmp = nums[i - 1] * cur * nums[i... | <|body_start_0|>
if nums is None:
return 0
self.ret = 0
def maxCoins_bt(nums, coins):
n = len(nums)
if n == 1:
self.ret = max(nums[-1] + coins, self.ret)
return
nums.insert(0, 1)
nums.append(1)
... | 有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 示例: 输入: [3,1,5,8] 输出... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。 0 ≤ n ≤ 500, 0 ... | stack_v2_sparse_classes_36k_train_026017 | 3,377 | permissive | [
{
"docstring": "回溯解法, 不适合递归超过12次",
"name": "maxCoins_slow",
"signature": "def maxCoins_slow(self, nums) -> int"
},
{
"docstring": "思路: 每次选定一个气球最后点爆, 选到只剩1个气球的值是一定的, 回到剩2个气球的状态, 可以通过只剩1个气球的状态推出来 状态转移方程: 选定一个气球, 最后点爆. dp[i][j]: 点爆从i到j的气球, 可以得到的最大值 1. 区间慢慢增大的过程中, 我们有很多的区间[i, j], 为了求这些区间内的最大值 设k在区间 ... | 2 | stack_v2_sparse_classes_30k_train_004189 | Implement the Python class `Solution` described below.
Class description:
有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = ... | Implement the Python class `Solution` described below.
Class description:
有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = ... | 9f49766a2b375a6c65f7bfa96df513875ddd772d | <|skeleton|>
class Solution:
"""有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。 0 ≤ n ≤ 500, 0 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""有 n 个气球,编号为0 到 n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。 现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。 注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。 求所能获得硬币的最大数量。 说明: 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 1... | the_stack_v2_python_sparse | Leetcode/312.maxCoins.py | Song2017/Leetcode_python | train | 1 |
5ef2b90e20860f7ff913230141a60546a2f1fcb9 | [
"html_template = get_template('email_verification_en.html')\ntext_template = get_template('email_verification_en.txt')\nverification_url = SMTPService._generate_email_verification_url(to_address, username)\nhtml_template = html_template.replace('[USERNAME]', username)\nhtml_template = html_template.replace('[VEFIFI... | <|body_start_0|>
html_template = get_template('email_verification_en.html')
text_template = get_template('email_verification_en.txt')
verification_url = SMTPService._generate_email_verification_url(to_address, username)
html_template = html_template.replace('[USERNAME]', username)
... | SMTPService | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMTPService:
def send_verification_email(to_address: str, username: str):
"""Sends a verification email with a unique token so we can verify user owns this email address"""
<|body_0|>
def send_email_alert(to_address: str, username: str, message: MessageDTO=None):
"""... | stack_v2_sparse_classes_36k_train_026018 | 4,777 | permissive | [
{
"docstring": "Sends a verification email with a unique token so we can verify user owns this email address",
"name": "send_verification_email",
"signature": "def send_verification_email(to_address: str, username: str)"
},
{
"docstring": "Send an email to user to alert them they have a new mess... | 5 | stack_v2_sparse_classes_30k_train_001040 | Implement the Python class `SMTPService` described below.
Class description:
Implement the SMTPService class.
Method signatures and docstrings:
- def send_verification_email(to_address: str, username: str): Sends a verification email with a unique token so we can verify user owns this email address
- def send_email_a... | Implement the Python class `SMTPService` described below.
Class description:
Implement the SMTPService class.
Method signatures and docstrings:
- def send_verification_email(to_address: str, username: str): Sends a verification email with a unique token so we can verify user owns this email address
- def send_email_a... | 6c567ff02c316bc1f1429c11c60dc72f450d1c57 | <|skeleton|>
class SMTPService:
def send_verification_email(to_address: str, username: str):
"""Sends a verification email with a unique token so we can verify user owns this email address"""
<|body_0|>
def send_email_alert(to_address: str, username: str, message: MessageDTO=None):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMTPService:
def send_verification_email(to_address: str, username: str):
"""Sends a verification email with a unique token so we can verify user owns this email address"""
html_template = get_template('email_verification_en.html')
text_template = get_template('email_verification_en.tx... | the_stack_v2_python_sparse | server/services/messaging/smtp_service.py | KaartGroup/tasking-manager | train | 2 | |
cc5e512c40eeb3d7ecfa986f9e8245d9a2c05f43 | [
"wt_resultfile = os.path.join(os.path.split(__file__)[0], 'defects_driver_results_tc.xml')\nwt_defectsdir = result_dir\nwith open(result_dir + '/' + 'myfile.log', 'w'):\n pass\nwt_logsdir = os.path.join(result_dir, 'myfile.log')\nwt_testcase_filepath = os.path.join(os.path.split(__file__)[0], 'defects_driver_tc.... | <|body_start_0|>
wt_resultfile = os.path.join(os.path.split(__file__)[0], 'defects_driver_results_tc.xml')
wt_defectsdir = result_dir
with open(result_dir + '/' + 'myfile.log', 'w'):
pass
wt_logsdir = os.path.join(result_dir, 'myfile.log')
wt_testcase_filepath = os.pa... | Defects Driver Class | test_DefectsDriver | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class test_DefectsDriver:
"""Defects Driver Class"""
def test_get_defect_json_list(self):
"""Gets the list of defect json files for the testcase execution"""
<|body_0|>
def test_create_failing_kw_json_without_keywords(self):
"""Create a json file each failing keyword""... | stack_v2_sparse_classes_36k_train_026019 | 4,423 | permissive | [
{
"docstring": "Gets the list of defect json files for the testcase execution",
"name": "test_get_defect_json_list",
"signature": "def test_get_defect_json_list(self)"
},
{
"docstring": "Create a json file each failing keyword",
"name": "test_create_failing_kw_json_without_keywords",
"si... | 4 | stack_v2_sparse_classes_30k_train_016535 | Implement the Python class `test_DefectsDriver` described below.
Class description:
Defects Driver Class
Method signatures and docstrings:
- def test_get_defect_json_list(self): Gets the list of defect json files for the testcase execution
- def test_create_failing_kw_json_without_keywords(self): Create a json file e... | Implement the Python class `test_DefectsDriver` described below.
Class description:
Defects Driver Class
Method signatures and docstrings:
- def test_get_defect_json_list(self): Gets the list of defect json files for the testcase execution
- def test_create_failing_kw_json_without_keywords(self): Create a json file e... | fc268c610c429f5a60e5627c2405aa66036487dd | <|skeleton|>
class test_DefectsDriver:
"""Defects Driver Class"""
def test_get_defect_json_list(self):
"""Gets the list of defect json files for the testcase execution"""
<|body_0|>
def test_create_failing_kw_json_without_keywords(self):
"""Create a json file each failing keyword""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class test_DefectsDriver:
"""Defects Driver Class"""
def test_get_defect_json_list(self):
"""Gets the list of defect json files for the testcase execution"""
wt_resultfile = os.path.join(os.path.split(__file__)[0], 'defects_driver_results_tc.xml')
wt_defectsdir = result_dir
with... | the_stack_v2_python_sparse | warrior/test_WarriorCore/test_defects_driver.py | shubhendra-tomar/warriorframework_py3 | train | 0 |
3f3c17ba25a83caae2dc659408a3756225357d8b | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file | ProcessorServicer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessorServicer:
"""Missing associated documentation comment in .proto file"""
def Ping(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def Follow(self, request, context):
"""Missing associated documentation com... | stack_v2_sparse_classes_36k_train_026020 | 9,531 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "Ping",
"signature": "def Ping(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file",
"name": "Follow",
"signature": "def Follow(self, request, context)"
},
... | 6 | stack_v2_sparse_classes_30k_test_000589 | Implement the Python class `ProcessorServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def Ping(self, request, context): Missing associated documentation comment in .proto file
- def Follow(self, request, context): Missing associa... | Implement the Python class `ProcessorServicer` described below.
Class description:
Missing associated documentation comment in .proto file
Method signatures and docstrings:
- def Ping(self, request, context): Missing associated documentation comment in .proto file
- def Follow(self, request, context): Missing associa... | 039a42aa9d1537e7beb4071d86bea7a42253d8b3 | <|skeleton|>
class ProcessorServicer:
"""Missing associated documentation comment in .proto file"""
def Ping(self, request, context):
"""Missing associated documentation comment in .proto file"""
<|body_0|>
def Follow(self, request, context):
"""Missing associated documentation com... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessorServicer:
"""Missing associated documentation comment in .proto file"""
def Ping(self, request, context):
"""Missing associated documentation comment in .proto file"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
r... | the_stack_v2_python_sparse | eventsourcing-master/eventsourcing/system/grpc/processor_pb2_grpc.py | menhswu/djangoapps | train | 0 |
00f9e85aafb17690211fd1d756a8fb0bf0aeeec0 | [
"status = ErrorCode.SUCCESS\ntry:\n sms_options = QueryHelper.get_sms_option(self.current_user.uid, self.db)\n self.write_ret(status, dict_=dict(sms_options=sms_options))\nexcept Exception as e:\n logging.exception('[UWEB] uid:%s tid:%s get SMS Options failed. Exception: %s', e.args)\n status = ErrorCod... | <|body_start_0|>
status = ErrorCode.SUCCESS
try:
sms_options = QueryHelper.get_sms_option(self.current_user.uid, self.db)
self.write_ret(status, dict_=dict(sms_options=sms_options))
except Exception as e:
logging.exception('[UWEB] uid:%s tid:%s get SMS Options... | SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send | SMSOptionHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SMSOptionHandler:
"""SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send"""
def get(self):
"""Display smsoption of current user."""
<|body_0|>
def put(self):
"""Modify smsoptions for current user."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k_train_026021 | 6,583 | no_license | [
{
"docstring": "Display smsoption of current user.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Modify smsoptions for current user.",
"name": "put",
"signature": "def put(self)"
}
] | 2 | null | Implement the Python class `SMSOptionHandler` described below.
Class description:
SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send
Method signatures and docstrings:
- def get(self): Display smsoption of current user.
- def put(self): Modify smsoptions for current user. | Implement the Python class `SMSOptionHandler` described below.
Class description:
SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send
Method signatures and docstrings:
- def get(self): Display smsoption of current user.
- def put(self): Modify smsoptions for current user.
<|skeleton... | 3b095a325581b1fc48497c234f0ad55e928586a1 | <|skeleton|>
class SMSOptionHandler:
"""SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send"""
def get(self):
"""Display smsoption of current user."""
<|body_0|>
def put(self):
"""Modify smsoptions for current user."""
<|body_1|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SMSOptionHandler:
"""SMSOption: login/powerlow/poweroff/illegalmove/sos/heartbeat_lost 1: send 0: not send"""
def get(self):
"""Display smsoption of current user."""
status = ErrorCode.SUCCESS
try:
sms_options = QueryHelper.get_sms_option(self.current_user.uid, self.db... | the_stack_v2_python_sparse | apps/uweb/handlers/smsoption.py | jcsy521/ydws | train | 0 |
b025caf8d1ccc701988cbe1aa7446fb2de2f2ffc | [
"if extra_vars:\n kwargs['extra_vars'] = parser.process_extra_vars(extra_vars, force_json=False)\nif not kwargs.get('job_type', False):\n kwargs['job_type'] = 'run'\nreturn super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists, **kwargs)",
"if extra_vars:\n kwargs['ext... | <|body_start_0|>
if extra_vars:
kwargs['extra_vars'] = parser.process_extra_vars(extra_vars, force_json=False)
if not kwargs.get('job_type', False):
kwargs['job_type'] = 'run'
return super(Resource, self).create(fail_on_found=fail_on_found, force_on_exists=force_on_exists... | Resource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resource:
def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, **kwargs):
"""Create a job template. You may include multiple --extra-vars flags in order to combine different sources of extra variables. Start this with @ in order to indicate a filename."""
... | stack_v2_sparse_classes_36k_train_026022 | 4,154 | permissive | [
{
"docstring": "Create a job template. You may include multiple --extra-vars flags in order to combine different sources of extra variables. Start this with @ in order to indicate a filename.",
"name": "create",
"signature": "def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, ... | 2 | stack_v2_sparse_classes_30k_train_018739 | Implement the Python class `Resource` described below.
Class description:
Implement the Resource class.
Method signatures and docstrings:
- def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, **kwargs): Create a job template. You may include multiple --extra-vars flags in order to combine di... | Implement the Python class `Resource` described below.
Class description:
Implement the Resource class.
Method signatures and docstrings:
- def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, **kwargs): Create a job template. You may include multiple --extra-vars flags in order to combine di... | e6a1f62a4f33ea94ff7dd53b9690a7b3057a7a31 | <|skeleton|>
class Resource:
def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, **kwargs):
"""Create a job template. You may include multiple --extra-vars flags in order to combine different sources of extra variables. Start this with @ in order to indicate a filename."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resource:
def create(self, fail_on_found=False, force_on_exists=False, extra_vars=None, **kwargs):
"""Create a job template. You may include multiple --extra-vars flags in order to combine different sources of extra variables. Start this with @ in order to indicate a filename."""
if extra_vars... | the_stack_v2_python_sparse | lib/tower_cli/resources/job_template.py | willthames/tower-cli | train | 2 | |
85f2568d0c2d48ca7a930f30af32bd52be4def5d | [
"def helper(in_left=0, in_right=len(in_order)):\n nonlocal pre_index\n if in_left == in_right:\n return None\n root_val = pre_order[pre_index]\n root = TreeNode(root_val)\n index = index_map[root_val]\n pre_index += 1\n root.left = helper(in_left, index)\n root.right = helper(index + ... | <|body_start_0|>
def helper(in_left=0, in_right=len(in_order)):
nonlocal pre_index
if in_left == in_right:
return None
root_val = pre_order[pre_index]
root = TreeNode(root_val)
index = index_map[root_val]
pre_index += 1
... | ConstructBST | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstructBST:
def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param pre_order: :param in_order: :return:"""
<|body_0|>
def from_in_order_and_post_order(s... | stack_v2_sparse_classes_36k_train_026023 | 2,539 | no_license | [
{
"docstring": "Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param pre_order: :param in_order: :return:",
"name": "from_pre_order_and_in_order_values",
"signature": "def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode"
},
{
"do... | 2 | null | Implement the Python class `ConstructBST` described below.
Class description:
Implement the ConstructBST class.
Method signatures and docstrings:
- def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode: Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :par... | Implement the Python class `ConstructBST` described below.
Class description:
Implement the ConstructBST class.
Method signatures and docstrings:
- def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode: Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :par... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class ConstructBST:
def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param pre_order: :param in_order: :return:"""
<|body_0|>
def from_in_order_and_post_order(s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConstructBST:
def from_pre_order_and_in_order_values(self, pre_order: List[int], in_order: List[int]) -> TreeNode:
"""Approach: Recursion Time Complexity: O(N) Space Complexity: O(N) :param pre_order: :param in_order: :return:"""
def helper(in_left=0, in_right=len(in_order)):
nonlo... | the_stack_v2_python_sparse | data_structures/tree_node/construct_bst_with_pre_post_and_in_order.py | Shiv2157k/leet_code | train | 1 | |
460ca86277d582b476ee991bc598709640996d3b | [
"super().__init__(name, property_set, price)\nself.house_price = house_price\nself.rents = rents\nself.number_of_houses = 0",
"if self.number_of_houses == 0:\n rent = self.rents[0]\n owner = self.owner\n if self.property_set in owner.state.owned_unmortgaged_sets:\n rent *= 2\nelse:\n rent = sel... | <|body_start_0|>
super().__init__(name, property_set, price)
self.house_price = house_price
self.rents = rents
self.number_of_houses = 0
<|end_body_0|>
<|body_start_1|>
if self.number_of_houses == 0:
rent = self.rents[0]
owner = self.owner
if ... | A type of Property representing a street. Manages rents, house-building and so on. | Street | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
... | stack_v2_sparse_classes_36k_train_026024 | 1,609 | permissive | [
{
"docstring": "The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]",
"name": "__init__",
"signature": "def __init__(self, name, property_set, price, house_price, rents)"
},
{
"docstring": "The player has landed on a square owned by anot... | 2 | stack_v2_sparse_classes_30k_train_004691 | Implement the Python class `Street` described below.
Class description:
A type of Property representing a street. Manages rents, house-building and so on.
Method signatures and docstrings:
- def __init__(self, name, property_set, price, house_price, rents): The 'constructor'. rents: passed in as a list: [base, one_ho... | Implement the Python class `Street` described below.
Class description:
A type of Property representing a street. Manages rents, house-building and so on.
Method signatures and docstrings:
- def __init__(self, name, property_set, price, house_price, rents): The 'constructor'. rents: passed in as a list: [base, one_ho... | 0460f2452c83846b6b9e3b234be411e12a86d69c | <|skeleton|>
class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
super().... | the_stack_v2_python_sparse | monopyly/squares/street.py | YSabarad/monopyly | train | 0 |
1d3376b4a156f6ff922dfcfd3e6dfbee4a25fec7 | [
"for x in range(len(factors)):\n if factors[x] > 1:\n tree = StencilCacheBlocker.StripMineLoopByIndex(x * 2, factors[x]).visit(tree)\nfor x in range(1, len(factors)):\n if factors[x] > 1:\n tree = self.bubble(tree, 2 * x, x)\nreturn tree",
"for x in range(index - new_index):\n tree = LoopSw... | <|body_start_0|>
for x in range(len(factors)):
if factors[x] > 1:
tree = StencilCacheBlocker.StripMineLoopByIndex(x * 2, factors[x]).visit(tree)
for x in range(1, len(factors)):
if factors[x] > 1:
tree = self.bubble(tree, 2 * x, x)
return t... | Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original tree. | StencilCacheBlocker | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StencilCacheBlocker:
"""Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original tree."""
def block(self, tree, fact... | stack_v2_sparse_classes_36k_train_026025 | 8,373 | no_license | [
{
"docstring": "Main method in StencilCacheBlocker. Used to block the loops in the tree.",
"name": "block",
"signature": "def block(self, tree, factors)"
},
{
"docstring": "Helper function to 'bubble up' a loop at index to be at new_index (new_index < index) while preserving the ordering of the ... | 2 | stack_v2_sparse_classes_30k_test_000434 | Implement the Python class `StencilCacheBlocker` described below.
Class description:
Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original t... | Implement the Python class `StencilCacheBlocker` described below.
Class description:
Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original t... | 87f5d5115587f3362c8ea097900d3d50a3485b1a | <|skeleton|>
class StencilCacheBlocker:
"""Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original tree."""
def block(self, tree, fact... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StencilCacheBlocker:
"""Class that takes a tree of perfectly-nested For loops (as in a stencil) and performs standard cache blocking on them. Usage: StencilCacheBlocker().block(tree, factors) where factors is a tuple, one for each loop nest in the original tree."""
def block(self, tree, factors):
... | the_stack_v2_python_sparse | stencil_code/optimizer.py | ucb-sejits/stencil_code | train | 3 |
04d19ce6c326937213a6918658252997e7f432c8 | [
"attack = UnitType.compute_attack(self, tribe, opponent_tribe)\nattack += self.attack * 0.03 * tribe.get_techno_level_by_name('carved_stone')\nif self.is_ranged():\n attack += self.attack * 0.05 * tribe.get_techno_level_by_name('bone_work')\nelse:\n attack += self.attack * 0.03 * tribe.get_techno_level_by_nam... | <|body_start_0|>
attack = UnitType.compute_attack(self, tribe, opponent_tribe)
attack += self.attack * 0.03 * tribe.get_techno_level_by_name('carved_stone')
if self.is_ranged():
attack += self.attack * 0.05 * tribe.get_techno_level_by_name('bone_work')
else:
attac... | designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones. | Human | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Human:
"""designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones."""
def compute_attack(self, tribe=None, opponent_tribe=None):
"""get the attack of the :model:`game.Human`, considering th... | stack_v2_sparse_classes_36k_train_026026 | 5,235 | no_license | [
{
"docstring": "get the attack of the :model:`game.Human`, considering the :model:`game.TechnologyKnowledge` of the owner’s and oponent’s :model:`game.Tribe`",
"name": "compute_attack",
"signature": "def compute_attack(self, tribe=None, opponent_tribe=None)"
},
{
"docstring": "get the defense of... | 3 | stack_v2_sparse_classes_30k_train_006392 | Implement the Python class `Human` described below.
Class description:
designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones.
Method signatures and docstrings:
- def compute_attack(self, tribe=None, opponent_tribe=None): ... | Implement the Python class `Human` described below.
Class description:
designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones.
Method signatures and docstrings:
- def compute_attack(self, tribe=None, opponent_tribe=None): ... | 1eec39046de6540e02de0af601c6d0546da19ad4 | <|skeleton|>
class Human:
"""designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones."""
def compute_attack(self, tribe=None, opponent_tribe=None):
"""get the attack of the :model:`game.Human`, considering th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Human:
"""designs a human kind of unit. Inherits from :model:`game:UnitType` for fighting behaviour, but has a economical concerns as well as technological ones."""
def compute_attack(self, tribe=None, opponent_tribe=None):
"""get the attack of the :model:`game.Human`, considering the :model:`gam... | the_stack_v2_python_sparse | game/models/unit.py | ramabouda/dolmen | train | 0 |
8a76dffc61a48d148c208898506130ee2b12e2e1 | [
"res = ApiResponse('Error in triggering RCA calculation')\nrootCauseAnalysis, _ = RootCauseAnalysis.objects.get_or_create(anomaly_id=anomalyId)\nrootCauseAnalysis.status = RootCauseAnalysis.STATUS_RECEIVED\nrootCauseAnalysis.save()\ntask = rootCauseAnalysisJob.delay(anomalyId)\nrootCauseAnalysis = RootCauseAnalysis... | <|body_start_0|>
res = ApiResponse('Error in triggering RCA calculation')
rootCauseAnalysis, _ = RootCauseAnalysis.objects.get_or_create(anomaly_id=anomalyId)
rootCauseAnalysis.status = RootCauseAnalysis.STATUS_RECEIVED
rootCauseAnalysis.save()
task = rootCauseAnalysisJob.delay(a... | Class to deal with functionalities associataed with RCA | RootCauseAnalyses | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootCauseAnalyses:
"""Class to deal with functionalities associataed with RCA"""
def calculateRCA(anomalyId: int):
"""Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed"""
<|body_0|>
def getRCA(anomalyId: int):
"""Get dat... | stack_v2_sparse_classes_36k_train_026027 | 5,943 | permissive | [
{
"docstring": "Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed",
"name": "calculateRCA",
"signature": "def calculateRCA(anomalyId: int)"
},
{
"docstring": "Get data for RCA :param anomalyId: id of anomaly object whose RCA to be fetched",
"name": ... | 4 | stack_v2_sparse_classes_30k_train_019895 | Implement the Python class `RootCauseAnalyses` described below.
Class description:
Class to deal with functionalities associataed with RCA
Method signatures and docstrings:
- def calculateRCA(anomalyId: int): Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed
- def getRCA(ano... | Implement the Python class `RootCauseAnalyses` described below.
Class description:
Class to deal with functionalities associataed with RCA
Method signatures and docstrings:
- def calculateRCA(anomalyId: int): Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed
- def getRCA(ano... | 4c10cd804d6ca31a21d14d65670fa4c6b9a5d011 | <|skeleton|>
class RootCauseAnalyses:
"""Class to deal with functionalities associataed with RCA"""
def calculateRCA(anomalyId: int):
"""Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed"""
<|body_0|>
def getRCA(anomalyId: int):
"""Get dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RootCauseAnalyses:
"""Class to deal with functionalities associataed with RCA"""
def calculateRCA(anomalyId: int):
"""Trigger job for RCA calculation :param anomalyId: id of anomaly object needed to be analyzed"""
res = ApiResponse('Error in triggering RCA calculation')
rootCauseA... | the_stack_v2_python_sparse | api/anomaly/services/rootCauseAnalyses.py | Slach/CueObserve | train | 0 |
737e6736fba9eca295117d03131560384f7c1f89 | [
"self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\nself.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')\nself.plugin_dir = directory\nself.log = None\nself.database = None\nself.noa = None\nself.thread = None\nself.thread_clock = None\nself.javaProcessObject = None\nself.pixmap_w... | <|body_start_0|>
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = directory
self.log = None
self.database = None
self.noa = None
self.thread = None
s... | Resources used by the process & interface Objects | Resources | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_36k_train_026028 | 5,429 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, directory)"
},
{
"docstring": "load interface graphical resources",
"name": "loadAppResources",
"signature": "def loadAppResources(self)"
},
{
"docstring": "Release application resources",
"nam... | 3 | stack_v2_sparse_classes_30k_train_009629 | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | Implement the Python class `Resources` described below.
Class description:
Resources used by the process & interface Objects
Method signatures and docstrings:
- def __init__(self, directory): Constructor
- def loadAppResources(self): load interface graphical resources
- def releaseResources(self, planHeatDMM): Releas... | 9764fcb86d3898b232c4cc333dab75ebe41cd421 | <|skeleton|>
class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
<|body_0|>
def loadAppResources(self):
"""load interface graphical resources"""
<|body_1|>
def releaseResources(self, planHeatDMM):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Resources:
"""Resources used by the process & interface Objects"""
def __init__(self, directory):
"""Constructor"""
self.logDateName = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
self.processName = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
self.plugin_dir = d... | the_stack_v2_python_sparse | PlanheatMappingModule/PlanHeatDMM/src/resources.py | Planheat/Planheat-Tool | train | 2 |
7223eacecb47885da2370922cbcb773f55363b59 | [
"if 'title' not in kwargs:\n kwargs['title'] = 'Member image'\nreturn self.getField('member_image').tag(self, **kwargs)",
"results = CONSTITUENCIES_LIST[master]\nresults = [(item, item) for item in results]\nreturn atapi.DisplayList(results)"
] | <|body_start_0|>
if 'title' not in kwargs:
kwargs['title'] = 'Member image'
return self.getField('member_image').tag(self, **kwargs)
<|end_body_0|>
<|body_start_1|>
results = CONSTITUENCIES_LIST[master]
results = [(item, item) for item in results]
return atapi.Displa... | Member Profile | MemberProfile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
<|body_0|>
def getConstituencyVocab(self, master):
"""Vocab method that returns a vocabulary consisting of the constituencies from the given coun... | stack_v2_sparse_classes_36k_train_026029 | 6,488 | no_license | [
{
"docstring": "Generate image tag using the api of the ImageField",
"name": "tag",
"signature": "def tag(self, **kwargs)"
},
{
"docstring": "Vocab method that returns a vocabulary consisting of the constituencies from the given county.",
"name": "getConstituencyVocab",
"signature": "def... | 2 | null | Implement the Python class `MemberProfile` described below.
Class description:
Member Profile
Method signatures and docstrings:
- def tag(self, **kwargs): Generate image tag using the api of the ImageField
- def getConstituencyVocab(self, master): Vocab method that returns a vocabulary consisting of the constituencie... | Implement the Python class `MemberProfile` described below.
Class description:
Member Profile
Method signatures and docstrings:
- def tag(self, **kwargs): Generate image tag using the api of the ImageField
- def getConstituencyVocab(self, master): Vocab method that returns a vocabulary consisting of the constituencie... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
<|body_0|>
def getConstituencyVocab(self, master):
"""Vocab method that returns a vocabulary consisting of the constituencies from the given coun... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MemberProfile:
"""Member Profile"""
def tag(self, **kwargs):
"""Generate image tag using the api of the ImageField"""
if 'title' not in kwargs:
kwargs['title'] = 'Member image'
return self.getField('member_image').tag(self, **kwargs)
def getConstituencyVocab(self,... | the_stack_v2_python_sparse | plone.products/bungenicms.membershipdirectory/trunk/bungenicms/membershipdirectory/content/memberprofile.py | malangalanga/bungeni-portal | train | 0 |
3886138f19051d29bd84361f4cab894f078a923d | [
"Algorithm.__init__(self)\nself.name = 'Keep only largest connected component'\nself.parent = 'Graph filtering'",
"image_arr, graph = args\ntry:\n graph = max(nx.connected_component_subgraphs(graph), key=len)\nexcept ValueError as e:\n print('ValueError exception:', e)\nself.result['graph'], self.result['im... | <|body_start_0|>
Algorithm.__init__(self)
self.name = 'Keep only largest connected component'
self.parent = 'Graph filtering'
<|end_body_0|>
<|body_start_1|>
image_arr, graph = args
try:
graph = max(nx.connected_component_subgraphs(graph), key=len)
except Val... | Keep only largest connected component algorithm implementation. | AlgBody | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlgBody:
"""Keep only largest connected component algorithm implementation."""
def __init__(self):
"""Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category"""
<|body_0|>
def process(self, args):
"""Keep only largest connect... | stack_v2_sparse_classes_36k_train_026030 | 1,637 | permissive | [
{
"docstring": "Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Keep only largest connected component from nefi1. Args: | *args* : a list containing image array and Graph obje... | 2 | null | Implement the Python class `AlgBody` described below.
Class description:
Keep only largest connected component algorithm implementation.
Method signatures and docstrings:
- def __init__(self): Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category
- def process(self, args): Keep... | Implement the Python class `AlgBody` described below.
Class description:
Keep only largest connected component algorithm implementation.
Method signatures and docstrings:
- def __init__(self): Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category
- def process(self, args): Keep... | 0dc9becc09da22af3edac90b81b1dd9b1f44fd5b | <|skeleton|>
class AlgBody:
"""Keep only largest connected component algorithm implementation."""
def __init__(self):
"""Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category"""
<|body_0|>
def process(self, args):
"""Keep only largest connect... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlgBody:
"""Keep only largest connected component algorithm implementation."""
def __init__(self):
"""Instance vars: | *name* : name of the algorithm | *parent* : name of the appropriate category"""
Algorithm.__init__(self)
self.name = 'Keep only largest connected component'
... | the_stack_v2_python_sparse | nefi2/model/algorithms/largest_connected.py | andreasfirczynski/NetworkExtractionFromImages | train | 0 |
70387825f1b1998cf882aa234f2d5388f7e88fc3 | [
"nums_sorted = sorted(nums)\ns = e = -1\nfor i in range(len(nums)):\n if nums[i] != nums_sorted[i]:\n if s == -1:\n s = i\n e = i\nif e != s:\n return e - s + 1\nelse:\n return 0",
"min_val = 9999\nmax_val = -9999\nflag = False\nfor i in range(1, len(nums)):\n if nums[i] < num... | <|body_start_0|>
nums_sorted = sorted(nums)
s = e = -1
for i in range(len(nums)):
if nums[i] != nums_sorted[i]:
if s == -1:
s = i
e = i
if e != s:
return e - s + 1
else:
return 0
<|end_body_0|... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findUnsortedSubarray_sortedMethod(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray_noExtraSpace(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n... | stack_v2_sparse_classes_36k_train_026031 | 1,532 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray_sortedMethod",
"signature": "def findUnsortedSubarray_sortedMethod(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findUnsortedSubarray_noExtraSpace",
"signature": "def findUnso... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray_sortedMethod(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray_noExtraSpace(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findUnsortedSubarray_sortedMethod(self, nums): :type nums: List[int] :rtype: int
- def findUnsortedSubarray_noExtraSpace(self, nums): :type nums: List[int] :rtype: int
<|ske... | a0f270c1adce25be11df92877813037f2e73e28b | <|skeleton|>
class Solution:
def findUnsortedSubarray_sortedMethod(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findUnsortedSubarray_noExtraSpace(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findUnsortedSubarray_sortedMethod(self, nums):
""":type nums: List[int] :rtype: int"""
nums_sorted = sorted(nums)
s = e = -1
for i in range(len(nums)):
if nums[i] != nums_sorted[i]:
if s == -1:
s = i
... | the_stack_v2_python_sparse | leetcode/581_shortest_unsorted_continuous_subarray.py | lvraikkonen/GoodCode | train | 0 | |
797b48eba8b550b2169a53ff5a76e512e4f13e86 | [
"self.time_delta_val = time_delta\nself.time_grace_val = time_grace\nself.db_lookup = db_lookup\nself.data_binding = data_binding\nself.nowtime = nowtime\nself.formatter = formatter\nself.converter = converter\nself.time_delta = weewx.units.ValueHelper((time_delta, 'second', 'group_elapsed'), 'current', self.format... | <|body_start_0|>
self.time_delta_val = time_delta
self.time_grace_val = time_grace
self.db_lookup = db_lookup
self.data_binding = data_binding
self.nowtime = nowtime
self.formatter = formatter
self.converter = converter
self.time_delta = weewx.units.ValueH... | Helper class that calculates trends. This class allows tags such as: $trend.barometer | TrendObj | [
"GPL-3.0-only",
"GPL-1.0-or-later",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over w... | stack_v2_sparse_classes_36k_train_026032 | 23,688 | permissive | [
{
"docstring": "Initialize a Trend object time_delta: The time difference over which the trend is to be calculated time_grace: A time within this amount is accepted.",
"name": "__init__",
"signature": "def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **o... | 2 | null | Implement the Python class `TrendObj` described below.
Class description:
Helper class that calculates trends. This class allows tags such as: $trend.barometer
Method signatures and docstrings:
- def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict): Initial... | Implement the Python class `TrendObj` described below.
Class description:
Helper class that calculates trends. This class allows tags such as: $trend.barometer
Method signatures and docstrings:
- def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict): Initial... | 7085654f455d39b06acc688738fde27e1f78ad1e | <|skeleton|>
class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrendObj:
"""Helper class that calculates trends. This class allows tags such as: $trend.barometer"""
def __init__(self, time_delta, time_grace, db_lookup, data_binding, nowtime, formatter, converter, **option_dict):
"""Initialize a Trend object time_delta: The time difference over which the tren... | the_stack_v2_python_sparse | dist/weewx-3.9.1/bin/weewx/tags.py | tomdotorg/docker-weewx | train | 21 |
c31afd1f99210d700b1b8664c40a26bb3f81bf61 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn ServiceHealth()",
"from .entity import Entity\nfrom .service_health_issue import ServiceHealthIssue\nfrom .service_health_status import ServiceHealthStatus\nfrom .entity import Entity\nfrom .service_health_issue import ServiceHealthIss... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return ServiceHealth()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .service_health_issue import ServiceHealthIssue
from .service_health_status import ServiceHealthSt... | ServiceHealth | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceHealth:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ServiceHealth:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k_train_026033 | 2,965 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ServiceHealth",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value... | 3 | stack_v2_sparse_classes_30k_train_021572 | Implement the Python class `ServiceHealth` described below.
Class description:
Implement the ServiceHealth class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ServiceHealth: Creates a new instance of the appropriate class based on discriminator value... | Implement the Python class `ServiceHealth` described below.
Class description:
Implement the ServiceHealth class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ServiceHealth: Creates a new instance of the appropriate class based on discriminator value... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ServiceHealth:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ServiceHealth:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ServiceHealth:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ServiceHealth:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ServiceHealt... | the_stack_v2_python_sparse | msgraph/generated/models/service_health.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
1ede40354dc18ecdfd5c1a5ca3c4b43ebd1d08ec | [
"threading.Thread.__init__(self)\nself.condition = condition\nself.item_list = item_list\nself.node = node",
"self.item = None\nif not self.item_list:\n self.condition.acquire()\n while True:\n if self.item_list:\n self.item = self.item_list.pop()\n break\n self.condition... | <|body_start_0|>
threading.Thread.__init__(self)
self.condition = condition
self.item_list = item_list
self.node = node
<|end_body_0|>
<|body_start_1|>
self.item = None
if not self.item_list:
self.condition.acquire()
while True:
if... | DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads. | DataReceiver | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataReceiver:
"""DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads."""
def __init__(self, condition, item_list, node):
"""Inits a DataReceiver instance. @param condition is a condition variable @param item... | stack_v2_sparse_classes_36k_train_026034 | 4,965 | no_license | [
{
"docstring": "Inits a DataReceiver instance. @param condition is a condition variable @param item_list is a list that contains items. @param node is a Node instance (actually the node that called the item).",
"name": "__init__",
"signature": "def __init__(self, condition, item_list, node)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_015601 | Implement the Python class `DataReceiver` described below.
Class description:
DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads.
Method signatures and docstrings:
- def __init__(self, condition, item_list, node): Inits a DataReceiver insta... | Implement the Python class `DataReceiver` described below.
Class description:
DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads.
Method signatures and docstrings:
- def __init__(self, condition, item_list, node): Inits a DataReceiver insta... | 90963eea34ba24a011ec5522e6d436ef891608dc | <|skeleton|>
class DataReceiver:
"""DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads."""
def __init__(self, condition, item_list, node):
"""Inits a DataReceiver instance. @param condition is a condition variable @param item... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataReceiver:
"""DataReceiver() receives a recently produced item. It represents the Consumer in a Consumer-Producer model. It works with threads."""
def __init__(self, condition, item_list, node):
"""Inits a DataReceiver instance. @param condition is a condition variable @param item_list is a li... | the_stack_v2_python_sparse | node/old-node.py | cbabalis/Elita | train | 0 |
d81b6c619422975c5739e0e14acaeccfe09ba0da | [
"if log2(n_init) % 1 != 0:\n warning_s = ' n_init must be a power of 2. Using n_init = 32'\n warnings.warn(warning_s, ParameterWarning)\n n_init = 32\nself.abs_tol = float(abs_tol)\nself.rel_tol = float(rel_tol)\nself.n_init = float(n_init)\nself.n_max = float(n_max)\nself.alpha = float(alpha)\nself.z_star... | <|body_start_0|>
if log2(n_init) % 1 != 0:
warning_s = ' n_init must be a power of 2. Using n_init = 32'
warnings.warn(warning_s, ParameterWarning)
n_init = 32
self.abs_tol = float(abs_tol)
self.rel_tol = float(rel_tol)
self.n_init = float(n_init)
... | Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> data Solution: 1.3799 Keister (Integrand Object) Lattice (DiscreteDistribution ... | CubQMCCLT | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CubQMCCLT:
"""Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> data Solution: 1.3799 Keister (Integrand O... | stack_v2_sparse_classes_36k_train_026035 | 5,196 | permissive | [
{
"docstring": "Args: integrand (Integrand): an instance of Integrand inflate (float): inflation factor when estimating variance alpha (float): significance level for confidence interval abs_tol (float): absolute error tolerance rel_tol (float): relative error tolerance n_max (int): maximum number of samples re... | 3 | null | Implement the Python class `CubQMCCLT` described below.
Class description:
Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> dat... | Implement the Python class `CubQMCCLT` described below.
Class description:
Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> dat... | 0ed9da2f10b9ac0004c993c01392b4c86002954c | <|skeleton|>
class CubQMCCLT:
"""Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> data Solution: 1.3799 Keister (Integrand O... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CubQMCCLT:
"""Stopping criterion based on Central Limit Theorem for multiple replications. >>> k = Keister(Gaussian(Lattice(seed=7),covariance=1./2)) >>> sc = CubQMCCLT(k,abs_tol=.05) >>> solution,data = sc.integrate() >>> solution 1.3798619783658828 >>> data Solution: 1.3799 Keister (Integrand Object) Lattic... | the_stack_v2_python_sparse | qmcpy/stopping_criterion/cub_qmc_clt.py | kachiann/QMCSoftware | train | 1 |
8f0708deafcad02261115190644b4b073e5ed17c | [
"cnt = collections.Counter(words)\nheap = [(-freq, word) for word, freq in cnt.items()]\nheapq.heapify(heap)\nreturn [heapq.heappop(heap)[1] for _ in range(k)]",
"import collections\ncnt = collections.Counter(words)\nkeys = list(cnt.keys())\nkeys.sort(key=lambda w: (-cnt[w], w))\nreturn keys[:k]"
] | <|body_start_0|>
cnt = collections.Counter(words)
heap = [(-freq, word) for word, freq in cnt.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
<|end_body_0|>
<|body_start_1|>
import collections
cnt = collections.Counter(words)
keys =... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_0|>
def topKFrequentSort(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_026036 | 920 | no_license | [
{
"docstring": ":type words: List[str] :type k: int :rtype: List[str]",
"name": "topKFrequent",
"signature": "def topKFrequent(self, words, k)"
},
{
"docstring": ":type words: List[str] :type k: int :rtype: List[str]",
"name": "topKFrequentSort",
"signature": "def topKFrequentSort(self, ... | 2 | stack_v2_sparse_classes_30k_train_011414 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, words, k): :type words: List[str] :type k: int :rtype: List[str]
- def topKFrequentSort(self, words, k): :type words: List[str] :type k: int :rtype: List[s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def topKFrequent(self, words, k): :type words: List[str] :type k: int :rtype: List[str]
- def topKFrequentSort(self, words, k): :type words: List[str] :type k: int :rtype: List[s... | ac53dd9bf2c4c9d17c9dc5f7fdda32e386658fdd | <|skeleton|>
class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_0|>
def topKFrequentSort(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def topKFrequent(self, words, k):
""":type words: List[str] :type k: int :rtype: List[str]"""
cnt = collections.Counter(words)
heap = [(-freq, word) for word, freq in cnt.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
def t... | the_stack_v2_python_sparse | words/top_k_frequent_words.py | hwc1824/LeetCodeSolution | train | 0 | |
8fd7353e4769d95986a91f882e3ec7dab72f94ff | [
"self.patience = patience\nself.verbose = verbose\nself.counter = 0\nself.best_score = None\nself.early_stop = False\nself.val_loss_min = np.Inf\nself.folder_path = folder_path",
"score = val_loss\nif self.best_score is None:\n self.best_score = score\n self.save_checkpoint(epoch, train_loss, val_loss, mode... | <|body_start_0|>
self.patience = patience
self.verbose = verbose
self.counter = 0
self.best_score = None
self.early_stop = False
self.val_loss_min = np.Inf
self.folder_path = folder_path
<|end_body_0|>
<|body_start_1|>
score = val_loss
if self.bes... | Early stops the training if validation loss doesn't improve after a given patience. | EarlyStopping | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True,... | stack_v2_sparse_classes_36k_train_026037 | 2,522 | no_license | [
{
"docstring": "Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True, prints a message for each validation loss improvement. Default: False path (str): path to folder where tp save the state dict.",
"name": "__init__",
"signature": "def __in... | 3 | stack_v2_sparse_classes_30k_train_002666 | Implement the Python class `EarlyStopping` described below.
Class description:
Early stops the training if validation loss doesn't improve after a given patience.
Method signatures and docstrings:
- def __init__(self, folder_path, patience=7, verbose=False): Args: patience (int): How long to wait after last time vali... | Implement the Python class `EarlyStopping` described below.
Class description:
Early stops the training if validation loss doesn't improve after a given patience.
Method signatures and docstrings:
- def __init__(self, folder_path, patience=7, verbose=False): Args: patience (int): How long to wait after last time vali... | 6311e012ceb4e6a1a45fdd5237a3b629c5319f8c | <|skeleton|>
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, folder_path, patience=7, verbose=False):
"""Args: patience (int): How long to wait after last time validation loss improved. Default: 7 verbose (bool): If True, prints a mes... | the_stack_v2_python_sparse | point_cloud_input/early_stopping.py | jtpils/master_thesis | train | 2 |
1ea85f28bec44c722a4c462ac6f3ff6194964709 | [
"if isinstance(interval, int):\n self._i = interval\nelif isinstance(int(interval), int):\n self._i = int(interval)\nif self._i < 0:\n raise ValueError('interval should be positive')\nif isinstance(float(sigma), (float,)):\n sigma = float(sigma)\n if sigma >= 0:\n self._sigma = sigma\n else... | <|body_start_0|>
if isinstance(interval, int):
self._i = interval
elif isinstance(int(interval), int):
self._i = int(interval)
if self._i < 0:
raise ValueError('interval should be positive')
if isinstance(float(sigma), (float,)):
sigma = fl... | Gaussian weighted moving average helper object. | GaussianMean | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GaussianMean:
"""Gaussian weighted moving average helper object."""
def __init__(self, interval, sigma=1.0):
"""GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for each point of the values' array including the point itse... | stack_v2_sparse_classes_36k_train_026038 | 6,931 | no_license | [
{
"docstring": "GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for each point of the values' array including the point itself. The interval is centered on the current point and an even interval will be promoted to the next odd value (e.g. 4 will b... | 2 | null | Implement the Python class `GaussianMean` described below.
Class description:
Gaussian weighted moving average helper object.
Method signatures and docstrings:
- def __init__(self, interval, sigma=1.0): GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for... | Implement the Python class `GaussianMean` described below.
Class description:
Gaussian weighted moving average helper object.
Method signatures and docstrings:
- def __init__(self, interval, sigma=1.0): GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for... | 985f34c2214ea55cd4d324704847d5a0d2a9de1e | <|skeleton|>
class GaussianMean:
"""Gaussian weighted moving average helper object."""
def __init__(self, interval, sigma=1.0):
"""GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for each point of the values' array including the point itse... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GaussianMean:
"""Gaussian weighted moving average helper object."""
def __init__(self, interval, sigma=1.0):
"""GaussianMean class constructor. Args: - *interval*: the amount of nearby points that the filter has to consider for each point of the values' array including the point itself. The inter... | the_stack_v2_python_sparse | mhelpers/mean.py | inogs/bit.sea | train | 4 |
962c4b48dd3108cc4e27acba5fc8af2cb7a8fd11 | [
"sentinel_sectPr = self.get_or_add_sectPr()\ncloned_sectPr = sentinel_sectPr.clone()\np = self.add_p()\np.set_sectPr(cloned_sectPr)\nreturn sentinel_sectPr",
"if self.sectPr is not None:\n content_elms = self[:-1]\nelse:\n content_elms = self[:]\nfor content_elm in content_elms:\n self.remove(content_elm... | <|body_start_0|>
sentinel_sectPr = self.get_or_add_sectPr()
cloned_sectPr = sentinel_sectPr.clone()
p = self.add_p()
p.set_sectPr(cloned_sectPr)
return sentinel_sectPr
<|end_body_0|>
<|body_start_1|>
if self.sectPr is not None:
content_elms = self[:-1]
... | ``<w:body>``, the container element for the main document story in ``document.xml``. | CT_Body | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element appended to the block content elements. Note that the "c... | stack_v2_sparse_classes_36k_train_026039 | 1,810 | permissive | [
{
"docstring": "Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element appended to the block content elements. Note that the \"current\" ``<w:sectPr>`` will always be the sentinel sectPr in this case since we're always working at the end of the block content.",
"name... | 2 | stack_v2_sparse_classes_30k_train_020073 | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element... | Implement the Python class `CT_Body` described below.
Class description:
``<w:body>``, the container element for the main document story in ``document.xml``.
Method signatures and docstrings:
- def add_section_break(self): Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element... | cabf6e4f1970dc14302f87414f170de19944bac2 | <|skeleton|>
class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element appended to the block content elements. Note that the "c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CT_Body:
"""``<w:body>``, the container element for the main document story in ``document.xml``."""
def add_section_break(self):
"""Return the current ``<w:sectPr>`` element after adding a clone of it in a new ``<w:p>`` element appended to the block content elements. Note that the "current" ``<w:... | the_stack_v2_python_sparse | Pdf_docx_pptx_xlsx_epub_png/source/docx/oxml/document.py | ryfeus/lambda-packs | train | 1,283 |
f6572f8bf975d49ddada45749086cd8f95487c45 | [
"self.api: CentralUnitPolling | CentralUnitWsRPC = swb_api\nself._reconnect_counts: int = 0\nassert self.api.mac is not None\nself.unique_id = self.api.unique_id if self.api.unique_id is not None else format_mac(self.api.mac)\nsuper().__init__(hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=SCAN_INTER... | <|body_start_0|>
self.api: CentralUnitPolling | CentralUnitWsRPC = swb_api
self._reconnect_counts: int = 0
assert self.api.mac is not None
self.unique_id = self.api.unique_id if self.api.unique_id is not None else format_mac(self.api.mac)
super().__init__(hass, _LOGGER, name=DOMA... | Class to manage fetching SwitchBee data API. | SwitchBeeCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SwitchBeeCoordinator:
"""Class to manage fetching SwitchBee data API."""
def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None:
"""Initialize."""
<|body_0|>
def _async_handle_update(self, push_data: dict) -> None:
"""Manu... | stack_v2_sparse_classes_36k_train_026040 | 3,546 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None"
},
{
"docstring": "Manually update data and notify listeners.",
"name": "_async_handle_update",
"signature": "def _async_handle... | 3 | null | Implement the Python class `SwitchBeeCoordinator` described below.
Class description:
Class to manage fetching SwitchBee data API.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None: Initialize.
- def _async_handle_update(self, push_data... | Implement the Python class `SwitchBeeCoordinator` described below.
Class description:
Class to manage fetching SwitchBee data API.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None: Initialize.
- def _async_handle_update(self, push_data... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class SwitchBeeCoordinator:
"""Class to manage fetching SwitchBee data API."""
def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None:
"""Initialize."""
<|body_0|>
def _async_handle_update(self, push_data: dict) -> None:
"""Manu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SwitchBeeCoordinator:
"""Class to manage fetching SwitchBee data API."""
def __init__(self, hass: HomeAssistant, swb_api: CentralUnitPolling | CentralUnitWsRPC) -> None:
"""Initialize."""
self.api: CentralUnitPolling | CentralUnitWsRPC = swb_api
self._reconnect_counts: int = 0
... | the_stack_v2_python_sparse | homeassistant/components/switchbee/coordinator.py | home-assistant/core | train | 35,501 |
e7ba890d619554bbc5031203eeee5155cfaf4e7a | [
"self.hashmap = collections.defaultdict(list)\nfor i in range(len(words)):\n self.hashmap[words[i]].append(i)",
"loc1 = self.hashmap[word1]\nloc2 = self.hashmap[word2]\np1 = 0\np2 = 0\ndiff = float('inf')\nwhile p1 < len(loc1) and p2 < len(loc2):\n diff = min(diff, abs(loc1[p1] - loc2[p2]))\n if loc1[p1]... | <|body_start_0|>
self.hashmap = collections.defaultdict(list)
for i in range(len(words)):
self.hashmap[words[i]].append(i)
<|end_body_0|>
<|body_start_1|>
loc1 = self.hashmap[word1]
loc2 = self.hashmap[word2]
p1 = 0
p2 = 0
diff = float('inf')
... | WordDistance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.hashmap = collections.defaultdic... | stack_v2_sparse_classes_36k_train_026041 | 1,445 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type word1: str :type word2: str :rtype: int",
"name": "shortest",
"signature": "def shortest(self, word1, word2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013112 | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int | Implement the Python class `WordDistance` described below.
Class description:
Implement the WordDistance class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def shortest(self, word1, word2): :type word1: str :type word2: str :rtype: int
<|skeleton|>
class WordDistance:
... | 819fbc523f3b33742333b6b39b72337a24a26f7a | <|skeleton|>
class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordDistance:
def __init__(self, words):
""":type words: List[str]"""
self.hashmap = collections.defaultdict(list)
for i in range(len(words)):
self.hashmap[words[i]].append(i)
def shortest(self, word1, word2):
""":type word1: str :type word2: str :rtype: int"""... | the_stack_v2_python_sparse | leetcode/Array/244m. 最短单词距离II(有重复,hashmap+双指针).py | Andrewlearning/Leetcoding | train | 1 | |
c84c81ddcc1ff8a22373a9aeaa600c3c6d8a53e2 | [
"if not (url and url.startswith('http')):\n logger.debug('Broken url %r', url)\n return\nreq = requests.get(url)\nif req.status_code == 200:\n voiceplaydb.write_artist_image(artist, req.content)",
"image = None\nif not voiceplaydb.get_artist_image(artist):\n lfm = VoicePlayLastFm()\n url = lfm.get_... | <|body_start_0|>
if not (url and url.startswith('http')):
logger.debug('Broken url %r', url)
return
req = requests.get(url)
if req.status_code == 200:
voiceplaydb.write_artist_image(artist, req.content)
<|end_body_0|>
<|body_start_1|>
image = None
... | Album art container | AlbumArt | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlbumArt:
"""Album art container"""
def set_artist_url(artist, url):
"""Download and save artists' album art"""
<|body_0|>
def get(self, artist):
"""Get artist picture"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not (url and url.startswit... | stack_v2_sparse_classes_36k_train_026042 | 993 | permissive | [
{
"docstring": "Download and save artists' album art",
"name": "set_artist_url",
"signature": "def set_artist_url(artist, url)"
},
{
"docstring": "Get artist picture",
"name": "get",
"signature": "def get(self, artist)"
}
] | 2 | null | Implement the Python class `AlbumArt` described below.
Class description:
Album art container
Method signatures and docstrings:
- def set_artist_url(artist, url): Download and save artists' album art
- def get(self, artist): Get artist picture | Implement the Python class `AlbumArt` described below.
Class description:
Album art container
Method signatures and docstrings:
- def set_artist_url(artist, url): Download and save artists' album art
- def get(self, artist): Get artist picture
<|skeleton|>
class AlbumArt:
"""Album art container"""
def set_a... | 3e35a25cfcf982a3871cf0d819bae4374ee31ecf | <|skeleton|>
class AlbumArt:
"""Album art container"""
def set_artist_url(artist, url):
"""Download and save artists' album art"""
<|body_0|>
def get(self, artist):
"""Get artist picture"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AlbumArt:
"""Album art container"""
def set_artist_url(artist, url):
"""Download and save artists' album art"""
if not (url and url.startswith('http')):
logger.debug('Broken url %r', url)
return
req = requests.get(url)
if req.status_code == 200:
... | the_stack_v2_python_sparse | voiceplay/datasources/albumart/albumart.py | tb0hdan/voiceplay | train | 4 |
f8e8fc96c20017bdd9c6dd55aeb84705a3659cc0 | [
"try:\n title = self.get(language=language, page=page)\n return title\nexcept self.model.DoesNotExist:\n if language_fallback:\n try:\n titles = self.filter(page=page)\n fallbacks = get_fallback_languages(language)\n for l in fallbacks:\n for title in ... | <|body_start_0|>
try:
title = self.get(language=language, page=page)
return title
except self.model.DoesNotExist:
if language_fallback:
try:
titles = self.filter(page=page)
fallbacks = get_fallback_languages(lang... | TitleManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TitleManager:
def get_title(self, page, language, language_fallback=False):
"""Gets the latest content for a particular page and language. Falls back to another language if wanted."""
<|body_0|>
def get_page_slug(self, slug, site=None):
"""Returns the latest slug for... | stack_v2_sparse_classes_36k_train_026043 | 18,602 | permissive | [
{
"docstring": "Gets the latest content for a particular page and language. Falls back to another language if wanted.",
"name": "get_title",
"signature": "def get_title(self, page, language, language_fallback=False)"
},
{
"docstring": "Returns the latest slug for the given slug and checks if it'... | 3 | stack_v2_sparse_classes_30k_train_019882 | Implement the Python class `TitleManager` described below.
Class description:
Implement the TitleManager class.
Method signatures and docstrings:
- def get_title(self, page, language, language_fallback=False): Gets the latest content for a particular page and language. Falls back to another language if wanted.
- def ... | Implement the Python class `TitleManager` described below.
Class description:
Implement the TitleManager class.
Method signatures and docstrings:
- def get_title(self, page, language, language_fallback=False): Gets the latest content for a particular page and language. Falls back to another language if wanted.
- def ... | d563d912c99f0c138a66d99829d8d0133226894e | <|skeleton|>
class TitleManager:
def get_title(self, page, language, language_fallback=False):
"""Gets the latest content for a particular page and language. Falls back to another language if wanted."""
<|body_0|>
def get_page_slug(self, slug, site=None):
"""Returns the latest slug for... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TitleManager:
def get_title(self, page, language, language_fallback=False):
"""Gets the latest content for a particular page and language. Falls back to another language if wanted."""
try:
title = self.get(language=language, page=page)
return title
except self.m... | the_stack_v2_python_sparse | cms/models/managers.py | DrMeers/django-cms-2.0 | train | 4 | |
bbabd82d84e4648ab72bf455da090758fd3adf5e | [
"auth_list = Auth.objects.all()\nuser = User.objects.select_related().filter(id=id).first()\nreturn render(request, 'django_sample_webpage/edit.html', {'auth_list': auth_list, 'user': user})",
"params = request.data\nname = params['name']\nauth_id = params['auth']\nuser = User.objects.filter(id=id).first()\nuser.... | <|body_start_0|>
auth_list = Auth.objects.all()
user = User.objects.select_related().filter(id=id).first()
return render(request, 'django_sample_webpage/edit.html', {'auth_list': auth_list, 'user': user})
<|end_body_0|>
<|body_start_1|>
params = request.data
name = params['name'... | ManageUserEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManageUserEditView:
def get(self, request, id):
"""編集ページ"""
<|body_0|>
def post(self, request, id):
"""編集"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
auth_list = Auth.objects.all()
user = User.objects.select_related().filter(id=id).first... | stack_v2_sparse_classes_36k_train_026044 | 2,261 | no_license | [
{
"docstring": "編集ページ",
"name": "get",
"signature": "def get(self, request, id)"
},
{
"docstring": "編集",
"name": "post",
"signature": "def post(self, request, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007653 | Implement the Python class `ManageUserEditView` described below.
Class description:
Implement the ManageUserEditView class.
Method signatures and docstrings:
- def get(self, request, id): 編集ページ
- def post(self, request, id): 編集 | Implement the Python class `ManageUserEditView` described below.
Class description:
Implement the ManageUserEditView class.
Method signatures and docstrings:
- def get(self, request, id): 編集ページ
- def post(self, request, id): 編集
<|skeleton|>
class ManageUserEditView:
def get(self, request, id):
"""編集ページ"... | adec9bfc4bb4fa51310164d04430abbbe6f2c94f | <|skeleton|>
class ManageUserEditView:
def get(self, request, id):
"""編集ページ"""
<|body_0|>
def post(self, request, id):
"""編集"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManageUserEditView:
def get(self, request, id):
"""編集ページ"""
auth_list = Auth.objects.all()
user = User.objects.select_related().filter(id=id).first()
return render(request, 'django_sample_webpage/edit.html', {'auth_list': auth_list, 'user': user})
def post(self, request, i... | the_stack_v2_python_sparse | DDD/server/django/project/django_sample_webpage/views.py | itsumura-h/architecture | train | 0 | |
88fb343bfca6642cac6e1470b2edce2348407dd6 | [
"new_kwargs = self.supports.copy()\nnew_kwargs.update(kwargs)\nreturn TernaryRegistrationFactory._check_registered_widget(self, *args, **new_kwargs)",
"if self.supports['equation_physics'] != WidgetType.supports['equation_physics']:\n err_str = \"Factory {0} accepts '{1}' physics while solver {2} supports '{3}... | <|body_start_0|>
new_kwargs = self.supports.copy()
new_kwargs.update(kwargs)
return TernaryRegistrationFactory._check_registered_widget(self, *args, **new_kwargs)
<|end_body_0|>
<|body_start_1|>
if self.supports['equation_physics'] != WidgetType.supports['equation_physics']:
... | Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and returns a instance of the class that best ma... | SolverFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and ret... | stack_v2_sparse_classes_36k_train_026045 | 4,473 | no_license | [
{
"docstring": "Implementation of a basic check to see if arguments match a widget.",
"name": "_check_registered_widget",
"signature": "def _check_registered_widget(self, *args, **kwargs)"
},
{
"docstring": "Register a widget with the factory. If `validation_function` is not specified, tests `Wi... | 2 | stack_v2_sparse_classes_30k_train_014559 | Implement the Python class `SolverFactory` described below.
Class description:
Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered fac... | Implement the Python class `SolverFactory` described below.
Class description:
Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered fac... | 1fb1a80839ceebef12a8d71aa9c295b65b08bac4 | <|skeleton|>
class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SolverFactory:
"""Factory for constant density acoustic wave (time-domain) solvers. Widgets (classes) can be registered with an instance of this class. Arguments to the factory's `__call__` method are then passed to a function specified by the registered factory, which validates the input and returns a instan... | the_stack_v2_python_sparse | pysit/solvers/solver_factory.py | simonlegrand/pysit | train | 1 |
8786eb64ccf232ebd902ef46163f08a0d5cf996e | [
"self.k = k\nself.bigKs = nums\nheapq.heapify(self.bigKs)\nwhile len(self.bigKs) > k:\n heapq.heappop(self.bigKs)",
"if len(self.bigKs) < self.k:\n heapq.heappush(self.bigKs, val)\nelse:\n heapq.heappushpop(self.bigKs, val)\nreturn self.bigKs[0]"
] | <|body_start_0|>
self.k = k
self.bigKs = nums
heapq.heapify(self.bigKs)
while len(self.bigKs) > k:
heapq.heappop(self.bigKs)
<|end_body_0|>
<|body_start_1|>
if len(self.bigKs) < self.k:
heapq.heappush(self.bigKs, val)
else:
heapq.heapp... | KthLargest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.k = k
self.bigKs = nums
heapq.heapify... | stack_v2_sparse_classes_36k_train_026046 | 669 | no_license | [
{
"docstring": ":type k: int :type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, k, nums)"
},
{
"docstring": ":type val: int :rtype: int",
"name": "add",
"signature": "def add(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000525 | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int | Implement the Python class `KthLargest` described below.
Class description:
Implement the KthLargest class.
Method signatures and docstrings:
- def __init__(self, k, nums): :type k: int :type nums: List[int]
- def add(self, val): :type val: int :rtype: int
<|skeleton|>
class KthLargest:
def __init__(self, k, nu... | 6650d4b09de77d42bd8b0b15e0e98b3746116569 | <|skeleton|>
class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
<|body_0|>
def add(self, val):
""":type val: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KthLargest:
def __init__(self, k, nums):
""":type k: int :type nums: List[int]"""
self.k = k
self.bigKs = nums
heapq.heapify(self.bigKs)
while len(self.bigKs) > k:
heapq.heappop(self.bigKs)
def add(self, val):
""":type val: int :rtype: int"""
... | the_stack_v2_python_sparse | algorithm/leetcode/Easy/703. Kth Largest Element in a Stream.py | vicwan/iOS-interview | train | 0 | |
64b9ccc9a378d91f9c4f2ce10be7cb95d950dfb6 | [
"self.debug = debug\nself.n = n\nself.a = a\nself.b = b\nself.x = np.zeros(n + 1, dtype=np.int8)\nsuper().__init__()\nif self.debug:\n print(sys._getframe().f_code.co_name, ':', self.n, self.a, self.b, self.debug)",
"count = self.n\nfor i in range(1, self.n + 1):\n nxt = self.a * i + self.b\n if self.x[i... | <|body_start_0|>
self.debug = debug
self.n = n
self.a = a
self.b = b
self.x = np.zeros(n + 1, dtype=np.int8)
super().__init__()
if self.debug:
print(sys._getframe().f_code.co_name, ':', self.n, self.a, self.b, self.debug)
<|end_body_0|>
<|body_start_1... | A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n : hate a and b in set 10 2 2 : 2x + 2 <= 10 x=1 => 4 remove 1 2 3 5 6 7 8 9 10... | CountAntiSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CountAntiSet:
"""A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n : hate a and b in set 10 2 2 : 2x + 2 ... | stack_v2_sparse_classes_36k_train_026047 | 3,185 | no_license | [
{
"docstring": "get the count of elements to meet the rule. (2) :param n: max number :param a: ax+b :param b: ax+b :param debug: debug mode :return:",
"name": "__init__",
"signature": "def __init__(self, n, a, b, debug=0)"
},
{
"docstring": "get the count of elements to meet the rule. (2)",
... | 3 | stack_v2_sparse_classes_30k_train_010666 | Implement the Python class `CountAntiSet` described below.
Class description:
A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n... | Implement the Python class `CountAntiSet` described below.
Class description:
A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n... | 2fb6246be3bf48eb8ad626217300a1a9328f541a | <|skeleton|>
class CountAntiSet:
"""A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n : hate a and b in set 10 2 2 : 2x + 2 ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CountAntiSet:
"""A class used to get the count of elements url : https://codeup.kr/problem.php?id=2128&rid=0 n, a, b이 주어진다. (1<=n<=10100) (1<=a,b<=103) 집합 A의 임의의 원소 x를 선택했을 때 ax+b가 집합 A에 존재하지 않도록 A의 원소를 빼버리자! 하지만 a, b는 배려심이 많기 때문에 A의 크기를 최대로 하려고 한다. ax+b = n : hate a and b in set 10 2 2 : 2x + 2 <= 10 x=1 => ... | the_stack_v2_python_sparse | 2022/1.py | cheoljoo/problemSolving | train | 1 |
d083183bb2f61aa3975dfd10d04795a0abdf6119 | [
"super(FM, self).__init__()\nself.cate_fea_size = len(cate_fea_uniques)\nself.num_fea_size = num_fea_size\nif self.num_fea_size != 0:\n self.fm_1st_order_dense = nn.Linear(self.num_fea_size, 1)\nself.fm_1st_order_sparse_emb = nn.ModuleList([nn.Embedding(voc_size, 1) for voc_size in cate_fea_uniques])\nself.fm_2n... | <|body_start_0|>
super(FM, self).__init__()
self.cate_fea_size = len(cate_fea_uniques)
self.num_fea_size = num_fea_size
if self.num_fea_size != 0:
self.fm_1st_order_dense = nn.Linear(self.num_fea_size, 1)
self.fm_1st_order_sparse_emb = nn.ModuleList([nn.Embedding(voc_... | FM | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FM:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim"""
<|body_0|>
def forward(self, X_sparse, X_dense=None):
"""X_sparse: sparse_feature [batch_size, sparse_fea... | stack_v2_sparse_classes_36k_train_026048 | 5,121 | permissive | [
{
"docstring": ":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim",
"name": "__init__",
"signature": "def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8)"
},
{
"docstring": "X_sparse: sparse_feature [batch_size, sparse_feature_num] X_dense: dense_... | 2 | null | Implement the Python class `FM` described below.
Class description:
Implement the FM class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim
- def forward(self, X_sparse, X_dense=... | Implement the Python class `FM` described below.
Class description:
Implement the FM class.
Method signatures and docstrings:
- def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8): :param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim
- def forward(self, X_sparse, X_dense=... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class FM:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim"""
<|body_0|>
def forward(self, X_sparse, X_dense=None):
"""X_sparse: sparse_feature [batch_size, sparse_fea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FM:
def __init__(self, cate_fea_uniques, num_fea_size=0, emb_size=8):
""":param cate_fea_uniques: :param num_fea_size: 数字特征 也就是连续特征 :param emb_size: embed_dim"""
super(FM, self).__init__()
self.cate_fea_size = len(cate_fea_uniques)
self.num_fea_size = num_fea_size
if se... | the_stack_v2_python_sparse | PyTorch/dev/others/Widedeep_ID2866_for_PyTorch/FM/model.py | Ascend/ModelZoo-PyTorch | train | 23 | |
a6dcf818128cd531e20806e72c4b7550f7ed97cc | [
"self.truId = truId\nself.dcs_interface_wrapper = dcs_interface_wrapper\nThread.__init__(self)\nPHOSHandler.__init__(self)",
"dcs_interface = self.dcs_interface_wrapper.getDcsInterface()\nmoduleId, rcuId, truId = self.idConverter.GetTruLogicalIDs(self.truId)\nstate = 0\nstate = dcs_interface.ToggleOnOffTru(module... | <|body_start_0|>
self.truId = truId
self.dcs_interface_wrapper = dcs_interface_wrapper
Thread.__init__(self)
PHOSHandler.__init__(self)
<|end_body_0|>
<|body_start_1|>
dcs_interface = self.dcs_interface_wrapper.getDcsInterface()
moduleId, rcuId, truId = self.idConverter.... | Member threading class | __ToggleOnOffThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class __ToggleOnOffThread:
"""Member threading class"""
def __init__(self, truId, dcs_interface_wrapper):
"""init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments"""
<|body_0|>
def run(self):
"""Run the thread"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_026049 | 2,272 | no_license | [
{
"docstring": "init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments",
"name": "__init__",
"signature": "def __init__(self, truId, dcs_interface_wrapper)"
},
{
"docstring": "Run the thread",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001499 | Implement the Python class `__ToggleOnOffThread` described below.
Class description:
Member threading class
Method signatures and docstrings:
- def __init__(self, truId, dcs_interface_wrapper): init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments
- def run(self): Run the thread | Implement the Python class `__ToggleOnOffThread` described below.
Class description:
Member threading class
Method signatures and docstrings:
- def __init__(self, truId, dcs_interface_wrapper): init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments
- def run(self): Run the thread
<|skeleton|>... | e258a33fef1c8719f29434bd59434be61bb912a9 | <|skeleton|>
class __ToggleOnOffThread:
"""Member threading class"""
def __init__(self, truId, dcs_interface_wrapper):
"""init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments"""
<|body_0|>
def run(self):
"""Run the thread"""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class __ToggleOnOffThread:
"""Member threading class"""
def __init__(self, truId, dcs_interface_wrapper):
"""init takes DcsInterfaceThreadWrapper and TRU ID (absolute number) as arguments"""
self.truId = truId
self.dcs_interface_wrapper = dcs_interface_wrapper
Thread.__init__(se... | the_stack_v2_python_sparse | src/phosgui/interface/TruCardHandler.py | odjuvsla/phos_dcs | train | 1 |
872d216d4d4093e5acfbf2d3a9fe5823f2ace938 | [
"name = attrs[source]\nparent = Domain.get_parent_domain(name)\nif parent and parent.account != self.account:\n raise ValidationError(_('Can not create subdomains of other users domains'))\nreturn attrs",
"instance = super(DomainSerializer, self).full_clean(instance)\nif instance and instance.name:\n record... | <|body_start_0|>
name = attrs[source]
parent = Domain.get_parent_domain(name)
if parent and parent.account != self.account:
raise ValidationError(_('Can not create subdomains of other users domains'))
return attrs
<|end_body_0|>
<|body_start_1|>
instance = super(Doma... | Validates if this zone generates a correct zone file | DomainSerializer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DomainSerializer:
"""Validates if this zone generates a correct zone file"""
def clean_name(self, attrs, source):
"""prevent users creating subdomains of other users domains"""
<|body_0|>
def full_clean(self, instance):
"""Checks if everything is consistent"""
... | stack_v2_sparse_classes_36k_train_026050 | 1,708 | permissive | [
{
"docstring": "prevent users creating subdomains of other users domains",
"name": "clean_name",
"signature": "def clean_name(self, attrs, source)"
},
{
"docstring": "Checks if everything is consistent",
"name": "full_clean",
"signature": "def full_clean(self, instance)"
}
] | 2 | null | Implement the Python class `DomainSerializer` described below.
Class description:
Validates if this zone generates a correct zone file
Method signatures and docstrings:
- def clean_name(self, attrs, source): prevent users creating subdomains of other users domains
- def full_clean(self, instance): Checks if everythin... | Implement the Python class `DomainSerializer` described below.
Class description:
Validates if this zone generates a correct zone file
Method signatures and docstrings:
- def clean_name(self, attrs, source): prevent users creating subdomains of other users domains
- def full_clean(self, instance): Checks if everythin... | 9a836f6e252d39dfe3741dd5df4c4a9e67040c1b | <|skeleton|>
class DomainSerializer:
"""Validates if this zone generates a correct zone file"""
def clean_name(self, attrs, source):
"""prevent users creating subdomains of other users domains"""
<|body_0|>
def full_clean(self, instance):
"""Checks if everything is consistent"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DomainSerializer:
"""Validates if this zone generates a correct zone file"""
def clean_name(self, attrs, source):
"""prevent users creating subdomains of other users domains"""
name = attrs[source]
parent = Domain.get_parent_domain(name)
if parent and parent.account != sel... | the_stack_v2_python_sparse | orchestra/contrib/domains/serializers.py | amon-ra/django-orchestra | train | 0 |
504341d1157f1c1efb8a0c9ea69de8df6935f817 | [
"s = '1'\nfor _ in range(n - 1):\n c = s[0]\n cnt = 1\n out = ''\n for i in range(1, len(s)):\n if s[i] == c:\n cnt += 1\n else:\n out = out + str(cnt) + str(c)\n cnt = 1\n c = s[i]\n s = out + str(cnt) + str(c)\nreturn s",
"if n == 1:\n ... | <|body_start_0|>
s = '1'
for _ in range(n - 1):
c = s[0]
cnt = 1
out = ''
for i in range(1, len(s)):
if s[i] == c:
cnt += 1
else:
out = out + str(cnt) + str(c)
cnt ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay_myfirst(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
s = '1'
for _ in range(n - 1):
c = s[0]
... | stack_v2_sparse_classes_36k_train_026051 | 1,390 | no_license | [
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay",
"signature": "def countAndSay(self, n)"
},
{
"docstring": ":type n: int :rtype: str",
"name": "countAndSay_myfirst",
"signature": "def countAndSay_myfirst(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020767 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay_myfirst(self, n): :type n: int :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countAndSay(self, n): :type n: int :rtype: str
- def countAndSay_myfirst(self, n): :type n: int :rtype: str
<|skeleton|>
class Solution:
def countAndSay(self, n):
... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
<|body_0|>
def countAndSay_myfirst(self, n):
""":type n: int :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countAndSay(self, n):
""":type n: int :rtype: str"""
s = '1'
for _ in range(n - 1):
c = s[0]
cnt = 1
out = ''
for i in range(1, len(s)):
if s[i] == c:
cnt += 1
else:
... | the_stack_v2_python_sparse | 38.CountandSay.py | JerryRoc/leetcode | train | 0 | |
30f126b48c2c2c1b925fdb0453832f01e9b22b0a | [
"cls.endpoint = '/api/courseadmin/'\ncls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)\ncls.administrator = AdministratorFactory(user__username='administrator', user__first_name='Name', user__last_name='Surname', about='About administrator')\ncls.supe... | <|body_start_0|>
cls.endpoint = '/api/courseadmin/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.administrator = AdministratorFactory(user__username='administrator', user__first_name='Name', user__last_name='Surname', abou... | Тесты свзи администратора с курсом | CourseAdminTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CourseAdminTestCase:
"""Тесты свзи администратора с курсом"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_admin_list(self):
"""Список связей администраторов с курсами"""
<|body_1|>
def test_get_course_admin(self):
... | stack_v2_sparse_classes_36k_train_026052 | 33,302 | no_license | [
{
"docstring": "Данные для тесткейса",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Список связей администраторов с курсами",
"name": "test_course_admin_list",
"signature": "def test_course_admin_list(self)"
},
{
"docstring": "Получение связи ... | 5 | stack_v2_sparse_classes_30k_train_000544 | Implement the Python class `CourseAdminTestCase` described below.
Class description:
Тесты свзи администратора с курсом
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_admin_list(self): Список связей администраторов с курсами
- def test_get_course_admin(self): Получе... | Implement the Python class `CourseAdminTestCase` described below.
Class description:
Тесты свзи администратора с курсом
Method signatures and docstrings:
- def setUpTestData(cls): Данные для тесткейса
- def test_course_admin_list(self): Список связей администраторов с курсами
- def test_get_course_admin(self): Получе... | 3de0f8eeb4dbf9ec37b17ece0dde51c9e0f381ac | <|skeleton|>
class CourseAdminTestCase:
"""Тесты свзи администратора с курсом"""
def setUpTestData(cls):
"""Данные для тесткейса"""
<|body_0|>
def test_course_admin_list(self):
"""Список связей администраторов с курсами"""
<|body_1|>
def test_get_course_admin(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CourseAdminTestCase:
"""Тесты свзи администратора с курсом"""
def setUpTestData(cls):
"""Данные для тесткейса"""
cls.endpoint = '/api/courseadmin/'
cls.course = CourseFactory(name='Course', description='Description', start='2020-01-05', cost=5000, deleted=False)
cls.admini... | the_stack_v2_python_sparse | education_django/education_app/test_api.py | ilyaignatyev/python-web-otus-ru | train | 0 |
449dfd00b0047311e79c10a0b0eff68e911a5b45 | [
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn None",
"if model._meta.app_label in settings.DATABASE_APPS_MAPPING:\n return settings.DATABASE_APPS_MAPPING[model._meta.app_label]\nreturn None",
"db_obj1 = settings.DATABASE... | <|body_start_0|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS... | A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} | DatabaseRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
def d... | stack_v2_sparse_classes_36k_train_026053 | 2,432 | permissive | [
{
"docstring": "Point all read operations to the specific database. @param model: @type model: @param hints: @type hints: @return: @rtype:",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Point all write operations to the specific database. @param ... | 4 | stack_v2_sparse_classes_30k_train_010557 | Implement the Python class `DatabaseRouter` described below.
Class description:
A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app... | Implement the Python class `DatabaseRouter` described below.
Class description:
A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app... | 9055095cbe796d6d6e2ce744d727ff60e27e09ed | <|skeleton|>
class DatabaseRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
def d... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseRouter:
"""A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}"""
def db_for_read(se... | the_stack_v2_python_sparse | heron/router.py | VForWaTer/vforwater-portal | train | 8 |
8c9532d2bab77dbb2cac80ed5da551c1d1982b5d | [
"panels = []\nfor plug in registry.with_mixin('panel', active=True):\n try:\n panels += plug.render_panels(self, self.request, ctx)\n except Exception:\n log_error(self.request.path)\n logger.error(f\"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'\")\nreturn ... | <|body_start_0|>
panels = []
for plug in registry.with_mixin('panel', active=True):
try:
panels += plug.render_panels(self, self.request, ctx)
except Exception:
log_error(self.request.path)
logger.error(f"Plugin '{plug.slug}' could ... | Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins. | InvenTreePluginViewMixin | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvenTreePluginViewMixin:
"""Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins."""
def get_plugin_panels(self, ctx):
"""Return a list of extra 'plugin panels' associated with this view."""
... | stack_v2_sparse_classes_36k_train_026054 | 1,207 | permissive | [
{
"docstring": "Return a list of extra 'plugin panels' associated with this view.",
"name": "get_plugin_panels",
"signature": "def get_plugin_panels(self, ctx)"
},
{
"docstring": "Add plugin context data to the view.",
"name": "get_context_data",
"signature": "def get_context_data(self, ... | 2 | null | Implement the Python class `InvenTreePluginViewMixin` described below.
Class description:
Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins.
Method signatures and docstrings:
- def get_plugin_panels(self, ctx): Return a list of... | Implement the Python class `InvenTreePluginViewMixin` described below.
Class description:
Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins.
Method signatures and docstrings:
- def get_plugin_panels(self, ctx): Return a list of... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class InvenTreePluginViewMixin:
"""Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins."""
def get_plugin_panels(self, ctx):
"""Return a list of extra 'plugin panels' associated with this view."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InvenTreePluginViewMixin:
"""Custom view mixin which adds context data to the view, based on loaded plugins. This allows rendered pages to be augmented by loaded plugins."""
def get_plugin_panels(self, ctx):
"""Return a list of extra 'plugin panels' associated with this view."""
panels = ... | the_stack_v2_python_sparse | InvenTree/plugin/views.py | inventree/InvenTree | train | 3,077 |
312e650779f1ecb78f813a76e0e883d24ac97c6f | [
"super(L1_Wav_L1_Sp, self).__init__()\nself.window_size = 2048\nhop_size = 441\ncenter = True\npad_mode = 'reflect'\nwindow = 'hann'\nself.stft = STFT(n_fft=self.window_size, hop_length=hop_size, win_length=self.window_size, window=window, center=center, pad_mode=pad_mode, freeze_parameters=True)",
"wav_loss = l1... | <|body_start_0|>
super(L1_Wav_L1_Sp, self).__init__()
self.window_size = 2048
hop_size = 441
center = True
pad_mode = 'reflect'
window = 'hann'
self.stft = STFT(n_fft=self.window_size, hop_length=hop_size, win_length=self.window_size, window=window, center=center,... | L1_Wav_L1_Sp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L1_Wav_L1_Sp:
def __init__(self):
"""L1 loss in the time-domain and L1 loss on the spectrogram."""
<|body_0|>
def __call__(self, output: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:
"""L1 loss in the time-domain and on the spectrogram. Args: output:... | stack_v2_sparse_classes_36k_train_026055 | 2,337 | permissive | [
{
"docstring": "L1 loss in the time-domain and L1 loss on the spectrogram.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "L1 loss in the time-domain and on the spectrogram. Args: output: torch.Tensor target: torch.Tensor Returns: loss: torch.float",
"name": "__cal... | 2 | null | Implement the Python class `L1_Wav_L1_Sp` described below.
Class description:
Implement the L1_Wav_L1_Sp class.
Method signatures and docstrings:
- def __init__(self): L1 loss in the time-domain and L1 loss on the spectrogram.
- def __call__(self, output: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:... | Implement the Python class `L1_Wav_L1_Sp` described below.
Class description:
Implement the L1_Wav_L1_Sp class.
Method signatures and docstrings:
- def __init__(self): L1 loss in the time-domain and L1 loss on the spectrogram.
- def __call__(self, output: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:... | 0a088e1fc852a15d7e558a7e203888de0577dfb1 | <|skeleton|>
class L1_Wav_L1_Sp:
def __init__(self):
"""L1 loss in the time-domain and L1 loss on the spectrogram."""
<|body_0|>
def __call__(self, output: torch.Tensor, target: torch.Tensor, **kwargs) -> torch.Tensor:
"""L1 loss in the time-domain and on the spectrogram. Args: output:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class L1_Wav_L1_Sp:
def __init__(self):
"""L1 loss in the time-domain and L1 loss on the spectrogram."""
super(L1_Wav_L1_Sp, self).__init__()
self.window_size = 2048
hop_size = 441
center = True
pad_mode = 'reflect'
window = 'hann'
self.stft = STFT(n_f... | the_stack_v2_python_sparse | bytesep/losses.py | XinyuanLiu2018/music_source_separation | train | 0 | |
3c7478d4515ee1ac65a0156d1493930f21b5a432 | [
"self.init = True\nif root is None:\n self.root = None\n self.minimum = None\n self.maximum = None\nelse:\n self.root = root\n self.minimum = root\n while self.minimum.left is not None:\n self.minimum = self.minimum.left\n self.maximum = root\n while self.maximum.right is not None:\n ... | <|body_start_0|>
self.init = True
if root is None:
self.root = None
self.minimum = None
self.maximum = None
else:
self.root = root
self.minimum = root
while self.minimum.left is not None:
self.minimum = self.... | BSTIterator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
self.init = True
... | stack_v2_sparse_classes_36k_train_026056 | 2,731 | permissive | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":rtype: bool",
"name": "hasNext",
"signature": "def hasNext(self)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
}
] | 3 | null | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int | Implement the Python class `BSTIterator` described below.
Class description:
Implement the BSTIterator class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def hasNext(self): :rtype: bool
- def next(self): :rtype: int
<|skeleton|>
class BSTIterator:
def __init__(self, root... | 24cf8d5f1831e838ea99f50ce4d8f048bd46c136 | <|skeleton|>
class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def hasNext(self):
""":rtype: bool"""
<|body_1|>
def next(self):
""":rtype: int"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BSTIterator:
def __init__(self, root):
""":type root: TreeNode"""
self.init = True
if root is None:
self.root = None
self.minimum = None
self.maximum = None
else:
self.root = root
self.minimum = root
while ... | the_stack_v2_python_sparse | python/173_binary_search_tree_iterator.py | jixinfeng/leetcode-soln | train | 0 | |
1827159197cf616b96bf28aaf9dde7d297e21408 | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | [summary] Args: tf ([type]): [description] | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k_train_026057 | 1,702 | no_license | [
{
"docstring": "[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1.",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "[summary] Args... | 2 | stack_v2_sparse_classes_30k_train_021634 | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | Implement the Python class `EncoderBlock` described below.
Class description:
[summary] Args: tf ([type]): [description]
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): [summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (... | 5f86dee95f4d1c32014d0d74a368f342ff3ce6f7 | <|skeleton|>
class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""[summary] Args: tf ([type]): [description]"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""[summary] Args: dm ([type]): [description] h ([type]): [description] hidden ([type]): [description] drop_rate (float, optional): [description]. Defaults to 0.1."""
super(Enc... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | d1sd41n/holbertonschool-machine_learning | train | 0 |
92ee5365ebc532914c8dd3d8a20bee06eec3bf95 | [
"if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):\n return 0\ngrid[i][j] = 0\ncount = 1\ncount += self.helper(grid, i - 1, j)\ncount += self.helper(grid, i + 1, j)\ncount += self.helper(grid, i, j - 1)\ncount += self.helper(grid, i, j + 1)\nreturn count",
"max_island = 0\nfor i ... | <|body_start_0|>
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):
return 0
grid[i][j] = 0
count = 1
count += self.helper(grid, i - 1, j)
count += self.helper(grid, i + 1, j)
count += self.helper(grid, i, j - 1)
count += ... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
<|body_0|>
def max_area_island(self, grid: List[List[int]]) -> int:
"""最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_026058 | 3,200 | permissive | [
{
"docstring": "帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数",
"name": "helper",
"signature": "def helper(self, grid: List[List[int]], i: int, j: int) -> int"
},
{
"docstring": "最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿",
"name": "max_area_island",
"signature": "def max_area_island(s... | 2 | stack_v2_sparse_classes_30k_train_013537 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, grid: List[List[int]], i: int, j: int) -> int: 帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数
- def max_area_island(self, grid: List[List[int]]) -> int: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def helper(self, grid: List[List[int]], i: int, j: int) -> int: 帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数
- def max_area_island(self, grid: List[List[int]]) -> int: ... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
<|body_0|>
def max_area_island(self, grid: List[List[int]]) -> int:
"""最大岛屿 Args: grid: 二维数组 Returns: 最大岛屿"""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def helper(self, grid: List[List[int]], i: int, j: int) -> int:
"""帮助类计算岛屿大小 Args: grid: 二维数组 i: 位置1 j: 位置j Returns: 1的个数"""
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] == 0):
return 0
grid[i][j] = 0
count = 1
count +=... | the_stack_v2_python_sparse | src/leetcodepython/array/max_area_island_695.py | zhangyu345293721/leetcode | train | 101 | |
5f80051be4b884c07ebc2c20f3e03e0c79652d87 | [
"self.root = root\n\ndef restore(node, v):\n node.val = v\n if node.left:\n restore(node.left, 2 * v + 1)\n if node.right:\n restore(node.right, 2 * v + 2)\nrestore(self.root, 0)",
"path = []\nwhile target > 0:\n if target % 2 == 0:\n path.append(0)\n target = (target - 2) ... | <|body_start_0|>
self.root = root
def restore(node, v):
node.val = v
if node.left:
restore(node.left, 2 * v + 1)
if node.right:
restore(node.right, 2 * v + 2)
restore(self.root, 0)
<|end_body_0|>
<|body_start_1|>
path ... | FindElements | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FindElements:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def find(self, target):
""":type target: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.root = root
def restore(node, v):
node.... | stack_v2_sparse_classes_36k_train_026059 | 1,551 | no_license | [
{
"docstring": ":type root: TreeNode",
"name": "__init__",
"signature": "def __init__(self, root)"
},
{
"docstring": ":type target: int :rtype: bool",
"name": "find",
"signature": "def find(self, target)"
}
] | 2 | null | Implement the Python class `FindElements` described below.
Class description:
Implement the FindElements class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def find(self, target): :type target: int :rtype: bool | Implement the Python class `FindElements` described below.
Class description:
Implement the FindElements class.
Method signatures and docstrings:
- def __init__(self, root): :type root: TreeNode
- def find(self, target): :type target: int :rtype: bool
<|skeleton|>
class FindElements:
def __init__(self, root):
... | 80e44f4e9d3a5b592fdebe0bf16d1df54e99991e | <|skeleton|>
class FindElements:
def __init__(self, root):
""":type root: TreeNode"""
<|body_0|>
def find(self, target):
""":type target: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FindElements:
def __init__(self, root):
""":type root: TreeNode"""
self.root = root
def restore(node, v):
node.val = v
if node.left:
restore(node.left, 2 * v + 1)
if node.right:
restore(node.right, 2 * v + 2)
... | the_stack_v2_python_sparse | Python/1261 - Find Elements in a Contaminated Binary Tree/1261_find-elements-in-a-contaminated-binary-tree.py | aptend/leetcode-rua | train | 2 | |
c09ef3458f1f9e06ca9efa92fdb9695055c48ba4 | [
"general_content = \"\\n\\n <p>What's a Vinely Taste Party? Think of it as learning through drinking.\\n It's part wine tasting. Part personality test. And part...well...party.</p>\\n\\n <p>The wines you'll sample will give us an idea of your personal taste.\\n The flavors you enjoy and ... | <|body_start_0|>
general_content = "\n\n <p>What's a Vinely Taste Party? Think of it as learning through drinking.\n It's part wine tasting. Part personality test. And part...well...party.</p>\n\n <p>The wines you'll sample will give us an idea of your personal taste.\n The flavors y... | Migration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
general_content = "\n\n <p>What's a Vinely ... | stack_v2_sparse_classes_36k_train_026060 | 2,834 | no_license | [
{
"docstring": "Write your forwards methods here.",
"name": "forwards",
"signature": "def forwards(self, orm)"
},
{
"docstring": "Write your backwards methods here.",
"name": "backwards",
"signature": "def backwards(self, orm)"
}
] | 2 | null | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here. | Implement the Python class `Migration` described below.
Class description:
Implement the Migration class.
Method signatures and docstrings:
- def forwards(self, orm): Write your forwards methods here.
- def backwards(self, orm): Write your backwards methods here.
<|skeleton|>
class Migration:
def forwards(self,... | c5c7d8a0b1a297e07302870017d3fb03c5dbb009 | <|skeleton|>
class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
<|body_0|>
def backwards(self, orm):
"""Write your backwards methods here."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Migration:
def forwards(self, orm):
"""Write your forwards methods here."""
general_content = "\n\n <p>What's a Vinely Taste Party? Think of it as learning through drinking.\n It's part wine tasting. Part personality test. And part...well...party.</p>\n\n <p>The wines you'... | the_stack_v2_python_sparse | cms/migrations/0013_add_rsvp_template.py | RSV3/nuvine | train | 0 | |
19883dd9a1c672c4e518fa79716c8c1706010cdd | [
"self.cache = {}\nself.new = {}\nself.loop = loop\nself.keytransform = keytransform\nself.keycalc = keycalc",
"key = self.keytransform(key)\nif key not in self.cache:\n coro = self.keycalc(key)\n self.cache[key] = self.new[key] = self.loop.create_task(coro)\nreturn self.cache[key]",
"fut = asyncio.Future(... | <|body_start_0|>
self.cache = {}
self.new = {}
self.loop = loop
self.keytransform = keytransform
self.keycalc = keycalc
<|end_body_0|>
<|body_start_1|>
key = self.keytransform(key)
if key not in self.cache:
coro = self.keycalc(key)
self.ca... | Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key. | EvaluationCache | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EvaluationCache:
"""Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key."""
def __init__(self, loop, keycalc, keytransform):
... | stack_v2_sparse_classes_36k_train_026061 | 5,512 | permissive | [
{
"docstring": "Initialize an EvaluationCache.",
"name": "__init__",
"signature": "def __init__(self, loop, keycalc, keytransform)"
},
{
"docstring": "Get the future associated to the key.",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": "Associate a key to a ... | 3 | null | Implement the Python class `EvaluationCache` described below.
Class description:
Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key.
Method signatures... | Implement the Python class `EvaluationCache` described below.
Class description:
Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key.
Method signatures... | d7b12c15453079e1a2c4fdae611c5f741574363d | <|skeleton|>
class EvaluationCache:
"""Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key."""
def __init__(self, loop, keycalc, keytransform):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EvaluationCache:
"""Key/value store where keys are associated to Futures. Attributes: cache: The cache. loop: The InferenceLoop for async evaluation. keycalc: An async function that takes a key and returns the value associated to that key."""
def __init__(self, loop, keycalc, keytransform):
"""In... | the_stack_v2_python_sparse | myia/abstract/ref.py | breuleux/myia | train | 1 |
dd18a20d5f2ac8061bc07268997a5c1441b83407 | [
"mod = 10 ** 9 + 7\nself.str_case = tr_case\ncur = 0\nfor ch_ar in tr_case:\n tmp = [i for i in self.alpha_count[-1]]\n tmp[self.alpha.find(ch_ar)] += 1\n self.alpha_count.append(tmp)\n cur ^= 1 << self.alpha.find(ch_ar)\n self.odds.append(cur)\nfor i in range(2, len(tr_case) + 1):\n self.inv.appe... | <|body_start_0|>
mod = 10 ** 9 + 7
self.str_case = tr_case
cur = 0
for ch_ar in tr_case:
tmp = [i for i in self.alpha_count[-1]]
tmp[self.alpha.find(ch_ar)] += 1
self.alpha_count.append(tmp)
cur ^= 1 << self.alpha.find(ch_ar)
se... | docstring | MaximumPalindromes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaximumPalindromes:
"""docstring"""
def initialize(self, tr_case):
"""docstring"""
<|body_0|>
def solution(self, left, right):
"""docstring"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mod = 10 ** 9 + 7
self.str_case = tr_case
... | stack_v2_sparse_classes_36k_train_026062 | 1,674 | no_license | [
{
"docstring": "docstring",
"name": "initialize",
"signature": "def initialize(self, tr_case)"
},
{
"docstring": "docstring",
"name": "solution",
"signature": "def solution(self, left, right)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000795 | Implement the Python class `MaximumPalindromes` described below.
Class description:
docstring
Method signatures and docstrings:
- def initialize(self, tr_case): docstring
- def solution(self, left, right): docstring | Implement the Python class `MaximumPalindromes` described below.
Class description:
docstring
Method signatures and docstrings:
- def initialize(self, tr_case): docstring
- def solution(self, left, right): docstring
<|skeleton|>
class MaximumPalindromes:
"""docstring"""
def initialize(self, tr_case):
... | 9e94c76685cdd2bd58c5237ba11a6c3166fa499b | <|skeleton|>
class MaximumPalindromes:
"""docstring"""
def initialize(self, tr_case):
"""docstring"""
<|body_0|>
def solution(self, left, right):
"""docstring"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MaximumPalindromes:
"""docstring"""
def initialize(self, tr_case):
"""docstring"""
mod = 10 ** 9 + 7
self.str_case = tr_case
cur = 0
for ch_ar in tr_case:
tmp = [i for i in self.alpha_count[-1]]
tmp[self.alpha.find(ch_ar)] += 1
s... | the_stack_v2_python_sparse | strings/medium/maximum_palindromes.py | ygretharekar/hr_py | train | 0 |
acbff3c9dd0accff2912f625530237535b9357c4 | [
"cnt = 0\ni = len(nums) - 1\nwhile i >= 0:\n if nums[i] == k:\n cnt += 1\n for j in range(i - 1, -1, -1):\n nums[i] += nums[j]\n if nums[i] == k:\n cnt += 1\n i -= 1\nreturn cnt",
"preSum = [0 for _ in range(len(nums) + 1)]\nfor i in range(len(nums)):\n preSum[i + 1] = ... | <|body_start_0|>
cnt = 0
i = len(nums) - 1
while i >= 0:
if nums[i] == k:
cnt += 1
for j in range(i - 1, -1, -1):
nums[i] += nums[j]
if nums[i] == k:
cnt += 1
i -= 1
return cnt
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cnt = 0
... | stack_v2_sparse_classes_36k_train_026063 | 1,798 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySum",
"signature": "def subarraySum(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySum2",
"signature": "def subarraySum2(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum2(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum2(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|>
cla... | 837957ea22aa07ce28a6c23ea0419bd2011e1f88 | <|skeleton|>
class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum2(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
cnt = 0
i = len(nums) - 1
while i >= 0:
if nums[i] == k:
cnt += 1
for j in range(i - 1, -1, -1):
nums[i] += nums[j]
... | the_stack_v2_python_sparse | fuck/子数组和为K问题.py | 2226171237/Algorithmpractice | train | 0 | |
f18bfd29abecbc59d9fd03c8dca206c3a52890b0 | [
"from collections import deque\nself.dq = deque()\nself.size = float(size)\nself.last = None",
"if len(self.dq) == self.size:\n out = self.dq.popleft()\n self.dq.append(val)\n self.last += float(val - out) / self.size\nelse:\n self.dq.append(val)\n if self.last is None:\n self.last = float(v... | <|body_start_0|>
from collections import deque
self.dq = deque()
self.size = float(size)
self.last = None
<|end_body_0|>
<|body_start_1|>
if len(self.dq) == self.size:
out = self.dq.popleft()
self.dq.append(val)
self.last += float(val - out) /... | 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|>
from collections import deque
... | stack_v2_sparse_classes_36k_train_026064 | 924 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | null | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
Implement the MovingAverage class.
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
... | d6fac85a94a7188e93d4e202e67b6485562d12bd | <|skeleton|>
class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
from collections import deque
self.dq = deque()
self.size = float(size)
self.last = None
def next(self, val):
""":type val: int :rtype: float"""
if l... | the_stack_v2_python_sparse | lc346.py | GeorgyZhou/Leetcode-Problem | train | 0 | |
54c9cfcfd170d0c69bc33d4df3ea4fed5e7d8245 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.iosVppEBook'.casefold():\n from .ios_vpp... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | An abstract class containing the base properties for Managed eBook. | ManagedEBook | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedEBook:
"""An abstract class containing the base properties for Managed eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The par... | stack_v2_sparse_classes_36k_train_026065 | 6,821 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ManagedEBook",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_value(... | 3 | stack_v2_sparse_classes_30k_train_012072 | Implement the Python class `ManagedEBook` described below.
Class description:
An abstract class containing the base properties for Managed eBook.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedEBook: Creates a new instance of the appropriate cla... | Implement the Python class `ManagedEBook` described below.
Class description:
An abstract class containing the base properties for Managed eBook.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedEBook: Creates a new instance of the appropriate cla... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class ManagedEBook:
"""An abstract class containing the base properties for Managed eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManagedEBook:
"""An abstract class containing the base properties for Managed eBook."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> ManagedEBook:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to us... | the_stack_v2_python_sparse | msgraph/generated/models/managed_e_book.py | microsoftgraph/msgraph-sdk-python | train | 135 |
09acf4bd8667cd25a043564452c6daf34b567b14 | [
"m, n = pic_dt.shape\nif resize is None:\n n_new, m_new = (np.round(x_scale * n).astype(int), np.round(y_scale * m).astype(int))\nelse:\n n_new, m_new = resize\nfx, fy = (n / n_new, m / m_new)\nidx_x_orign = np.array(list(range(n_new)) * m_new).reshape(m_new, n_new)\nidx_y_orign = np.repeat(list(range(m_new))... | <|body_start_0|>
m, n = pic_dt.shape
if resize is None:
n_new, m_new = (np.round(x_scale * n).astype(int), np.round(y_scale * m).astype(int))
else:
n_new, m_new = resize
fx, fy = (n / n_new, m / m_new)
idx_x_orign = np.array(list(range(n_new)) * m_new).res... | 图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR) | pic_scale | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic... | stack_v2_sparse_classes_36k_train_026066 | 5,079 | no_license | [
{
"docstring": "最近邻插值(图片 m * n * 图层) param pic_dt: 为一个图片的一个图层的数据 len(pic_dt) == 2 param resize: set (长, 宽) param x_scale: float 长度缩放大小 param y_scale: float 宽带缩放大小",
"name": "INTER_NEAREST",
"signature": "def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None)"
},
{
"docstring": "找位置,... | 4 | stack_v2_sparse_classes_30k_train_008144 | Implement the Python class `pic_scale` described below.
Class description:
图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)
Method signatures and docstrings:
- def INTER_NEAREST(self, pic_dt, resize, x_... | Implement the Python class `pic_scale` described below.
Class description:
图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)
Method signatures and docstrings:
- def INTER_NEAREST(self, pic_dt, resize, x_... | 122c43776c2b10bd5f9b9a299bdbf9739173ad46 | <|skeleton|>
class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pic_scale:
"""图片缩放:包含两个方法 INTER_NEAREST 最近邻插值 INTER_LINEAR 双线性插值 例子: pic_sc = pic_scale() pic_sc.pic_resize(img_dt, resize, fx=None, fy=None, interpolation = pic_sc.INTER_LINEAR)"""
def INTER_NEAREST(self, pic_dt, resize, x_scale=None, y_scale=None):
"""最近邻插值(图片 m * n * 图层) param pic_dt: 为一个图片的一个... | the_stack_v2_python_sparse | DataWhale计算机视觉入门/图片缩放.py | scchy/My_Learn | train | 4 |
357b533e107f8c32eaa948f760132bee3fc465b9 | [
"self.is_max_snapshots_config_enabled = is_max_snapshots_config_enabled\nself.is_max_space_config_enabled = is_max_space_config_enabled\nself.storage_array_snapshot_max_space_config = storage_array_snapshot_max_space_config\nself.storage_array_snapshot_throttling_policies = storage_array_snapshot_throttling_policie... | <|body_start_0|>
self.is_max_snapshots_config_enabled = is_max_snapshots_config_enabled
self.is_max_space_config_enabled = is_max_space_config_enabled
self.storage_array_snapshot_max_space_config = storage_array_snapshot_max_space_config
self.storage_array_snapshot_throttling_policies = ... | Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or not. is_max_space_config_enabled (bool): Specifies if the storage array snapshot max space config is... | StorageArraySnapshotConfigParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StorageArraySnapshotConfigParams:
"""Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or not. is_max_space_config_enabled (bool):... | stack_v2_sparse_classes_36k_train_026067 | 4,007 | permissive | [
{
"docstring": "Constructor for the StorageArraySnapshotConfigParams class",
"name": "__init__",
"signature": "def __init__(self, is_max_snapshots_config_enabled=None, is_max_space_config_enabled=None, storage_array_snapshot_max_space_config=None, storage_array_snapshot_throttling_policies=None)"
},
... | 2 | null | Implement the Python class `StorageArraySnapshotConfigParams` described below.
Class description:
Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or n... | Implement the Python class `StorageArraySnapshotConfigParams` described below.
Class description:
Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or n... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class StorageArraySnapshotConfigParams:
"""Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or not. is_max_space_config_enabled (bool):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StorageArraySnapshotConfigParams:
"""Implementation of the 'StorageArraySnapshotConfigParams' model. TODO: type description here. Attributes: is_max_snapshots_config_enabled (bool): Specifies if the storage array snapshot max snapshots config is enabled or not. is_max_space_config_enabled (bool): Specifies if... | the_stack_v2_python_sparse | cohesity_management_sdk/models/storage_array_snapshot_config_params.py | cohesity/management-sdk-python | train | 24 |
5ead6f9fe5b9254ea69c112ca585fcff2db806bf | [
"self.reader = reader\nself.version = version\nself.colids = [c.colid for c in schema]\nself.is_keyed = is_keyed",
"if self.reader is not None:\n self.reader.close()\n self.reader = None",
"\"\"\"Return next row from the archive reader.\"\"\"\nrow = self.reader.next()\nwhile row is not None:\n if row.t... | <|body_start_0|>
self.reader = reader
self.version = version
self.colids = [c.colid for c in schema]
self.is_keyed = is_keyed
<|end_body_0|>
<|body_start_1|>
if self.reader is not None:
self.reader.close()
self.reader = None
<|end_body_1|>
<|body_start_2... | Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times. | SnapshotIterator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnapshotIterator:
"""Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times."""
def __init__(self, reader: ArchiveReader, version: int, schema: List[Column], is_keyed: bool):
"""Initial... | stack_v2_sparse_classes_36k_train_026068 | 5,788 | permissive | [
{
"docstring": "Initialize the archive reader. Parameters ---------- reader: histore.archive.reader.ArchiveReader Reader for a dataset archive. version: int Unique version identifier for the read snapshot. schema: list of histore.document.schema.Column Schema for the read snapshot. is_keyed: bool Flag indicatin... | 3 | stack_v2_sparse_classes_30k_test_000019 | Implement the Python class `SnapshotIterator` described below.
Class description:
Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times.
Method signatures and docstrings:
- def __init__(self, reader: ArchiveReader, ver... | Implement the Python class `SnapshotIterator` described below.
Class description:
Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times.
Method signatures and docstrings:
- def __init__(self, reader: ArchiveReader, ver... | d600052514a1c5f672137f76a6e1388184b17cd4 | <|skeleton|>
class SnapshotIterator:
"""Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times."""
def __init__(self, reader: ArchiveReader, version: int, schema: List[Column], is_keyed: bool):
"""Initial... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnapshotIterator:
"""Reader for data streams. Provides the functionality to open the stream for reading. Dataset reader should be able to read the same dataset multiple times."""
def __init__(self, reader: ArchiveReader, version: int, schema: List[Column], is_keyed: bool):
"""Initialize the archi... | the_stack_v2_python_sparse | histore/archive/reader.py | Sandy4321/histore | train | 0 |
5d2a5d06f2f3e78da8f0081e883233e4fcbbfa94 | [
"UserModel = get_user_model()\ntry:\n user = UserModel.objects.get(email=username)\n if user.check_password(password):\n return user\nexcept UserModel.DoesNotExist:\n try:\n user = UserModel.objects.get(username=username)\n if user.check_password(password):\n return user\n ... | <|body_start_0|>
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
try:
user = UserModel.objects.get(username=username)
... | Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function | EmailAuthBackend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function"""
def authenticate(self, username=None, password=None):
... | stack_v2_sparse_classes_36k_train_026069 | 1,317 | no_license | [
{
"docstring": "Authenticate a user based on email address as the user name.",
"name": "authenticate",
"signature": "def authenticate(self, username=None, password=None)"
},
{
"docstring": "Get a User object from the user_id.",
"name": "get_user",
"signature": "def get_user(self, user_id... | 2 | null | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function
Method signatures and docst... | Implement the Python class `EmailAuthBackend` described below.
Class description:
Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function
Method signatures and docst... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function"""
def authenticate(self, username=None, password=None):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EmailAuthBackend:
"""Email Authentication Backend Allows a user to sign in using an email/password pair, then check a username/password pair if email failed **注意** 此类不能编译,因为 django.contrib.auth 中会判断此类的类型,编译之后无法识别为 python function"""
def authenticate(self, username=None, password=None):
"""Authent... | the_stack_v2_python_sparse | utils/backends.py | sundw2015/841 | train | 4 |
54acdaa8bbe5d76ce043cde5f69f451b08332260 | [
"if not email:\n raise ValueError('Users must have an email address')\nvalidate_email(email)\nvalidate_password(password)\nuser = self.model(email=self.normalize_email(email))\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password)\nuser.is_admi... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
validate_email(email)
validate_password(password)
user = self.model(email=self.normalize_email(email))
user.set_password(password)
user.save(using=self._db)
return user... | CustomUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomUserManager:
def create_user(self, email: str, password: str=None) -> User:
"""Creates, saves and returns a User. Args: email: email field value password: password field value Returns: new User instance"""
<|body_0|>
def create_superuser(self, email: str, password: str... | stack_v2_sparse_classes_36k_train_026070 | 1,325 | no_license | [
{
"docstring": "Creates, saves and returns a User. Args: email: email field value password: password field value Returns: new User instance",
"name": "create_user",
"signature": "def create_user(self, email: str, password: str=None) -> User"
},
{
"docstring": "Same as create_user(), but sets is_... | 2 | stack_v2_sparse_classes_30k_train_017387 | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email: str, password: str=None) -> User: Creates, saves and returns a User. Args: email: email field value password: password field value ... | Implement the Python class `CustomUserManager` described below.
Class description:
Implement the CustomUserManager class.
Method signatures and docstrings:
- def create_user(self, email: str, password: str=None) -> User: Creates, saves and returns a User. Args: email: email field value password: password field value ... | 755975666cdb0de43a6198040297157c86c16137 | <|skeleton|>
class CustomUserManager:
def create_user(self, email: str, password: str=None) -> User:
"""Creates, saves and returns a User. Args: email: email field value password: password field value Returns: new User instance"""
<|body_0|>
def create_superuser(self, email: str, password: str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomUserManager:
def create_user(self, email: str, password: str=None) -> User:
"""Creates, saves and returns a User. Args: email: email field value password: password field value Returns: new User instance"""
if not email:
raise ValueError('Users must have an email address')
... | the_stack_v2_python_sparse | app/users/managers.py | vladhoi/labs-management | train | 1 | |
290e8cd268006000cee9af28736b19d9a4ad31e6 | [
"super(Weapon, self).at_object_creation()\nself.db.hit = 0.4\nself.db.parry = 0.8\nself.db.damage = 8.0\nself.db.magic = False\nself.cmdset.add_default(CmdSetWeapon, permanent=True)",
"if self.location.has_player and self.home == self.location:\n self.location.msg_contents('%s suddenly and magically fades into... | <|body_start_0|>
super(Weapon, self).at_object_creation()
self.db.hit = 0.4
self.db.parry = 0.8
self.db.damage = 8.0
self.db.magic = False
self.cmdset.add_default(CmdSetWeapon, permanent=True)
<|end_body_0|>
<|body_start_1|>
if self.location.has_player and self.h... | This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10) | Weapon | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Weapon:
"""This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10)"""
def at_object_creation(self):
"""Called at first creation of the ... | stack_v2_sparse_classes_36k_train_026071 | 36,948 | permissive | [
{
"docstring": "Called at first creation of the object",
"name": "at_object_creation",
"signature": "def at_object_creation(self)"
},
{
"docstring": "When reset, the weapon is simply deleted, unless it has a place to return to.",
"name": "reset",
"signature": "def reset(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004027 | Implement the Python class `Weapon` described below.
Class description:
This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10)
Method signatures and docstrings:
- def a... | Implement the Python class `Weapon` described below.
Class description:
This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10)
Method signatures and docstrings:
- def a... | 4515b6b569f919b18223ff2b241ea70f3e787e1e | <|skeleton|>
class Weapon:
"""This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10)"""
def at_object_creation(self):
"""Called at first creation of the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Weapon:
"""This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10)"""
def at_object_creation(self):
"""Called at first creation of the object"""
... | the_stack_v2_python_sparse | contrib/tutorial_world/objects.py | mergederg/deuterium | train | 1 |
eb99ccc2e8cefce621198e1d43cee86db5ef1454 | [
"queryset = DistanceType.objects.all()\nserializer = DistanceTypeSerializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = StreetType.objects.all()\nserializer = StreetTypeSerializer(queryset, many=True)\nreturn Response(serializer.data)",
"queryset = LocationType.objects.all()\nserializer... | <|body_start_0|>
queryset = DistanceType.objects.all()
serializer = DistanceTypeSerializer(queryset, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = StreetType.objects.all()
serializer = StreetTypeSerializer(queryset, many=True)
ret... | API for working with information related to hotels (Hotel) | HotelViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
<|body_0|>
def streets(self, request):
"""Getting a list of "street types" :param request... | stack_v2_sparse_classes_36k_train_026072 | 7,291 | no_license | [
{
"docstring": "Getting a list of \"distance types\" :param request: :return:",
"name": "distance",
"signature": "def distance(self, request)"
},
{
"docstring": "Getting a list of \"street types\" :param request: :return:",
"name": "streets",
"signature": "def streets(self, request)"
}... | 5 | null | Implement the Python class `HotelViewSet` described below.
Class description:
API for working with information related to hotels (Hotel)
Method signatures and docstrings:
- def distance(self, request): Getting a list of "distance types" :param request: :return:
- def streets(self, request): Getting a list of "street ... | Implement the Python class `HotelViewSet` described below.
Class description:
API for working with information related to hotels (Hotel)
Method signatures and docstrings:
- def distance(self, request): Getting a list of "distance types" :param request: :return:
- def streets(self, request): Getting a list of "street ... | bead0c1d30e5772377649e852f9d2be6b0cc9e26 | <|skeleton|>
class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
<|body_0|>
def streets(self, request):
"""Getting a list of "street types" :param request... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HotelViewSet:
"""API for working with information related to hotels (Hotel)"""
def distance(self, request):
"""Getting a list of "distance types" :param request: :return:"""
queryset = DistanceType.objects.all()
serializer = DistanceTypeSerializer(queryset, many=True)
retu... | the_stack_v2_python_sparse | src/apps/hotels/viewsets.py | oleg-developer/booking-system | train | 0 |
b4645782c895d11c598933e90239c7bf38eb17f4 | [
"self.name = name\nself.description = description\nself.installments = installments\nself.statement_descriptor = statement_descriptor\nself.currency = currency\nself.interval = interval\nself.interval_count = interval_count\nself.payment_methods = payment_methods\nself.billing_type = billing_type\nself.status = sta... | <|body_start_0|>
self.name = name
self.description = description
self.installments = installments
self.statement_descriptor = statement_descriptor
self.currency = currency
self.interval = interval
self.interval_count = interval_count
self.payment_methods =... | Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card's statement currency (string): Currency inter... | UpdatePlanRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdatePlanRequest:
"""Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card'... | stack_v2_sparse_classes_36k_train_026073 | 5,096 | permissive | [
{
"docstring": "Constructor for the UpdatePlanRequest class",
"name": "__init__",
"signature": "def __init__(self, name=None, description=None, installments=None, statement_descriptor=None, currency=None, interval=None, interval_count=None, payment_methods=None, billing_type=None, status=None, shippable... | 2 | stack_v2_sparse_classes_30k_train_000841 | Implement the Python class `UpdatePlanRequest` described below.
Class description:
Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text... | Implement the Python class `UpdatePlanRequest` described below.
Class description:
Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class UpdatePlanRequest:
"""Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card'... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdatePlanRequest:
"""Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card's statement c... | the_stack_v2_python_sparse | mundiapi/models/update_plan_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
808050a7d7aa1a29ce5adfb6d591df29b0dbf7ab | [
"super(GLResizeVisitor, self).__init__()\nself._width = width\nself._height = height",
"adapter = GLNodeAdapter.adapter(node)\nif adapter:\n adapter.resize_enter(self._width, self._height)",
"adapter = GLNodeAdapter.adapter(node)\nif adapter:\n adapter.resize_enter(self._width, self._height)"
] | <|body_start_0|>
super(GLResizeVisitor, self).__init__()
self._width = width
self._height = height
<|end_body_0|>
<|body_start_1|>
adapter = GLNodeAdapter.adapter(node)
if adapter:
adapter.resize_enter(self._width, self._height)
<|end_body_1|>
<|body_start_2|>
... | GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation | GLResizeVisitor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GLResizeVisitor:
"""GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation"""
def __init__(self, width, height):
"""Constructor. @param width The current width of the viewport. @param height The current height of the viewport."""
<|bo... | stack_v2_sparse_classes_36k_train_026074 | 3,263 | no_license | [
{
"docstring": "Constructor. @param width The current width of the viewport. @param height The current height of the viewport.",
"name": "__init__",
"signature": "def __init__(self, width, height)"
},
{
"docstring": "Overrides the AbstractSceneGraphVisitor's _enter method for an OpenGL Resize op... | 3 | stack_v2_sparse_classes_30k_train_004550 | Implement the Python class `GLResizeVisitor` described below.
Class description:
GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation
Method signatures and docstrings:
- def __init__(self, width, height): Constructor. @param width The current width of the viewport. @param h... | Implement the Python class `GLResizeVisitor` described below.
Class description:
GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation
Method signatures and docstrings:
- def __init__(self, width, height): Constructor. @param width The current width of the viewport. @param h... | 68598875117ded3263fbbb8d02a9191183b25d6b | <|skeleton|>
class GLResizeVisitor:
"""GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation"""
def __init__(self, width, height):
"""Constructor. @param width The current width of the viewport. @param height The current height of the viewport."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GLResizeVisitor:
"""GLSceneGraphVisitor implementes a Scene Graph Traversal object in for an OpenGL Resize operation"""
def __init__(self, width, height):
"""Constructor. @param width The current width of the viewport. @param height The current height of the viewport."""
super(GLResizeVis... | the_stack_v2_python_sparse | kousen/gl/gltraversal.py | dbarsam/kousen | train | 1 |
919db12dde6d6740bb4331a91b54bcc197fc0e1a | [
"if len(grid) == 0:\n return 0\nm = len(grid)\nn = len(grid[0])\ndp = [[0] * n for _ in range(m)]\ndp[0][0] = grid[0][0]\nfor i in range(1, m):\n dp[i][0] = dp[i - 1][0] + grid[i][0]\nfor j in range(1, n):\n dp[0][j] = dp[0][j - 1] + grid[0][j]\nfor i in range(1, m):\n for j in range(1, n):\n dp[... | <|body_start_0|>
if len(grid) == 0:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = dp[i - 1][0] + grid[i][0]
for j in range(1, n):
dp[0][j] = dp[0]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid) -> int:
"""动态规划,时间和空间复杂度为O(m*n),二维数组"""
<|body_0|>
def minPathSum2(self, grid):
"""优化动态规划,时间复杂度为O(m*n), 空间复杂度为0(n), 一维数组"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(grid) == 0:
return 0
... | stack_v2_sparse_classes_36k_train_026075 | 2,129 | no_license | [
{
"docstring": "动态规划,时间和空间复杂度为O(m*n),二维数组",
"name": "minPathSum",
"signature": "def minPathSum(self, grid) -> int"
},
{
"docstring": "优化动态规划,时间复杂度为O(m*n), 空间复杂度为0(n), 一维数组",
"name": "minPathSum2",
"signature": "def minPathSum2(self, grid)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000870 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid) -> int: 动态规划,时间和空间复杂度为O(m*n),二维数组
- def minPathSum2(self, grid): 优化动态规划,时间复杂度为O(m*n), 空间复杂度为0(n), 一维数组 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid) -> int: 动态规划,时间和空间复杂度为O(m*n),二维数组
- def minPathSum2(self, grid): 优化动态规划,时间复杂度为O(m*n), 空间复杂度为0(n), 一维数组
<|skeleton|>
class Solution:
def minPathSu... | 13e7ec9fe7a92ab13b247bd4edeb1ada5de81a08 | <|skeleton|>
class Solution:
def minPathSum(self, grid) -> int:
"""动态规划,时间和空间复杂度为O(m*n),二维数组"""
<|body_0|>
def minPathSum2(self, grid):
"""优化动态规划,时间复杂度为O(m*n), 空间复杂度为0(n), 一维数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid) -> int:
"""动态规划,时间和空间复杂度为O(m*n),二维数组"""
if len(grid) == 0:
return 0
m = len(grid)
n = len(grid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = dp[i -... | the_stack_v2_python_sparse | Algorithms/64_Minimum_Path_Sum/Minimum_Path_Sum.py | lirui-ML/my_leetcode | train | 1 | |
96be9e83e6972ff942dfad7565405838ff82f318 | [
"st = []\nr = [0 for _ in T]\ni = len(T) - 1\nwhile i >= 0:\n while st and T[st[-1]] <= T[i]:\n st.pop()\n if st:\n r[i] = st[-1] - i\n st.append(i)\n i -= 1\nreturn r",
"st = []\nr = [0 for _ in T]\nfor i, t in enumerate(T):\n while st and T[st[-1]] < t:\n prev = st.pop()\n ... | <|body_start_0|>
st = []
r = [0 for _ in T]
i = len(T) - 1
while i >= 0:
while st and T[st[-1]] <= T[i]:
st.pop()
if st:
r[i] = st[-1] - i
st.append(i)
i -= 1
return r
<|end_body_0|>
<|body_start_1|>... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
"""从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈"""
<|body_0|>
def dailyTemperatures2(self, T):
"""从左到右的单调栈,如果当前元素比左边的大,说明肯定是第一个大的 因为如果之前有比栈里面的元素大的,早就出栈了"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_36k_train_026076 | 1,080 | no_license | [
{
"docstring": "从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈",
"name": "dailyTemperatures",
"signature": "def dailyTemperatures(self, T)"
},
{
"docstring": "从左到右的单调栈,如果当前元素比左边的大,说明肯定是第一个大的 因为如果之前有比栈里面的元素大的,早就出栈了",
"name": "dailyTemperatures2",
"signature": "def dai... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): 从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈
- def dailyTemperatures2(self, T): 从左到右的单调栈,如果当前元素比左边的大,说明肯定是第一个大的 因为如果之前有比栈里面... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def dailyTemperatures(self, T): 从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈
- def dailyTemperatures2(self, T): 从左到右的单调栈,如果当前元素比左边的大,说明肯定是第一个大的 因为如果之前有比栈里面... | f563dbf35878808491f03281889c9a0800be7d90 | <|skeleton|>
class Solution:
def dailyTemperatures(self, T):
"""从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈"""
<|body_0|>
def dailyTemperatures2(self, T):
"""从左到右的单调栈,如果当前元素比左边的大,说明肯定是第一个大的 因为如果之前有比栈里面的元素大的,早就出栈了"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def dailyTemperatures(self, T):
"""从右至左的单调栈,栈内元素从底到顶递减 每次遇见一个新元素将比自己小的元素pop出来, 这样就知道了右边第一个比自己大的,然后自己入栈"""
st = []
r = [0 for _ in T]
i = len(T) - 1
while i >= 0:
while st and T[st[-1]] <= T[i]:
st.pop()
if st:
... | the_stack_v2_python_sparse | leetcode/739.每日温度/main.py | lee3164/newcoder | train | 1 | |
7032e5a7d0df09b73bb171c5daa95ad7686fa895 | [
"player_index = 5\nvillager = Villager.awake_init(player_index, [], ())\nassert villager.statements == (Statement('I am a Villager.', ((5, frozenset({Role.VILLAGER})),)),)",
"player_index = 0\nresult = Villager.get_villager_statements(player_index)\nassert result == (Statement('I am a Villager.', ((0, frozenset({... | <|body_start_0|>
player_index = 5
villager = Villager.awake_init(player_index, [], ())
assert villager.statements == (Statement('I am a Villager.', ((5, frozenset({Role.VILLAGER})),)),)
<|end_body_0|>
<|body_start_1|>
player_index = 0
result = Villager.get_villager_statements(pl... | Tests for the Villager player class. | TestVillager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVillager:
"""Tests for the Villager player class."""
def test_awake_init() -> None:
"""Should initialize a Villager."""
<|body_0|>
def test_get_villager_statements() -> None:
"""Execute initialization actions and return the possible statements."""
<|b... | stack_v2_sparse_classes_36k_train_026077 | 1,242 | permissive | [
{
"docstring": "Should initialize a Villager.",
"name": "test_awake_init",
"signature": "def test_awake_init() -> None"
},
{
"docstring": "Execute initialization actions and return the possible statements.",
"name": "test_get_villager_statements",
"signature": "def test_get_villager_stat... | 3 | stack_v2_sparse_classes_30k_val_001193 | Implement the Python class `TestVillager` described below.
Class description:
Tests for the Villager player class.
Method signatures and docstrings:
- def test_awake_init() -> None: Should initialize a Villager.
- def test_get_villager_statements() -> None: Execute initialization actions and return the possible state... | Implement the Python class `TestVillager` described below.
Class description:
Tests for the Villager player class.
Method signatures and docstrings:
- def test_awake_init() -> None: Should initialize a Villager.
- def test_get_villager_statements() -> None: Execute initialization actions and return the possible state... | 6e91c2f24e72f9374c4f703bd966963ea6626e8e | <|skeleton|>
class TestVillager:
"""Tests for the Villager player class."""
def test_awake_init() -> None:
"""Should initialize a Villager."""
<|body_0|>
def test_get_villager_statements() -> None:
"""Execute initialization actions and return the possible statements."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestVillager:
"""Tests for the Villager player class."""
def test_awake_init() -> None:
"""Should initialize a Villager."""
player_index = 5
villager = Villager.awake_init(player_index, [], ())
assert villager.statements == (Statement('I am a Villager.', ((5, frozenset({Ro... | the_stack_v2_python_sparse | unit_test/roles/village/villager_test.py | srijan-deepsource/wolfbot | train | 0 |
708ceff036b5b0424def759456b1f5d48f687c24 | [
"if not nums:\n return None\ncurrent_sum = 0\nmax_sum = nums[0]\nelement_list = []\nfor num in nums:\n element_list.append(num)\n current_sum += num\n if current_sum >= max_sum:\n max_list = copy.copy(element_list)\n max_sum = current_sum\n if current_sum < 0:\n element_list = []... | <|body_start_0|>
if not nums:
return None
current_sum = 0
max_sum = nums[0]
element_list = []
for num in nums:
element_list.append(num)
current_sum += num
if current_sum >= max_sum:
max_list = copy.copy(element_list)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return None
... | stack_v2_sparse_classes_36k_train_026078 | 1,087 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray1",
"signature": "def maxSubArray1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maxSubArray2",
"signature": "def maxSubArray2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014972 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxSubArray1(self, nums): :type nums: List[int] :rtype: int
- def maxSubArray2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxSubArr... | 8fb6c1d947046dabd58ff8482b2c0b41f39aa988 | <|skeleton|>
class Solution:
def maxSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maxSubArray2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxSubArray1(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return None
current_sum = 0
max_sum = nums[0]
element_list = []
for num in nums:
element_list.append(num)
current_sum += num
... | the_stack_v2_python_sparse | Python/LeetCode/53.py | czx94/Algorithms-Collection | train | 2 | |
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_36k_train_026079 | 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_000101 | 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_36k | 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 | |
a1bc2fceaf142f1113e32d2767ab9fe520dbac3a | [
"self.year_range = range(start_year, end_year + 1)\nself.countries = countries_obj\nself.income = income_obj",
"for year in self.year_range:\n merged_data = merge_by_year(year, self.countries, self.income)\n regions = set(merged_data.Region.values)\n for region in regions:\n region_data = merged_d... | <|body_start_0|>
self.year_range = range(start_year, end_year + 1)
self.countries = countries_obj
self.income = income_obj
<|end_body_0|>
<|body_start_1|>
for year in self.year_range:
merged_data = merge_by_year(year, self.countries, self.income)
regions = set(me... | Graphically explores the given data | ExploratoryAnalysis | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExploratoryAnalysis:
"""Graphically explores the given data"""
def __init__(self, start_year, end_year, countries_obj, income_obj):
"""Constructor"""
<|body_0|>
def generate_histogram_plots_by_region(self):
"""Generates all the plots based on region for every yea... | stack_v2_sparse_classes_36k_train_026080 | 1,957 | no_license | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, start_year, end_year, countries_obj, income_obj)"
},
{
"docstring": "Generates all the plots based on region for every year in the range asked",
"name": "generate_histogram_plots_by_region",
"signature": "... | 2 | null | Implement the Python class `ExploratoryAnalysis` described below.
Class description:
Graphically explores the given data
Method signatures and docstrings:
- def __init__(self, start_year, end_year, countries_obj, income_obj): Constructor
- def generate_histogram_plots_by_region(self): Generates all the plots based on... | Implement the Python class `ExploratoryAnalysis` described below.
Class description:
Graphically explores the given data
Method signatures and docstrings:
- def __init__(self, start_year, end_year, countries_obj, income_obj): Constructor
- def generate_histogram_plots_by_region(self): Generates all the plots based on... | b493aea42bf5421e1c0bbc4514e8f6b691ad2200 | <|skeleton|>
class ExploratoryAnalysis:
"""Graphically explores the given data"""
def __init__(self, start_year, end_year, countries_obj, income_obj):
"""Constructor"""
<|body_0|>
def generate_histogram_plots_by_region(self):
"""Generates all the plots based on region for every yea... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExploratoryAnalysis:
"""Graphically explores the given data"""
def __init__(self, start_year, end_year, countries_obj, income_obj):
"""Constructor"""
self.year_range = range(start_year, end_year + 1)
self.countries = countries_obj
self.income = income_obj
def generate... | the_stack_v2_python_sparse | vdn207/exploratory_analysis.py | SeanRosario/assignment9 | train | 0 |
eeec7dd7ccf23b7f76bd00c05a8210b6ad976e65 | [
"k = len(lists)\nif k == 0:\n return None\nelif k == 1:\n return lists[0]\nend = k - 1\nwhile end != 0:\n i = 0\n j = end\n while i < j:\n lists[i] = self.mergeTwoLists(lists[i], lists[j])\n i = i + 1\n j = j - 1\n if i >= j:\n end = j\nreturn lists[0]",
"if l... | <|body_start_0|>
k = len(lists)
if k == 0:
return None
elif k == 1:
return lists[0]
end = k - 1
while end != 0:
i = 0
j = end
while i < j:
lists[i] = self.mergeTwoLists(lists[i], lists[j])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
k = len(... | stack_v2_sparse_classes_36k_train_026081 | 1,371 | no_license | [
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
},
{
"docstring": ":type l1: ListNode :type l2: ListNode :rtype: ListNode",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1, l2)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(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 mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
- def mergeTwoLists(self, l1, l2): :type l1: ListNode :type l2: ListNode :rtype: ListNode
<|skeleton|>... | cd8470b4a7ee47b872b590b3682d0f3c59aa2199 | <|skeleton|>
class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_0|>
def mergeTwoLists(self, l1, l2):
""":type l1: ListNode :type l2: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
k = len(lists)
if k == 0:
return None
elif k == 1:
return lists[0]
end = k - 1
while end != 0:
i = 0
j = end
wh... | the_stack_v2_python_sparse | merge_k_sorted_lists.py | manika1511/interview_prep | train | 0 | |
6fad8ed0e7549cf93a323465b60a264ab7cf7919 | [
"try:\n label = get_single_label(id, self.request.user.id)\n return label\nexcept IndexError:\n raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])",
"try:\n label = self.get_object(id)\n return Response({'data': label, 'code': 200, 'msg': response_code[200]})\nexcept RequestObjectDo... | <|body_start_0|>
try:
label = get_single_label(id, self.request.user.id)
return label
except IndexError:
raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])
<|end_body_0|>
<|body_start_1|>
try:
label = self.get_object(id)
... | EditLabel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request contains user detail, id contains label id returns: single label or does not exist""... | stack_v2_sparse_classes_36k_train_026082 | 4,340 | no_license | [
{
"docstring": "param id: Label id returns: single label or raise error",
"name": "get_object",
"signature": "def get_object(self, id=None)"
},
{
"docstring": "param request, id: Http request contains user detail, id contains label id returns: single label or does not exist",
"name": "get",
... | 3 | stack_v2_sparse_classes_30k_train_011666 | Implement the Python class `EditLabel` described below.
Class description:
Implement the EditLabel class.
Method signatures and docstrings:
- def get_object(self, id=None): param id: Label id returns: single label or raise error
- def get(self, request, id=None): param request, id: Http request contains user detail, ... | Implement the Python class `EditLabel` described below.
Class description:
Implement the EditLabel class.
Method signatures and docstrings:
- def get_object(self, id=None): param id: Label id returns: single label or raise error
- def get(self, request, id=None): param request, id: Http request contains user detail, ... | 8513e544cc635c372998cb8ac57bd4c93c431a9a | <|skeleton|>
class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request contains user detail, id contains label id returns: single label or does not exist""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EditLabel:
def get_object(self, id=None):
"""param id: Label id returns: single label or raise error"""
try:
label = get_single_label(id, self.request.user.id)
return label
except IndexError:
raise RequestObjectDoesNotExixts(code=409, msg=response_co... | the_stack_v2_python_sparse | fundoo/label/views.py | deep-sarkar/keep | train | 0 | |
7937eab41ff5b687237bc2a7b6b9837ccb63c797 | [
"super().__init__(**kwargs)\nself.problem_reference = GetClosestPersonOrRefillProblem\nself.problem = None",
"grid, remaining_gas = perception\nplayer_values = [self.player_number, self.player_number + 7]\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] in player_values:\n ... | <|body_start_0|>
super().__init__(**kwargs)
self.problem_reference = GetClosestPersonOrRefillProblem
self.problem = None
<|end_body_0|>
<|body_start_1|>
grid, remaining_gas = perception
player_values = [self.player_number, self.player_number + 7]
for i in range(len(grid)... | Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each step this agent perform a new A* search until... | GetClosestPersonOrRefillAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetClosestPersonOrRefillAgent:
"""Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heurist... | stack_v2_sparse_classes_36k_train_026083 | 44,047 | permissive | [
{
"docstring": "As stated before, all information that will be passed during the initialization is packed in the kwargs and, because of that, unless you decided to implement fancy attributes here, you can safely pass the kwargs dictionary directly to the superclass constructor. For pedagogical reasons, we decid... | 5 | stack_v2_sparse_classes_30k_train_001875 | Implement the Python class `GetClosestPersonOrRefillAgent` described below.
Class description:
Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* se... | Implement the Python class `GetClosestPersonOrRefillAgent` described below.
Class description:
Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* se... | 89b67b61817500aad359c64c7f43fcc2f1ef0698 | <|skeleton|>
class GetClosestPersonOrRefillAgent:
"""Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heurist... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetClosestPersonOrRefillAgent:
"""Agent Class that implements a planning agent The GetClosestPersonOrRefill class is a subclass of Agent that implements a specific agent whose objective is to collect the closest available person or refuelling, by using A* search with manhattan distance as heuristic. On each s... | the_stack_v2_python_sparse | EP2/ep2.py | ricardokojo/MAC0425-2019 | train | 1 |
46f324c5e26717807963c5ebe1bd34e28eacbc0e | [
"races = Race.objects.all()\nserializer = RaceListSerializer(races, many=True)\nreturn Response(serializer.data)",
"queryset = Race.objects.all()\nrace = get_object_or_404(queryset, pk=pk)\nserializer = RaceSerializer(race)\nreturn Response(serializer.data)"
] | <|body_start_0|>
races = Race.objects.all()
serializer = RaceListSerializer(races, many=True)
return Response(serializer.data)
<|end_body_0|>
<|body_start_1|>
queryset = Race.objects.all()
race = get_object_or_404(queryset, pk=pk)
serializer = RaceSerializer(race)
... | RacesView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RacesView:
def list(self, request):
"""Получение списка рас"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение расы по идентификатору pk - идентификатор расы"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
races = Race.objects.all()
... | stack_v2_sparse_classes_36k_train_026084 | 12,404 | no_license | [
{
"docstring": "Получение списка рас",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Получение расы по идентификатору pk - идентификатор расы",
"name": "retrieve",
"signature": "def retrieve(self, request, pk=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020014 | Implement the Python class `RacesView` described below.
Class description:
Implement the RacesView class.
Method signatures and docstrings:
- def list(self, request): Получение списка рас
- def retrieve(self, request, pk=None): Получение расы по идентификатору pk - идентификатор расы | Implement the Python class `RacesView` described below.
Class description:
Implement the RacesView class.
Method signatures and docstrings:
- def list(self, request): Получение списка рас
- def retrieve(self, request, pk=None): Получение расы по идентификатору pk - идентификатор расы
<|skeleton|>
class RacesView:
... | be47a0a6f50bf8680b22e0b9cae3e3b34a198a3d | <|skeleton|>
class RacesView:
def list(self, request):
"""Получение списка рас"""
<|body_0|>
def retrieve(self, request, pk=None):
"""Получение расы по идентификатору pk - идентификатор расы"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RacesView:
def list(self, request):
"""Получение списка рас"""
races = Race.objects.all()
serializer = RaceListSerializer(races, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
"""Получение расы по идентификатору pk - идентификатор... | the_stack_v2_python_sparse | StarfinderBack/starfinder/views.py | Skirgus/StarfinderMasterAssistant | train | 0 | |
ea6e9194dff7d1d9d914cdd569197f44441e9eda | [
"outer_message = MIMEMultipart()\nouter_message.attach(MIMEText(body, 'plain'))\nouter_message['Subject'] = subject\nouter_message['To'] = recipients\nouter_message['From'] = 'pscad.script@gmail.com'\nouter_message.preamble = 'You will not see this in a MIME-aware mail reader.\\n'\nattachment_list = (fn.strip() for... | <|body_start_0|>
outer_message = MIMEMultipart()
outer_message.attach(MIMEText(body, 'plain'))
outer_message['Subject'] = subject
outer_message['To'] = recipients
outer_message['From'] = 'pscad.script@gmail.com'
outer_message.preamble = 'You will not see this in a MIME-aw... | E-Mail Helper Utility | Mail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mail:
"""E-Mail Helper Utility"""
def send_gmail(sender, password, recipients, subject, body, attachments=None):
"""Sends a document using a GMail account"""
<|body_0|>
def send_outlook_mail(to, subject, body, attachments=None):
"""Sends a document using a Micros... | stack_v2_sparse_classes_36k_train_026085 | 5,852 | no_license | [
{
"docstring": "Sends a document using a GMail account",
"name": "send_gmail",
"signature": "def send_gmail(sender, password, recipients, subject, body, attachments=None)"
},
{
"docstring": "Sends a document using a Microsoft Outlook account",
"name": "send_outlook_mail",
"signature": "d... | 2 | stack_v2_sparse_classes_30k_train_012400 | Implement the Python class `Mail` described below.
Class description:
E-Mail Helper Utility
Method signatures and docstrings:
- def send_gmail(sender, password, recipients, subject, body, attachments=None): Sends a document using a GMail account
- def send_outlook_mail(to, subject, body, attachments=None): Sends a do... | Implement the Python class `Mail` described below.
Class description:
E-Mail Helper Utility
Method signatures and docstrings:
- def send_gmail(sender, password, recipients, subject, body, attachments=None): Sends a document using a GMail account
- def send_outlook_mail(to, subject, body, attachments=None): Sends a do... | bf1c1161a8da0dd8d3c2cc488740ec8605d4fa68 | <|skeleton|>
class Mail:
"""E-Mail Helper Utility"""
def send_gmail(sender, password, recipients, subject, body, attachments=None):
"""Sends a document using a GMail account"""
<|body_0|>
def send_outlook_mail(to, subject, body, attachments=None):
"""Sends a document using a Micros... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mail:
"""E-Mail Helper Utility"""
def send_gmail(sender, password, recipients, subject, body, attachments=None):
"""Sends a document using a GMail account"""
outer_message = MIMEMultipart()
outer_message.attach(MIMEText(body, 'plain'))
outer_message['Subject'] = subject
... | the_stack_v2_python_sparse | automation/utilities/mail.py | yuanzy97/pscad_automation_python | train | 0 |
7b77dfe44cf236d66bcdfdb131c39d1d53c4a811 | [
"opens = '([{'\ncloses = ')]}'\nparstack = Stack()\nbalance = True\nfor each in s:\n if each in '([{':\n parstack.push(each)\n elif parstack.isEmpty():\n balance = False\n else:\n top = parstack.pop()\n if opens.index(top) != closes.index(each):\n balance = False\nif ... | <|body_start_0|>
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
balance = False
else:
top = parstack.p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
opens = '([{'
closes = ')]}'
parstack = Stack()
... | stack_v2_sparse_classes_36k_train_026086 | 1,433 | no_license | [
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid_stack",
"signature": "def isValid_stack(self, s)"
},
{
"docstring": ":type s: str :rtype: bool",
"name": "isValid",
"signature": "def isValid(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013057 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isValid_stack(self, s): :type s: str :rtype: bool
- def isValid(self, s): :type s: str :rtype: bool
<|skeleton|>
class Solution:
def isValid_stack(self, s):
"""... | 85f71621c54f6b0029f3a2746f022f89dd7419d9 | <|skeleton|>
class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
<|body_0|>
def isValid(self, s):
""":type s: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isValid_stack(self, s):
""":type s: str :rtype: bool"""
opens = '([{'
closes = ')]}'
parstack = Stack()
balance = True
for each in s:
if each in '([{':
parstack.push(each)
elif parstack.isEmpty():
... | the_stack_v2_python_sparse | LeetCode/String/20_Stack_valid_parentheses.py | XyK0907/for_work | train | 0 | |
3f71b53e25fe89de0e43902bda8c8ec7efbff07e | [
"n1 = container.geometry.material.refractive_index\nn2 = adjacent.geometry.material.refractive_index\nnormal = geometry.normal(ray.position)\nif np.dot(normal, ray.direction) < 0.0:\n normal = flip(normal)\nangle = angle_between(normal, np.array(ray.direction))\nr = fresnel_reflectivity(angle, n1, n2)\nreturn fl... | <|body_start_0|>
n1 = container.geometry.material.refractive_index
n2 = adjacent.geometry.material.refractive_index
normal = geometry.normal(ray.position)
if np.dot(normal, ray.direction) < 0.0:
normal = flip(normal)
angle = angle_between(normal, np.array(ray.directio... | Fresnel reflection and refraction on the surface. | FresnelSurfaceDelegate | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FresnelSurfaceDelegate:
"""Fresnel reflection and refraction on the surface."""
def reflectivity(self, surface, ray, geometry, container, adjacent):
"""Returns the reflectivity given the interaction. Parameters ---------- surface: Surface The surface object owned by the material. ray... | stack_v2_sparse_classes_36k_train_026087 | 9,521 | no_license | [
{
"docstring": "Returns the reflectivity given the interaction. Parameters ---------- surface: Surface The surface object owned by the material. ray: Ray The incident ray. geometry: Geometry The geometry being hit. container: Node The node containing the incident ray. adjacent: Node The node that would contain ... | 3 | stack_v2_sparse_classes_30k_val_000104 | Implement the Python class `FresnelSurfaceDelegate` described below.
Class description:
Fresnel reflection and refraction on the surface.
Method signatures and docstrings:
- def reflectivity(self, surface, ray, geometry, container, adjacent): Returns the reflectivity given the interaction. Parameters ---------- surfa... | Implement the Python class `FresnelSurfaceDelegate` described below.
Class description:
Fresnel reflection and refraction on the surface.
Method signatures and docstrings:
- def reflectivity(self, surface, ray, geometry, container, adjacent): Returns the reflectivity given the interaction. Parameters ---------- surfa... | 1f89db30f9f2e3d61a2bd9f5ab1a1742f897ad87 | <|skeleton|>
class FresnelSurfaceDelegate:
"""Fresnel reflection and refraction on the surface."""
def reflectivity(self, surface, ray, geometry, container, adjacent):
"""Returns the reflectivity given the interaction. Parameters ---------- surface: Surface The surface object owned by the material. ray... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FresnelSurfaceDelegate:
"""Fresnel reflection and refraction on the surface."""
def reflectivity(self, surface, ray, geometry, container, adjacent):
"""Returns the reflectivity given the interaction. Parameters ---------- surface: Surface The surface object owned by the material. ray: Ray The inc... | the_stack_v2_python_sparse | pvtrace/material/surface.py | pcyc/pvtrace | train | 0 |
d68571175086b2ed21edf0dd1e35a0d381d27c71 | [
"page_facade = request.models.DynamicPage\npage_attr_facade = request.models.DynamicPageModel\npage_url = '/%s' % page_url\npage = page_facade.get_records_paged(0, 1, ModelFilter(DynamicPage.url, page_url, ModelFilter.EQ))\nif len(page) == 0:\n msg_not_found = 'Page %s does not exist.' % page_url\n return Res... | <|body_start_0|>
page_facade = request.models.DynamicPage
page_attr_facade = request.models.DynamicPageModel
page_url = '/%s' % page_url
page = page_facade.get_records_paged(0, 1, ModelFilter(DynamicPage.url, page_url, ModelFilter.EQ))
if len(page) == 0:
msg_not_found... | This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a relation between :py:class:`fantastico.contrib.dynamic_pages.models.pages.Dynami... | PagesRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PagesRouter:
"""This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a relation between :py:class:`fantastico.co... | stack_v2_sparse_classes_36k_train_026088 | 5,410 | permissive | [
{
"docstring": "This method is used to route all /dynamic/... requests to database pages. It renders the configured template into database binded to :py:class:`fantastico.contrib.models.pages.DynamicPageModel` values.",
"name": "serve_dynamic_page",
"signature": "def serve_dynamic_page(self, request, pa... | 2 | stack_v2_sparse_classes_30k_train_011836 | Implement the Python class `PagesRouter` described below.
Class description:
This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a re... | Implement the Python class `PagesRouter` described below.
Class description:
This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a re... | 81c8590556baa9e1148071b7835d74b1efada561 | <|skeleton|>
class PagesRouter:
"""This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a relation between :py:class:`fantastico.co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PagesRouter:
"""This class provides the API for managing dynamic pages. In addition, it creates the special route **/dynamic/<page_url>** used to access pages stored in the database. From dynamic pages module perspective, a web page is nothing more than a relation between :py:class:`fantastico.contrib.dynamic... | the_stack_v2_python_sparse | fantastico/contrib/dynamic_pages/pages_router.py | rcosnita/fantastico | train | 3 |
1cb0a3e2cab7ef95893fdb45f6a3f49c16dff589 | [
"config_dict = self.config_dict\nif len(config_dict['c']) > 1:\n config_dict['c'] = config_dict['c'][0]\ntry:\n plt.scatter(y=grid[:, 0], x=grid[:, 1], **config_dict)\nexcept (IndexError, TypeError):\n return self.scatter_grid_list(grid_list=grid)",
"if len(grid_list) == 0:\n return\ncolor = itertools... | <|body_start_0|>
config_dict = self.config_dict
if len(config_dict['c']) > 1:
config_dict['c'] = config_dict['c'][0]
try:
plt.scatter(y=grid[:, 0], x=grid[:, 1], **config_dict)
except (IndexError, TypeError):
return self.scatter_grid_list(grid_list=gri... | Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatter: https://matplotlib.org/3.1.1/api/_a... | GridScatter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GridScatter:
"""Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatt... | stack_v2_sparse_classes_36k_train_026089 | 21,101 | permissive | [
{
"docstring": "Plot an input grid of (y,x) coordinates using the matplotlib method `plt.scatter`. Parameters ---------- grid : Grid2D The grid of (y,x) coordinates that is plotted.",
"name": "scatter_grid",
"signature": "def scatter_grid(self, grid: typing.Union[np.ndarray, grid_2d.Grid2D])"
},
{
... | 4 | null | Implement the Python class `GridScatter` described below.
Class description:
Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the fo... | Implement the Python class `GridScatter` described below.
Class description:
Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the fo... | c21e8859bdb20737352147b9904797ac99985b73 | <|skeleton|>
class GridScatter:
"""Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GridScatter:
"""Scatters an input set of grid points, for example (y,x) coordinates or data structures representing 2D (y,x) coordinates like a `Grid2D` or `Grid2DIrregular`. List of (y,x) coordinates are plotted with varying colors. This object wraps the following Matplotlib methods: - plt.scatter: https://m... | the_stack_v2_python_sparse | autoarray/plot/mat_wrap/wrap/wrap_2d.py | jonathanfrawley/PyAutoArray_copy | train | 0 |
a302311fa685467c20d5fc4e7cf9142fa80e28ec | [
"if self.get_config_param('stat', None) in [DEFAULT_STAT_TYPE, None]:\n formatter = SUPERDARK_FORMATTER\nelse:\n formatter = SUPERDARK_STAT_FORMATTER\nreturn self.get_filename_from_format(formatter, '.fits', **kwargs)",
"self.safe_update(**kwargs)\nsuperdark_file = self.get_superdark_file()\nreturn self.get... | <|body_start_0|>
if self.get_config_param('stat', None) in [DEFAULT_STAT_TYPE, None]:
formatter = SUPERDARK_FORMATTER
else:
formatter = SUPERDARK_STAT_FORMATTER
return self.get_filename_from_format(formatter, '.fits', **kwargs)
<|end_body_0|>
<|body_start_1|>
sel... | Simple functor class to tie together standard dark data analysis | DarkAnalysisTask | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DarkAnalysisTask:
"""Simple functor class to tie together standard dark data analysis"""
def get_superdark_file(self, **kwargs):
"""Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwargs Passed to the file name formatter Returns ------- ret... | stack_v2_sparse_classes_36k_train_026090 | 2,361 | permissive | [
{
"docstring": "Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwargs Passed to the file name formatter Returns ------- retval : `str` The filename",
"name": "get_superdark_file",
"signature": "def get_superdark_file(self, **kwargs)"
},
{
"docstring":... | 2 | null | Implement the Python class `DarkAnalysisTask` described below.
Class description:
Simple functor class to tie together standard dark data analysis
Method signatures and docstrings:
- def get_superdark_file(self, **kwargs): Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwa... | Implement the Python class `DarkAnalysisTask` described below.
Class description:
Simple functor class to tie together standard dark data analysis
Method signatures and docstrings:
- def get_superdark_file(self, **kwargs): Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwa... | 28418284fdaf2b2fb0afbeccd4324f7ad3e676c8 | <|skeleton|>
class DarkAnalysisTask:
"""Simple functor class to tie together standard dark data analysis"""
def get_superdark_file(self, **kwargs):
"""Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwargs Passed to the file name formatter Returns ------- ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DarkAnalysisTask:
"""Simple functor class to tie together standard dark data analysis"""
def get_superdark_file(self, **kwargs):
"""Get the name of the superdark file for a particular run, raft, ccd... Parameters ---------- kwargs Passed to the file name formatter Returns ------- retval : `str` T... | the_stack_v2_python_sparse | python/lsst/eo_utils/dark/analysis.py | lsst-camera-dh/EO-utilities | train | 2 |
e9bbec5d3bf10ec11e0549960997864895f33789 | [
"name = 'PrepareReadCountData'\noutput_dir = output_dir\ninput_file = cases_paths[0][0]\noutput_file = output_file\nlog_name = 'prepare_read_count_data.json'\nlogger = logger\nsuper().__init__(name, output_dir, input_file, output_file, log_name, logger)\nself.cases = cases_paths\nself.controls = controls_paths\nsel... | <|body_start_0|>
name = 'PrepareReadCountData'
output_dir = output_dir
input_file = cases_paths[0][0]
output_file = output_file
log_name = 'prepare_read_count_data.json'
logger = logger
super().__init__(name, output_dir, input_file, output_file, log_name, logger)
... | RunPrepareReadCountData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunPrepareReadCountData:
def __init__(self, output_dir, cases_paths, controls_paths, output_file=None, logger=None):
"""The constructor class for a RunPrepareReadCountData object. :param output_dir: The output directory. :param cases_paths: The list of paths to the read count files for t... | stack_v2_sparse_classes_36k_train_026091 | 7,625 | no_license | [
{
"docstring": "The constructor class for a RunPrepareReadCountData object. :param output_dir: The output directory. :param cases_paths: The list of paths to the read count files for the cases. :param controls_paths: The list of paths to the read count files for the controls. :param output_file: The path to the... | 5 | stack_v2_sparse_classes_30k_train_011241 | Implement the Python class `RunPrepareReadCountData` described below.
Class description:
Implement the RunPrepareReadCountData class.
Method signatures and docstrings:
- def __init__(self, output_dir, cases_paths, controls_paths, output_file=None, logger=None): The constructor class for a RunPrepareReadCountData obje... | Implement the Python class `RunPrepareReadCountData` described below.
Class description:
Implement the RunPrepareReadCountData class.
Method signatures and docstrings:
- def __init__(self, output_dir, cases_paths, controls_paths, output_file=None, logger=None): The constructor class for a RunPrepareReadCountData obje... | 2bb67262fc520edded9a0311f2182426371dea6b | <|skeleton|>
class RunPrepareReadCountData:
def __init__(self, output_dir, cases_paths, controls_paths, output_file=None, logger=None):
"""The constructor class for a RunPrepareReadCountData object. :param output_dir: The output directory. :param cases_paths: The list of paths to the read count files for t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunPrepareReadCountData:
def __init__(self, output_dir, cases_paths, controls_paths, output_file=None, logger=None):
"""The constructor class for a RunPrepareReadCountData object. :param output_dir: The output directory. :param cases_paths: The list of paths to the read count files for the cases. :par... | the_stack_v2_python_sparse | asetools/mod/process/prepare_count_data.py | durrantmm/ASETools | train | 0 | |
d787b2ff925a978567c06c2a8174a2d3dfb9b541 | [
"self._actionButtons = []\nself._iconSize = QtCore.QSize(LineEditIconButton.iconSize + 2, LineEditIconButton.iconSize + 2)\nself._iconRegion = QtCore.QSize(self._iconSize.width() + LineEditIconButton.iconMargin, self._iconSize.height())\nsuper(LineEdit, self).__init__(*args, **kw)",
"button = LineEditIconButton(s... | <|body_start_0|>
self._actionButtons = []
self._iconSize = QtCore.QSize(LineEditIconButton.iconSize + 2, LineEditIconButton.iconSize + 2)
self._iconRegion = QtCore.QSize(self._iconSize.width() + LineEditIconButton.iconMargin, self._iconSize.height())
super(LineEdit, self).__init__(*args,... | Line edit that supports embedded actions. | LineEdit | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LineEdit:
"""Line edit that supports embedded actions."""
def __init__(self, *args, **kw):
"""Initialise line edit."""
<|body_0|>
def addAction(self, action):
"""Add *action*."""
<|body_1|>
def removeAction(self, action):
"""Remove *action*. ... | stack_v2_sparse_classes_36k_train_026092 | 3,683 | permissive | [
{
"docstring": "Initialise line edit.",
"name": "__init__",
"signature": "def __init__(self, *args, **kw)"
},
{
"docstring": "Add *action*.",
"name": "addAction",
"signature": "def addAction(self, action)"
},
{
"docstring": "Remove *action*. Raise :py:exc:`ValueError` if no match... | 4 | stack_v2_sparse_classes_30k_val_000654 | Implement the Python class `LineEdit` described below.
Class description:
Line edit that supports embedded actions.
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialise line edit.
- def addAction(self, action): Add *action*.
- def removeAction(self, action): Remove *action*. Raise :py:exc:`... | Implement the Python class `LineEdit` described below.
Class description:
Line edit that supports embedded actions.
Method signatures and docstrings:
- def __init__(self, *args, **kw): Initialise line edit.
- def addAction(self, action): Add *action*.
- def removeAction(self, action): Remove *action*. Raise :py:exc:`... | f55f52787484fcf931c4653e7e241791f052c04f | <|skeleton|>
class LineEdit:
"""Line edit that supports embedded actions."""
def __init__(self, *args, **kw):
"""Initialise line edit."""
<|body_0|>
def addAction(self, action):
"""Add *action*."""
<|body_1|>
def removeAction(self, action):
"""Remove *action*. ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LineEdit:
"""Line edit that supports embedded actions."""
def __init__(self, *args, **kw):
"""Initialise line edit."""
self._actionButtons = []
self._iconSize = QtCore.QSize(LineEditIconButton.iconSize + 2, LineEditIconButton.iconSize + 2)
self._iconRegion = QtCore.QSize(s... | the_stack_v2_python_sparse | source/ftrack_connect/ui/widget/line_edit.py | IngenuityEngine/ftrack-connect | train | 0 |
a52151ea5bac9315b1d8b6f8f590fb1283291474 | [
"super(PriProb, self).__init__()\nself.r = np.random.multinomial(totalR, [1 / float(J)] * J, size=1)\nnormalizedR = ad.normalize(self.r, using_max=False)\nself.R = nn.Parameter(torchten(normalizedR))",
"repeatedR = self.R.repeat(J, 1).unsqueeze(dim=2)\nres = torch.bmm(repeatedR, wt1) + F_DIST_w1\nres = torchfun.r... | <|body_start_0|>
super(PriProb, self).__init__()
self.r = np.random.multinomial(totalR, [1 / float(J)] * J, size=1)
normalizedR = ad.normalize(self.r, using_max=False)
self.R = nn.Parameter(torchten(normalizedR))
<|end_body_0|>
<|body_start_1|>
repeatedR = self.R.repeat(J, 1).un... | An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here. | PriProb | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriProb:
"""An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here."""
def __init__(self):
"""Initializes PriProb, creates the rewards dataset for the model."""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_026093 | 16,500 | permissive | [
{
"docstring": "Initializes PriProb, creates the rewards dataset for the model.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Goes forward in the network -- multiply the weights, apply relu, multiply weights again and apply softmax Returns: torch.Tensor -- result aft... | 2 | stack_v2_sparse_classes_30k_train_012149 | Implement the Python class `PriProb` described below.
Class description:
An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here.
Method signatures and docstrings:
- def __init__(self): Initializes PriProb, creates the rewa... | Implement the Python class `PriProb` described below.
Class description:
An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here.
Method signatures and docstrings:
- def __init__(self): Initializes PriProb, creates the rewa... | 3b85c1b70adcbe5d5b2764195090b28093081b1f | <|skeleton|>
class PriProb:
"""An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here."""
def __init__(self):
"""Initializes PriProb, creates the rewards dataset for the model."""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PriProb:
"""An instance of this class emulates the sub-model used in Pricing Problem to calculate the loss function and update rewards. Constraining not done here."""
def __init__(self):
"""Initializes PriProb, creates the rewards dataset for the model."""
super(PriProb, self).__init__()
... | the_stack_v2_python_sparse | nnAvicaching_find_rewards.py | anmolkabra/avicaching-summ17 | train | 0 |
7e9daaf777de38f4b168931a6674724a54138ade | [
"self.device = device\nself.layer_output_size = layer_output_size\nself.model_name = model\nself.model, self.extraction_layer = self._get_model_and_layer(model, layer, model_path)\nself.model = self.model.to(self.device)\nself.model.eval()\nself.scaler = transforms.Resize((224, 224))\nself.normalize = transforms.No... | <|body_start_0|>
self.device = device
self.layer_output_size = layer_output_size
self.model_name = model
self.model, self.extraction_layer = self._get_model_and_layer(model, layer, model_path)
self.model = self.model.to(self.device)
self.model.eval()
self.scaler =... | Img2Vec | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Img2Vec:
def __init__(self, model_path, model='resnet-18', layer='default', layer_output_size=512, device='cuda'):
"""Img2Vec :param model: String name of requested model :param layer: String or Int depending on model. See more docs: https://github.com/christiansafka/img2vec.git :param l... | stack_v2_sparse_classes_36k_train_026094 | 4,647 | permissive | [
{
"docstring": "Img2Vec :param model: String name of requested model :param layer: String or Int depending on model. See more docs: https://github.com/christiansafka/img2vec.git :param layer_output_size: Int depicting the output size of the requested layer :param device: String that lets us decide between using... | 3 | stack_v2_sparse_classes_30k_train_011028 | Implement the Python class `Img2Vec` described below.
Class description:
Implement the Img2Vec class.
Method signatures and docstrings:
- def __init__(self, model_path, model='resnet-18', layer='default', layer_output_size=512, device='cuda'): Img2Vec :param model: String name of requested model :param layer: String ... | Implement the Python class `Img2Vec` described below.
Class description:
Implement the Img2Vec class.
Method signatures and docstrings:
- def __init__(self, model_path, model='resnet-18', layer='default', layer_output_size=512, device='cuda'): Img2Vec :param model: String name of requested model :param layer: String ... | e97f11cee15a522a09cab325ee943526f19c7d71 | <|skeleton|>
class Img2Vec:
def __init__(self, model_path, model='resnet-18', layer='default', layer_output_size=512, device='cuda'):
"""Img2Vec :param model: String name of requested model :param layer: String or Int depending on model. See more docs: https://github.com/christiansafka/img2vec.git :param l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Img2Vec:
def __init__(self, model_path, model='resnet-18', layer='default', layer_output_size=512, device='cuda'):
"""Img2Vec :param model: String name of requested model :param layer: String or Int depending on model. See more docs: https://github.com/christiansafka/img2vec.git :param layer_output_si... | the_stack_v2_python_sparse | distil/utils.py | uncharted-distil/distil-primitives | train | 4 | |
1584e4b608a56cdf5878586b4b876b72c42d2fba | [
"key = self._chooseName('', reg)\nself[key] = reg\nreturn key",
"if not name:\n name = reg.__class__.__name__\ni = 1\nchosenName = name\nwhile chosenName in self:\n i += 1\n chosenName = name + str(i)\nreturn chosenName"
] | <|body_start_0|>
key = self._chooseName('', reg)
self[key] = reg
return key
<|end_body_0|>
<|body_start_1|>
if not name:
name = reg.__class__.__name__
i = 1
chosenName = name
while chosenName in self:
i += 1
chosenName = name +... | Registration manager Manages registrations within a package. | RegistrationManager | [
"ZPL-2.1",
"Python-2.0",
"ICU",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegistrationManager:
"""Registration manager Manages registrations within a package."""
def addRegistration(self, reg):
"""See IWriteContainer"""
<|body_0|>
def _chooseName(self, name, reg):
"""Choose a name for the registration."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k_train_026095 | 9,659 | permissive | [
{
"docstring": "See IWriteContainer",
"name": "addRegistration",
"signature": "def addRegistration(self, reg)"
},
{
"docstring": "Choose a name for the registration.",
"name": "_chooseName",
"signature": "def _chooseName(self, name, reg)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014072 | Implement the Python class `RegistrationManager` described below.
Class description:
Registration manager Manages registrations within a package.
Method signatures and docstrings:
- def addRegistration(self, reg): See IWriteContainer
- def _chooseName(self, name, reg): Choose a name for the registration. | Implement the Python class `RegistrationManager` described below.
Class description:
Registration manager Manages registrations within a package.
Method signatures and docstrings:
- def addRegistration(self, reg): See IWriteContainer
- def _chooseName(self, name, reg): Choose a name for the registration.
<|skeleton|... | 4c538584703754c956ca66392fdcecf0a0ca2314 | <|skeleton|>
class RegistrationManager:
"""Registration manager Manages registrations within a package."""
def addRegistration(self, reg):
"""See IWriteContainer"""
<|body_0|>
def _chooseName(self, name, reg):
"""Choose a name for the registration."""
<|body_1|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegistrationManager:
"""Registration manager Manages registrations within a package."""
def addRegistration(self, reg):
"""See IWriteContainer"""
key = self._chooseName('', reg)
self[key] = reg
return key
def _chooseName(self, name, reg):
"""Choose a name for ... | the_stack_v2_python_sparse | CMS/Zope-3.2.1/Dependencies/zope.app-Zope-3.2.1/zope.app/component/registration.py | germanfriday/code-examples-sandbox | train | 0 |
63f5792aa6e4e471562ed2303bb3788345448c54 | [
"from wsgiref.simple_server import make_server, WSGIRequestHandler\nif self.quiet:\n\n class QuietHandler(WSGIRequestHandler):\n\n def log_request(*args, **kw):\n pass\n self.options['handler_class'] = QuietHandler\ntry:\n self.server = make_server(self.host, self.port, handler, **self.op... | <|body_start_0|>
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw):
pass
self.options['handler_class'] = QuietHandler
try:
... | Allows to programmatically shut down bottle server. | StoppableWSGIRefServer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StoppableWSGIRefServer:
"""Allows to programmatically shut down bottle server."""
def run(self, handler):
"""Start the server."""
<|body_0|>
def stop(self):
"""Stop the server."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from wsgiref.simple_... | stack_v2_sparse_classes_36k_train_026096 | 11,848 | permissive | [
{
"docstring": "Start the server.",
"name": "run",
"signature": "def run(self, handler)"
},
{
"docstring": "Stop the server.",
"name": "stop",
"signature": "def stop(self)"
}
] | 2 | null | Implement the Python class `StoppableWSGIRefServer` described below.
Class description:
Allows to programmatically shut down bottle server.
Method signatures and docstrings:
- def run(self, handler): Start the server.
- def stop(self): Stop the server. | Implement the Python class `StoppableWSGIRefServer` described below.
Class description:
Allows to programmatically shut down bottle server.
Method signatures and docstrings:
- def run(self, handler): Start the server.
- def stop(self): Stop the server.
<|skeleton|>
class StoppableWSGIRefServer:
"""Allows to prog... | 6bef453bf5042401ecdafcdda404452dfd982ecf | <|skeleton|>
class StoppableWSGIRefServer:
"""Allows to programmatically shut down bottle server."""
def run(self, handler):
"""Start the server."""
<|body_0|>
def stop(self):
"""Stop the server."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StoppableWSGIRefServer:
"""Allows to programmatically shut down bottle server."""
def run(self, handler):
"""Start the server."""
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
... | the_stack_v2_python_sparse | bot/web.py | ghostduck/monkalot | train | 0 |
1b523f2a0ea17a05dcde0a7379b2897aeac02eeb | [
"self.marker = empty\nself.root = None\nself.entities = 0",
"self.entities += 1\nif self.root is None:\n self.root = FFANode(marker=self.marker)\nself.root.add_branch(flex)",
"assert self.marker not in token\nif self.root:\n return self.root.parse(token)\nreturn []"
] | <|body_start_0|>
self.marker = empty
self.root = None
self.entities = 0
<|end_body_0|>
<|body_start_1|>
self.entities += 1
if self.root is None:
self.root = FFANode(marker=self.marker)
self.root.add_branch(flex)
<|end_body_1|>
<|body_start_2|>
assert... | A base class of an automaton looking for inflection options in a token. | FlexAutomaton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexAutomaton:
"""A base class of an automaton looking for inflection options in a token."""
def __init__(self, empty):
"""Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be used in flex templates."""
<|body_0|>
def add(... | stack_v2_sparse_classes_36k_train_026097 | 4,965 | no_license | [
{
"docstring": "Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be used in flex templates.",
"name": "__init__",
"signature": "def __init__(self, empty)"
},
{
"docstring": "Add an inflection to an automaton as a search option. The places stem pa... | 3 | stack_v2_sparse_classes_30k_train_011043 | Implement the Python class `FlexAutomaton` described below.
Class description:
A base class of an automaton looking for inflection options in a token.
Method signatures and docstrings:
- def __init__(self, empty): Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be us... | Implement the Python class `FlexAutomaton` described below.
Class description:
A base class of an automaton looking for inflection options in a token.
Method signatures and docstrings:
- def __init__(self, empty): Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be us... | b863d42145544b73b38a5f23042962b521690e51 | <|skeleton|>
class FlexAutomaton:
"""A base class of an automaton looking for inflection options in a token."""
def __init__(self, empty):
"""Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be used in flex templates."""
<|body_0|>
def add(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexAutomaton:
"""A base class of an automaton looking for inflection options in a token."""
def __init__(self, empty):
"""Initialize an instance. Args: empty - a marker of a arbitrary non-empty sequence of symbols should be used in flex templates."""
self.marker = empty
self.root... | the_stack_v2_python_sparse | automaton.py | sleepofnodreaming/gramdicmaker2016 | train | 0 |
0fb83d856fb1b5909c75c0bb30df787eef1b3cf3 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn CrossTenantAccessPolicyConfigurationPartner()",
"from .cross_tenant_access_policy_b2_b_setting import CrossTenantAccessPolicyB2BSetting\nfrom .cross_tenant_access_policy_inbound_trust import CrossTenantAccessPolicyInboundTrust\nfrom .c... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return CrossTenantAccessPolicyConfigurationPartner()
<|end_body_0|>
<|body_start_1|>
from .cross_tenant_access_policy_b2_b_setting import CrossTenantAccessPolicyB2BSetting
from .cross_tenant_ac... | CrossTenantAccessPolicyConfigurationPartner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossTenantAccessPolicyConfigurationPartner:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CrossTenantAccessPolicyConfigurationPartner:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use t... | stack_v2_sparse_classes_36k_train_026098 | 7,671 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: CrossTenantAccessPolicyConfigurationPartner",
"name": "create_from_discriminator_value",
"signature": "def c... | 3 | null | Implement the Python class `CrossTenantAccessPolicyConfigurationPartner` described below.
Class description:
Implement the CrossTenantAccessPolicyConfigurationPartner class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CrossTenantAccessPolicyConfigur... | Implement the Python class `CrossTenantAccessPolicyConfigurationPartner` described below.
Class description:
Implement the CrossTenantAccessPolicyConfigurationPartner class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CrossTenantAccessPolicyConfigur... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class CrossTenantAccessPolicyConfigurationPartner:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CrossTenantAccessPolicyConfigurationPartner:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossTenantAccessPolicyConfigurationPartner:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> CrossTenantAccessPolicyConfigurationPartner:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the dis... | the_stack_v2_python_sparse | msgraph/generated/models/cross_tenant_access_policy_configuration_partner.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
a7836d8c1e912b8040e056c52ffc50134e34d83d | [
"selector = _get_selector(loop)\nif evt & self._READ:\n selector.add_reader(socket, lambda *args: f())\nif evt & self._WRITE:\n selector.add_writer(socket, lambda *args: f())",
"selector = _get_selector(loop)\nfor socket in sockets:\n selector.remove_reader(socket)\n selector.remove_writer(socket)"
] | <|body_start_0|>
selector = _get_selector(loop)
if evt & self._READ:
selector.add_reader(socket, lambda *args: f())
if evt & self._WRITE:
selector.add_writer(socket, lambda *args: f())
<|end_body_0|>
<|body_start_1|>
selector = _get_selector(loop)
for soc... | Poller returning asyncio.Future for poll results. | Poller | [
"BSD-3-Clause",
"LGPL-3.0-only",
"LicenseRef-scancode-zeromq-exception-lgpl-3.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
<|body_0|>
def _unwatch_raw_sockets(self, loop, *sockets):
"""Unschedule callback for a raw socket"""
... | stack_v2_sparse_classes_36k_train_026099 | 6,271 | permissive | [
{
"docstring": "Schedule callback for a raw socket",
"name": "_watch_raw_socket",
"signature": "def _watch_raw_socket(self, loop, socket, evt, f)"
},
{
"docstring": "Unschedule callback for a raw socket",
"name": "_unwatch_raw_sockets",
"signature": "def _unwatch_raw_sockets(self, loop, ... | 2 | stack_v2_sparse_classes_30k_train_015506 | Implement the Python class `Poller` described below.
Class description:
Poller returning asyncio.Future for poll results.
Method signatures and docstrings:
- def _watch_raw_socket(self, loop, socket, evt, f): Schedule callback for a raw socket
- def _unwatch_raw_sockets(self, loop, *sockets): Unschedule callback for ... | Implement the Python class `Poller` described below.
Class description:
Poller returning asyncio.Future for poll results.
Method signatures and docstrings:
- def _watch_raw_socket(self, loop, socket, evt, f): Schedule callback for a raw socket
- def _unwatch_raw_sockets(self, loop, *sockets): Unschedule callback for ... | f5042e35b945aded77b23470ead62d7eacefde92 | <|skeleton|>
class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
<|body_0|>
def _unwatch_raw_sockets(self, loop, *sockets):
"""Unschedule callback for a raw socket"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Poller:
"""Poller returning asyncio.Future for poll results."""
def _watch_raw_socket(self, loop, socket, evt, f):
"""Schedule callback for a raw socket"""
selector = _get_selector(loop)
if evt & self._READ:
selector.add_reader(socket, lambda *args: f())
if evt... | the_stack_v2_python_sparse | contrib/python/pyzmq/py3/zmq/asyncio.py | catboost/catboost | train | 8,012 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.