blob_id
stringlengths
40
40
bodies
listlengths
2
6
bodies_text
stringlengths
196
7.73k
class_docstring
stringlengths
0
700
class_name
stringlengths
1
86
detected_licenses
listlengths
0
45
format_version
stringclasses
1 value
full_text
stringlengths
467
8.64k
id
stringlengths
40
40
length_bytes
int64
515
49.7k
license_type
stringclasses
2 values
methods
listlengths
2
6
n_methods
int64
2
6
original_id
stringlengths
38
40
prompt
stringlengths
160
3.93k
prompted_full_text
stringlengths
681
10.7k
revision_id
stringlengths
40
40
skeleton
stringlengths
162
4.09k
snapshot_name
stringclasses
1 value
snapshot_source_dir
stringclasses
1 value
solution
stringlengths
331
8.3k
source
stringclasses
1 value
source_path
stringlengths
5
177
source_repo
stringlengths
6
88
split
stringclasses
1 value
star_events_count
int64
0
209k
4964eb35309f007839db58a757a265390428f46c
[ "if compile:\n regex = re.compile(regex)\nmm = regex.findall(line)\nif mm:\n return mm\nelse:\n return 0", "if compile:\n regex = re.compile(regex)\nmm = regex.match(line)\nif mm != None:\n return mm.groups()\nelse:\n return 0", "if compile:\n regex = re.compile(regex)\nline = regex.sub(s, ...
<|body_start_0|> if compile: regex = re.compile(regex) mm = regex.findall(line) if mm: return mm else: return 0 <|end_body_0|> <|body_start_1|> if compile: regex = re.compile(regex) mm = regex.match(line) if mm != N...
regular expression functions
Lib
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Lib: """regular expression functions""" def FindAll(self, line, regex, compile=0): """find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?""" <|body_0|> def Match(self, line, regex, compile=0): """find regex 'regex' ...
stack_v2_sparse_classes_10k_train_005200
1,115
no_license
[ { "docstring": "find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?", "name": "FindAll", "signature": "def FindAll(self, line, regex, compile=0)" }, { "docstring": "find regex 'regex' in string 'line' compile: must we compile a regex before, or is ...
3
stack_v2_sparse_classes_30k_train_003264
Implement the Python class `Lib` described below. Class description: regular expression functions Method signatures and docstrings: - def FindAll(self, line, regex, compile=0): find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled? - def Match(self, line, regex, compile=0)...
Implement the Python class `Lib` described below. Class description: regular expression functions Method signatures and docstrings: - def FindAll(self, line, regex, compile=0): find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled? - def Match(self, line, regex, compile=0)...
3cfcae894c165189cc3ff61e27ca284f09e87871
<|skeleton|> class Lib: """regular expression functions""" def FindAll(self, line, regex, compile=0): """find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?""" <|body_0|> def Match(self, line, regex, compile=0): """find regex 'regex' ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Lib: """regular expression functions""" def FindAll(self, line, regex, compile=0): """find all regex 'regex' in string 'line' compile: must we compile a regex before, or is it compiled?""" if compile: regex = re.compile(regex) mm = regex.findall(line) if mm: ...
the_stack_v2_python_sparse
dmerce2/Core/RegExp.py
rbe/dmerce
train
0
9ea1c2746cd676d8a16df87e9b920ae9f6c52dd6
[ "top_n = 2\nseq_length = 4\nxlnet_base = _get_xlnet_base()\nxlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), span_labeling_activation='tanh', dropout_rate=0.1)\ninputs = dict(input_word_ids=tf.keras.layer...
<|body_start_0|> top_n = 2 seq_length = 4 xlnet_base = _get_xlnet_base() xlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), span_labeling_activation='tanh', dropout_rate=0.1) ...
XLNetSpanLabelerTest
[ "Apache-2.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class XLNetSpanLabelerTest: def test_xlnet_trainer(self): """Validate that the Keras object can be created.""" <|body_0|> def test_serialize_deserialize(self): """Validates that the XLNet trainer can be serialized and deserialized.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_10k_train_005201
13,124
permissive
[ { "docstring": "Validate that the Keras object can be created.", "name": "test_xlnet_trainer", "signature": "def test_xlnet_trainer(self)" }, { "docstring": "Validates that the XLNet trainer can be serialized and deserialized.", "name": "test_serialize_deserialize", "signature": "def tes...
2
stack_v2_sparse_classes_30k_train_000696
Implement the Python class `XLNetSpanLabelerTest` described below. Class description: Implement the XLNetSpanLabelerTest class. Method signatures and docstrings: - def test_xlnet_trainer(self): Validate that the Keras object can be created. - def test_serialize_deserialize(self): Validates that the XLNet trainer can ...
Implement the Python class `XLNetSpanLabelerTest` described below. Class description: Implement the XLNetSpanLabelerTest class. Method signatures and docstrings: - def test_xlnet_trainer(self): Validate that the Keras object can be created. - def test_serialize_deserialize(self): Validates that the XLNet trainer can ...
6fc53292b1d3ce3c0340ce724c2c11c77e663d27
<|skeleton|> class XLNetSpanLabelerTest: def test_xlnet_trainer(self): """Validate that the Keras object can be created.""" <|body_0|> def test_serialize_deserialize(self): """Validates that the XLNet trainer can be serialized and deserialized.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class XLNetSpanLabelerTest: def test_xlnet_trainer(self): """Validate that the Keras object can be created.""" top_n = 2 seq_length = 4 xlnet_base = _get_xlnet_base() xlnet_trainer_model = xlnet.XLNetSpanLabeler(network=xlnet_base, start_n_top=top_n, end_n_top=top_n, initiali...
the_stack_v2_python_sparse
models/official/nlp/modeling/models/xlnet_test.py
aboerzel/German_License_Plate_Recognition
train
34
8a7959652c3ad690e8f5536089b278135343e145
[ "dp = [0] * (n + 1)\ndp[0], dp[1] = (1, 1)\nfor i in range(2, n + 1):\n for j in range(i):\n dp[i] += dp[j] * dp[i - j - 1]\nreturn dp[n]", "dp = [[False for i in range(n)] for j in range(n)]\n\ndef dfs(left, right, x):\n if dp[len(left)][len(right)] != False:\n return dp[len(left)][len(right)...
<|body_start_0|> dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[n] <|end_body_0|> <|body_start_1|> dp = [[False for i in range(n)] for j in range(n)] def dfs(left...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def numTrees(self, n): """:type n: int :rtype: int""" <|body_0|> def numTrees_rec(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range...
stack_v2_sparse_classes_10k_train_005202
1,585
no_license
[ { "docstring": ":type n: int :rtype: int", "name": "numTrees", "signature": "def numTrees(self, n)" }, { "docstring": ":type n: int :rtype: int", "name": "numTrees_rec", "signature": "def numTrees_rec(self, n)" } ]
2
stack_v2_sparse_classes_30k_train_005684
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numTrees(self, n): :type n: int :rtype: int - def numTrees_rec(self, n): :type n: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def numTrees(self, n): :type n: int :rtype: int - def numTrees_rec(self, n): :type n: int :rtype: int <|skeleton|> class Solution: def numTrees(self, n): """:type n...
ed0837ce14a22660657ffd15ff99d7cb1804e8c1
<|skeleton|> class Solution: def numTrees(self, n): """:type n: int :rtype: int""" <|body_0|> def numTrees_rec(self, n): """:type n: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def numTrees(self, n): """:type n: int :rtype: int""" dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[n] def numTrees_rec(self, n): """:type...
the_stack_v2_python_sparse
python/096-unique-binary-search-trees.py
ByronHsu/leetcode
train
5
39a350c094dc6dfa2cc94d925aedccaa2cea19e7
[ "quadrado = Quadrado()\nquadrado.lado = 4\nself.assertEquals(4, quadrado.RetornaLado())", "quadrado = Quadrado()\nquadrado.lado = 3\nself.assertEquals(9, quadrado.CalcularArea())" ]
<|body_start_0|> quadrado = Quadrado() quadrado.lado = 4 self.assertEquals(4, quadrado.RetornaLado()) <|end_body_0|> <|body_start_1|> quadrado = Quadrado() quadrado.lado = 3 self.assertEquals(9, quadrado.CalcularArea()) <|end_body_1|>
MyQuadradoTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MyQuadradoTest: def testRetornaLado(self): """Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.""" <|body_0|> def testeCalcularArea(self): """Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos.""" ...
stack_v2_sparse_classes_10k_train_005203
784
no_license
[ { "docstring": "Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.", "name": "testRetornaLado", "signature": "def testRetornaLado(self)" }, { "docstring": "Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos.", "name": "testeCalcul...
2
stack_v2_sparse_classes_30k_train_003270
Implement the Python class `MyQuadradoTest` described below. Class description: Implement the MyQuadradoTest class. Method signatures and docstrings: - def testRetornaLado(self): Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos. - def testeCalcularArea(self): Função que testa o método...
Implement the Python class `MyQuadradoTest` described below. Class description: Implement the MyQuadradoTest class. Method signatures and docstrings: - def testRetornaLado(self): Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos. - def testeCalcularArea(self): Função que testa o método...
0ebcb2da872fcd5c101826455710634a3e6e69cb
<|skeleton|> class MyQuadradoTest: def testRetornaLado(self): """Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.""" <|body_0|> def testeCalcularArea(self): """Função que testa o método 'CalculaArea' da classe Quadrado :return: sem retornos.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MyQuadradoTest: def testRetornaLado(self): """Função que testa o método 'Retorna Lado' da classe Quadrado :return: sem retornos.""" quadrado = Quadrado() quadrado.lado = 4 self.assertEquals(4, quadrado.RetornaLado()) def testeCalcularArea(self): """Função que testa...
the_stack_v2_python_sparse
Projeto_Testes/First_TDD_File.py
gnfandrade/Projetos_Python
train
0
69cd7a004977df6951dda67690458c86b1397761
[ "if isinstance(expressions, tuple):\n expressions = [expressions]\nmasks = [list(comp(self.loc[:, method], thr)) for method, comp, thr in expressions]\nif len(masks) > 1:\n masks = numpy.logical_and(*masks)\nelse:\n masks = masks[0]\nreturn TAPPredictionResult(self.loc[masks, :])", "if type(others) == ty...
<|body_start_0|> if isinstance(expressions, tuple): expressions = [expressions] masks = [list(comp(self.loc[:, method], thr)) for method, comp, thr in expressions] if len(masks) > 1: masks = numpy.logical_and(*masks) else: masks = masks[0] retu...
A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object TAPPredictionResult: +--------------+-------------+ | Peptide Obj | Me...
TAPPredictionResult
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TAPPredictionResult: """A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object TAPPredictionResult: +-...
stack_v2_sparse_classes_10k_train_005204
14,645
permissive
[ { "docstring": "Filters a result data frame based on a specified expression consisting of a list of triple with (method_name, comparator, threshold). The expression is applied to each row. If any of the columns fulfill the criteria the row remains. :param list((str,comparator,float)) expressions: A list of trip...
2
null
Implement the Python class `TAPPredictionResult` described below. Class description: A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide....
Implement the Python class `TAPPredictionResult` described below. Class description: A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide....
b3e54c8c4ed12b780b61f74672e9667245a7bb78
<|skeleton|> class TAPPredictionResult: """A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object TAPPredictionResult: +-...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TAPPredictionResult: """A :class:`~Fred2.Core.Result.TAPPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the ` prediction names of the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object TAPPredictionResult: +--------------...
the_stack_v2_python_sparse
Fred2/Core/Result.py
FRED-2/Fred2
train
42
a53b851c71f2701570b04278c4125d898602d0d6
[ "kwargs['nargs'] = -1\ndefault = kwargs.pop('default', tuple())\nsuper().__init__(*args, **kwargs)\nself.default = default", "if not value:\n value = self.default\nelse:\n value = [self._parse_arg_str(i) for i in value]\nreturn super().process_value(ctx, value)", "parsed = ast.literal_eval(args)\nif not i...
<|body_start_0|> kwargs['nargs'] = -1 default = kwargs.pop('default', tuple()) super().__init__(*args, **kwargs) self.default = default <|end_body_0|> <|body_start_1|> if not value: value = self.default else: value = [self._parse_arg_str(i) for i ...
Multiple arguments with default value.
DefaultArgumentsMultiple
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DefaultArgumentsMultiple: """Multiple arguments with default value.""" def __init__(self, *args: Any, **kwargs: Any) -> None: """Create MultipleArguments instance.""" <|body_0|> def full_process_value(self, ctx: Context, value: Any) -> Any: """Given a value and c...
stack_v2_sparse_classes_10k_train_005205
10,471
permissive
[ { "docstring": "Create MultipleArguments instance.", "name": "__init__", "signature": "def __init__(self, *args: Any, **kwargs: Any) -> None" }, { "docstring": "Given a value and context this runs the logic to convert the value as necessary. :param ctx: command context :param value: value for op...
3
null
Implement the Python class `DefaultArgumentsMultiple` described below. Class description: Multiple arguments with default value. Method signatures and docstrings: - def __init__(self, *args: Any, **kwargs: Any) -> None: Create MultipleArguments instance. - def full_process_value(self, ctx: Context, value: Any) -> Any...
Implement the Python class `DefaultArgumentsMultiple` described below. Class description: Multiple arguments with default value. Method signatures and docstrings: - def __init__(self, *args: Any, **kwargs: Any) -> None: Create MultipleArguments instance. - def full_process_value(self, ctx: Context, value: Any) -> Any...
bec49adaeba661d8d0f03ac9935dc89f39d95a0d
<|skeleton|> class DefaultArgumentsMultiple: """Multiple arguments with default value.""" def __init__(self, *args: Any, **kwargs: Any) -> None: """Create MultipleArguments instance.""" <|body_0|> def full_process_value(self, ctx: Context, value: Any) -> Any: """Given a value and c...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DefaultArgumentsMultiple: """Multiple arguments with default value.""" def __init__(self, *args: Any, **kwargs: Any) -> None: """Create MultipleArguments instance.""" kwargs['nargs'] = -1 default = kwargs.pop('default', tuple()) super().__init__(*args, **kwargs) se...
the_stack_v2_python_sparse
benchmark/framework/cli.py
fetchai/agents-aea
train
192
dafeb5ffc6685f724a581d5e9d23054b7d161d71
[ "pos_bboxes_list = [res.pos_bboxes for res in sampling_results]\nneg_bboxes_list = [res.neg_bboxes for res in sampling_results]\npos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results]\npos_gt_labels_list = [res.pos_gt_labels for res in sampling_results]\nlabels, label_weights, bbox_targets, bbox_weigh...
<|body_start_0|> pos_bboxes_list = [res.pos_bboxes for res in sampling_results] neg_bboxes_list = [res.neg_bboxes for res in sampling_results] pos_gt_bboxes_list = [res.pos_gt_bboxes for res in sampling_results] pos_gt_labels_list = [res.pos_gt_labels for res in sampling_results] ...
CustomConvFCBBoxHead class for OTX.
CustomConvFCBBoxHead
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CustomConvFCBBoxHead: """CustomConvFCBBoxHead class for OTX.""" def get_targets(self, sampling_results, gt_bboxes, gt_labels, img_metas, rcnn_train_cfg, concat=True): """Calculate the ground truth for all samples in a batch according to the sampling_results. Almost the same as the im...
stack_v2_sparse_classes_10k_train_005206
8,559
permissive
[ { "docstring": "Calculate the ground truth for all samples in a batch according to the sampling_results. Almost the same as the implementation in bbox_head, we passed additional parameters pos_inds_list and neg_inds_list to `_get_target_single` function. Args: sampling_results (List[obj:SamplingResults]): Assig...
2
null
Implement the Python class `CustomConvFCBBoxHead` described below. Class description: CustomConvFCBBoxHead class for OTX. Method signatures and docstrings: - def get_targets(self, sampling_results, gt_bboxes, gt_labels, img_metas, rcnn_train_cfg, concat=True): Calculate the ground truth for all samples in a batch acc...
Implement the Python class `CustomConvFCBBoxHead` described below. Class description: CustomConvFCBBoxHead class for OTX. Method signatures and docstrings: - def get_targets(self, sampling_results, gt_bboxes, gt_labels, img_metas, rcnn_train_cfg, concat=True): Calculate the ground truth for all samples in a batch acc...
80454808b38727e358e8b880043eeac0f18152fb
<|skeleton|> class CustomConvFCBBoxHead: """CustomConvFCBBoxHead class for OTX.""" def get_targets(self, sampling_results, gt_bboxes, gt_labels, img_metas, rcnn_train_cfg, concat=True): """Calculate the ground truth for all samples in a batch according to the sampling_results. Almost the same as the im...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CustomConvFCBBoxHead: """CustomConvFCBBoxHead class for OTX.""" def get_targets(self, sampling_results, gt_bboxes, gt_labels, img_metas, rcnn_train_cfg, concat=True): """Calculate the ground truth for all samples in a batch according to the sampling_results. Almost the same as the implementation ...
the_stack_v2_python_sparse
src/otx/algorithms/detection/adapters/mmdet/models/heads/custom_roi_head.py
openvinotoolkit/training_extensions
train
397
c65202139a2349f4634690195a93f3f433673a1d
[ "import_info.pop(CONF_MONITORED_CONDITIONS, None)\nimport_info.pop(CONF_NICS, None)\nimport_info.pop(CONF_DRIVES, None)\nimport_info.pop(CONF_VOLUMES, None)\nreturn await self.async_step_user(import_info)", "errors = {}\nif user_input is not None:\n host = user_input[CONF_HOST]\n protocol = 'https' if user_...
<|body_start_0|> import_info.pop(CONF_MONITORED_CONDITIONS, None) import_info.pop(CONF_NICS, None) import_info.pop(CONF_DRIVES, None) import_info.pop(CONF_VOLUMES, None) return await self.async_step_user(import_info) <|end_body_0|> <|body_start_1|> errors = {} if...
Qnap configuration flow.
QnapConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class QnapConfigFlow: """Qnap configuration flow.""" async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: """Set the config entry up from yaml.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: ...
stack_v2_sparse_classes_10k_train_005207
3,220
permissive
[ { "docstring": "Set the config entry up from yaml.", "name": "async_step_import", "signature": "async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult" }, { "docstring": "Handle a flow initialized by the user.", "name": "async_step_user", "signature": "async def asy...
2
stack_v2_sparse_classes_30k_train_006153
Implement the Python class `QnapConfigFlow` described below. Class description: Qnap configuration flow. Method signatures and docstrings: - async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: Set the config entry up from yaml. - async def async_step_user(self, user_input: dict[str, Any] | N...
Implement the Python class `QnapConfigFlow` described below. Class description: Qnap configuration flow. Method signatures and docstrings: - async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: Set the config entry up from yaml. - async def async_step_user(self, user_input: dict[str, Any] | N...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class QnapConfigFlow: """Qnap configuration flow.""" async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: """Set the config entry up from yaml.""" <|body_0|> async def async_step_user(self, user_input: dict[str, Any] | None=None) -> FlowResult: ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class QnapConfigFlow: """Qnap configuration flow.""" async def async_step_import(self, import_info: dict[str, Any]) -> FlowResult: """Set the config entry up from yaml.""" import_info.pop(CONF_MONITORED_CONDITIONS, None) import_info.pop(CONF_NICS, None) import_info.pop(CONF_DRIV...
the_stack_v2_python_sparse
homeassistant/components/qnap/config_flow.py
home-assistant/core
train
35,501
0eb09798c0258e0ed3a5b4bbaaa575446bdc483d
[ "self.frame_type_link = frame_type_link\nself.a_frame_inst = a_frame_inst\nself.b_frame_inst = b_frame_inst\nself.frame_inst_arg_links = []\na_frame_inst.link = self\nb_frame_inst.link = self\nself._link_args()", "a_frame_inst_args = self.a_frame_inst.args\nb_frame_inst_args = self.b_frame_inst.args\nfor a_frame_...
<|body_start_0|> self.frame_type_link = frame_type_link self.a_frame_inst = a_frame_inst self.b_frame_inst = b_frame_inst self.frame_inst_arg_links = [] a_frame_inst.link = self b_frame_inst.link = self self._link_args() <|end_body_0|> <|body_start_1|> a_...
Frame_inst_link
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Frame_inst_link: def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): """called from Frame_type_link.link_frame_insts""" <|body_0|> def _link_args(self): """called from __init__""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.frame_...
stack_v2_sparse_classes_10k_train_005208
6,044
no_license
[ { "docstring": "called from Frame_type_link.link_frame_insts", "name": "__init__", "signature": "def __init__(self, frame_type_link, a_frame_inst, b_frame_inst)" }, { "docstring": "called from __init__", "name": "_link_args", "signature": "def _link_args(self)" } ]
2
stack_v2_sparse_classes_30k_train_000676
Implement the Python class `Frame_inst_link` described below. Class description: Implement the Frame_inst_link class. Method signatures and docstrings: - def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): called from Frame_type_link.link_frame_insts - def _link_args(self): called from __init__
Implement the Python class `Frame_inst_link` described below. Class description: Implement the Frame_inst_link class. Method signatures and docstrings: - def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): called from Frame_type_link.link_frame_insts - def _link_args(self): called from __init__ <|skelet...
194446ec1adeec5ef85db3f96b6d8d2876cc8811
<|skeleton|> class Frame_inst_link: def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): """called from Frame_type_link.link_frame_insts""" <|body_0|> def _link_args(self): """called from __init__""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Frame_inst_link: def __init__(self, frame_type_link, a_frame_inst, b_frame_inst): """called from Frame_type_link.link_frame_insts""" self.frame_type_link = frame_type_link self.a_frame_inst = a_frame_inst self.b_frame_inst = b_frame_inst self.frame_inst_arg_links = [] ...
the_stack_v2_python_sparse
udapi-python/udapi/block/valency/link_structures.py
Jankus1994/ud-valency
train
0
47a8a465a6a83d067d67917f1fdbb99fe4afc63c
[ "if len(li) <= 0:\n return False\nif len(li) == 1:\n return ListNode(li[0])\nelse:\n root = ListNode(li[0])\n tmp = root\n for i in range(1, len(li)):\n tmp.next = ListNode(li[i])\n tmp = tmp.next\n return root", "value = []\ntmp = root\nwhile tmp.next != None:\n value.append(st...
<|body_start_0|> if len(li) <= 0: return False if len(li) == 1: return ListNode(li[0]) else: root = ListNode(li[0]) tmp = root for i in range(1, len(li)): tmp.next = ListNode(li[i]) tmp = tmp.next ...
ListNode_handle
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ListNode_handle: def Creatlist(self, li): """从列表创建一个链表 :param li: 列表 :return: 头结点""" <|body_0|> def print_linked(self, root: ListNode): """打印链表 :param root: 头结点 :return: 打印链表""" <|body_1|> def length(self, root): """计算链表的长度 :param root: :return:"...
stack_v2_sparse_classes_10k_train_005209
3,869
no_license
[ { "docstring": "从列表创建一个链表 :param li: 列表 :return: 头结点", "name": "Creatlist", "signature": "def Creatlist(self, li)" }, { "docstring": "打印链表 :param root: 头结点 :return: 打印链表", "name": "print_linked", "signature": "def print_linked(self, root: ListNode)" }, { "docstring": "计算链表的长度 :pa...
5
stack_v2_sparse_classes_30k_train_002753
Implement the Python class `ListNode_handle` described below. Class description: Implement the ListNode_handle class. Method signatures and docstrings: - def Creatlist(self, li): 从列表创建一个链表 :param li: 列表 :return: 头结点 - def print_linked(self, root: ListNode): 打印链表 :param root: 头结点 :return: 打印链表 - def length(self, root)...
Implement the Python class `ListNode_handle` described below. Class description: Implement the ListNode_handle class. Method signatures and docstrings: - def Creatlist(self, li): 从列表创建一个链表 :param li: 列表 :return: 头结点 - def print_linked(self, root: ListNode): 打印链表 :param root: 头结点 :return: 打印链表 - def length(self, root)...
2ef266ee3175d08d125151c9983b864e6ed3343b
<|skeleton|> class ListNode_handle: def Creatlist(self, li): """从列表创建一个链表 :param li: 列表 :return: 头结点""" <|body_0|> def print_linked(self, root: ListNode): """打印链表 :param root: 头结点 :return: 打印链表""" <|body_1|> def length(self, root): """计算链表的长度 :param root: :return:"...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ListNode_handle: def Creatlist(self, li): """从列表创建一个链表 :param li: 列表 :return: 头结点""" if len(li) <= 0: return False if len(li) == 1: return ListNode(li[0]) else: root = ListNode(li[0]) tmp = root for i in range(1, len(l...
the_stack_v2_python_sparse
leetcode/0001-0100/0019.删除链表的倒数第n个结点.py
alpharol/algorithm_python3
train
1
87cc971945e216c065217371ffee3ebaca09f943
[ "entry_frm = form.FormNode(self.name)\nentry_frm(value=getattr(storable, self.get_column_name(), self.get('default_value', '')))\nif style == 'listing' or self.get('read_only', False):\n entry_frm(type='label')\n if self.get('obfuscate', True):\n entry_frm(value='********')\n return entry_frm\nelif ...
<|body_start_0|> entry_frm = form.FormNode(self.name) entry_frm(value=getattr(storable, self.get_column_name(), self.get('default_value', ''))) if style == 'listing' or self.get('read_only', False): entry_frm(type='label') if self.get('obfuscate', True): e...
Allow editing of an optionally encrypted password field.
PasswordField
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PasswordField: """Allow editing of an optionally encrypted password field.""" def get_element(self, req, style, storable): """@see: L{modu.editable.define.definition.get_element()}""" <|body_0|> def update_storable(self, req, form, storable): """@see: L{modu.edit...
stack_v2_sparse_classes_10k_train_005210
6,918
permissive
[ { "docstring": "@see: L{modu.editable.define.definition.get_element()}", "name": "get_element", "signature": "def get_element(self, req, style, storable)" }, { "docstring": "@see: L{modu.editable.define.definition.update_storable()}", "name": "update_storable", "signature": "def update_s...
2
stack_v2_sparse_classes_30k_train_001082
Implement the Python class `PasswordField` described below. Class description: Allow editing of an optionally encrypted password field. Method signatures and docstrings: - def get_element(self, req, style, storable): @see: L{modu.editable.define.definition.get_element()} - def update_storable(self, req, form, storabl...
Implement the Python class `PasswordField` described below. Class description: Allow editing of an optionally encrypted password field. Method signatures and docstrings: - def get_element(self, req, style, storable): @see: L{modu.editable.define.definition.get_element()} - def update_storable(self, req, form, storabl...
795f3bc413956b98522ac514dafe35cbab0d57a3
<|skeleton|> class PasswordField: """Allow editing of an optionally encrypted password field.""" def get_element(self, req, style, storable): """@see: L{modu.editable.define.definition.get_element()}""" <|body_0|> def update_storable(self, req, form, storable): """@see: L{modu.edit...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PasswordField: """Allow editing of an optionally encrypted password field.""" def get_element(self, req, style, storable): """@see: L{modu.editable.define.definition.get_element()}""" entry_frm = form.FormNode(self.name) entry_frm(value=getattr(storable, self.get_column_name(), se...
the_stack_v2_python_sparse
src/modu/editable/datatypes/string.py
philchristensen/modu
train
0
d8a171b8c2a82b1ea59cb6027c59d1c995dd657b
[ "def helper(p1, p2):\n if p1 and p2:\n return p1.val == p2.val and helper(p1.left, p2.right) and helper(p1.right, p2.left)\n else:\n return p1 is p2\nif root is None:\n return True\nelse:\n return helper(root.left, root.right)", "if root is None:\n return True\np1 = root.left\np2 = ro...
<|body_start_0|> def helper(p1, p2): if p1 and p2: return p1.val == p2.val and helper(p1.left, p2.right) and helper(p1.right, p2.left) else: return p1 is p2 if root is None: return True else: return helper(root.left,...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def isSymmetric(self, root): """When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetricIterative(self, root): """Using it...
stack_v2_sparse_classes_10k_train_005211
1,950
no_license
[ { "docstring": "When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool", "name": "isSymmetric", "signature": "def isSymmetric(self, root)" }, { "docstring": "Using iterative :param root: :r...
2
stack_v2_sparse_classes_30k_train_001212
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def isSymmetric(self, root): When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode ...
11d6bf2ba7b50c07e048df37c4e05c8f46b92241
<|skeleton|> class Solution: def isSymmetric(self, root): """When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool""" <|body_0|> def isSymmetricIterative(self, root): """Using it...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def isSymmetric(self, root): """When need to compare left and right part at same level together, than separate original tree to several subTrees is a solution. :type root: TreeNode :rtype: bool""" def helper(p1, p2): if p1 and p2: return p1.val == p2.val a...
the_stack_v2_python_sparse
LeetCodes/DFS/SymmetricTree.py
chutianwen/LeetCodes
train
0
0d4f7d61f4a35c62f973ef175267e9b3999931d0
[ "self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100')\nself.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100')\nself.bakery = Company.objects.create(name='bakery', caffe=self.ca...
<|body_start_0|> self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', street='Filry', house_number='14', postal_code='44-100') self.bakery = Company.objects.c...
Company model tests.
CompanyModelTest
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompanyModelTest: """Company model tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_name(self): """Check if name is unique across one caffe.""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.caffe = Caffe.objects.create(n...
stack_v2_sparse_classes_10k_train_005212
8,665
permissive
[ { "docstring": "Test data setup.", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Check if name is unique across one caffe.", "name": "test_name", "signature": "def test_name(self)" } ]
2
stack_v2_sparse_classes_30k_train_003230
Implement the Python class `CompanyModelTest` described below. Class description: Company model tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_name(self): Check if name is unique across one caffe.
Implement the Python class `CompanyModelTest` described below. Class description: Company model tests. Method signatures and docstrings: - def setUp(self): Test data setup. - def test_name(self): Check if name is unique across one caffe. <|skeleton|> class CompanyModelTest: """Company model tests.""" def se...
cdb7f5edb29255c7e874eaa6231621063210a8b0
<|skeleton|> class CompanyModelTest: """Company model tests.""" def setUp(self): """Test data setup.""" <|body_0|> def test_name(self): """Check if name is unique across one caffe.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CompanyModelTest: """Company model tests.""" def setUp(self): """Test data setup.""" self.caffe = Caffe.objects.create(name='kafo', city='Gliwice', street='Wieczorka', house_number='14', postal_code='44-100') self.filtry = Caffe.objects.create(name='filtry', city='Warszawa', stree...
the_stack_v2_python_sparse
caffe/cash/test_models.py
VirrageS/io-kawiarnie
train
3
619f2cff6e97da7a8707040c73527b2da13c2190
[ "if len(xcols) == 0 or xcols is None:\n return 0.0\nsample_size = len(df.index)\ndf1 = df.copy()\ndf1 = df1.groupby(xcols)[xcols].size()\ndf1 = df1.apply(lambda x: x / sample_size)\nlocal_ent = -df1 * np.log(df1 + 1e-07)\nall_ent = local_ent.sum()\nif verbose:\n print('\\nprobs for ', xcols)\n print(df1)\n...
<|body_start_0|> if len(xcols) == 0 or xcols is None: return 0.0 sample_size = len(df.index) df1 = df.copy() df1 = df1.groupby(xcols)[xcols].size() df1 = df1.apply(lambda x: x / sample_size) local_ent = -df1 * np.log(df1 + 1e-07) all_ent = local_ent.su...
This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs's in entropies are base e, natural logs Error in entropy is ln(n+1) - ln(n) ...
DataEntropy
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataEntropy: """This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs's in entropies are base e, natural log...
stack_v2_sparse_classes_10k_train_005213
5,703
permissive
[ { "docstring": "Returns the entropy H(x) where x is given by the list of columns xcols in the dataframe df. Parameters ---------- df : pandas.DataFrame dataframe for which entropy is calculated xcols : list[str] list of column names in df. The x in H(x) verbose : bool If True, print extra info in console. Retur...
4
stack_v2_sparse_classes_30k_train_002373
Implement the Python class `DataEntropy` described below. Class description: This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs...
Implement the Python class `DataEntropy` described below. Class description: This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs...
5b4a3055ea14c2ee9c80c339f759fe2b9c8c51e2
<|skeleton|> class DataEntropy: """This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs's in entropies are base e, natural log...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DataEntropy: """This class calculates classical (not quantum yet) entropy, conditional information (CI), mutual information (MI) and conditional mutual info ( CMI) from a dataframe (hence, from empirical data, not from the true distributions of a bnet). logs's in entropies are base e, natural logs Error in en...
the_stack_v2_python_sparse
shannon_info_theory/DataEntropy.py
artiste-qb-net/quantum-fog
train
95
5438d06bdd1830e1613cd34df1fb13235798e29b
[ "for i in range(len(s)):\n t = s[:i] + s[i + 1:]\n if t == t[::-1]:\n return True\nreturn s == s[::-1]", "def is_pali_range(i, j):\n return all((s[k] == s[j - k + i] for k in range(i, j)))\nfor i in range(len(s) / 2):\n if s[i] != s[~i]:\n j = len(s) - 1 - i\n return is_pali_range...
<|body_start_0|> for i in range(len(s)): t = s[:i] + s[i + 1:] if t == t[::-1]: return True return s == s[::-1] <|end_body_0|> <|body_start_1|> def is_pali_range(i, j): return all((s[k] == s[j - k + i] for k in range(i, j))) for i in r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def validPalindrome(self, s: str) -> bool: """For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if the original string was a palindrome), then we'll return true""" <|body_0|> def val...
stack_v2_sparse_classes_10k_train_005214
1,977
no_license
[ { "docstring": "For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if the original string was a palindrome), then we'll return true", "name": "validPalindrome", "signature": "def validPalindrome(self, s: str) -> bool" },...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validPalindrome(self, s: str) -> bool: For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def validPalindrome(self, s: str) -> bool: For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if...
727dec2e23e765925a5e7e003fc99aeaf25111e9
<|skeleton|> class Solution: def validPalindrome(self, s: str) -> bool: """For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if the original string was a palindrome), then we'll return true""" <|body_0|> def val...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def validPalindrome(self, s: str) -> bool: """For each index i in the given string, let's remove that character, then check if the resulting string is a palindrome. If it is, (or if the original string was a palindrome), then we'll return true""" for i in range(len(s)): t...
the_stack_v2_python_sparse
funNLearn/src/main/java/dsAlgo/leetcode/P6xx/P680_ValidPalindromeII.py
vishalpmittal/practice-fun
train
0
25385a28f0f74829106862d6042db499eda90493
[ "self._has_been_validated: bool = False\nself._source_names: Set[SourceName] = {GITHUB, GITLAB, BITBUCKET}\nself.protocol_override: Optional[Protocol] = None\nself._sources: Dict[SourceName, Source] = {GITHUB: Source(GITHUB, GITHUB_YAML), GITLAB: Source(GITLAB, GITLAB_YAML), BITBUCKET: Source(BITBUCKET, BITBUCKET_Y...
<|body_start_0|> self._has_been_validated: bool = False self._source_names: Set[SourceName] = {GITHUB, GITLAB, BITBUCKET} self.protocol_override: Optional[Protocol] = None self._sources: Dict[SourceName, Source] = {GITHUB: Source(GITHUB, GITHUB_YAML), GITLAB: Source(GITLAB, GITLAB_YAML),...
Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol
SourceController
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SourceController: """Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol""" def __init__(self): """SourceController __init__""" <|body...
stack_v2_sparse_classes_10k_train_005215
3,873
permissive
[ { "docstring": "SourceController __init__", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Register source with controller :param Optional[Union[Source, SourceName]] source: Source to add :raise SourcesValidatedError: :raise UnknownTypeError:", "name": "add_source",...
5
stack_v2_sparse_classes_30k_train_005863
Implement the Python class `SourceController` described below. Class description: Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol Method signatures and docstrings: - def __...
Implement the Python class `SourceController` described below. Class description: Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol Method signatures and docstrings: - def __...
1438fc8b1bb7379de66142ffcb0e20b459b59159
<|skeleton|> class SourceController: """Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol""" def __init__(self): """SourceController __init__""" <|body...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SourceController: """Class encapsulating project information from clowder yaml for controlling clowder :ivar Optional[str] protocol_override: The protocol to override sources without an explicitly specified protcol""" def __init__(self): """SourceController __init__""" self._has_been_vali...
the_stack_v2_python_sparse
clowder/controller/source_controller.py
JrGoodle/clowder
train
17
2c211f1fb3b4ccf847ff2a4dbbe6683c999d96f0
[ "revoked_token = self._client.revoke_token(token=token)\nif check:\n self.check_token_is_revoked(revoked_token, must_revoked=False)\nreturn revoked_token", "def predicate():\n try:\n self.get_token_validate(token)\n is_revoked = True\n except exceptions.NotFound:\n is_revoked = False...
<|body_start_0|> revoked_token = self._client.revoke_token(token=token) if check: self.check_token_is_revoked(revoked_token, must_revoked=False) return revoked_token <|end_body_0|> <|body_start_1|> def predicate(): try: self.get_token_validate(tok...
Token steps.
TokenSteps
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TokenSteps: """Token steps.""" def revoke_token(self, token, check=True): """Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.AccessInfo: token""" <|body_0|> def check_token...
stack_v2_sparse_classes_10k_train_005216
4,425
no_license
[ { "docstring": "Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.AccessInfo: token", "name": "revoke_token", "signature": "def revoke_token(self, token, check=True)" }, { "docstring": "Step to check...
4
null
Implement the Python class `TokenSteps` described below. Class description: Token steps. Method signatures and docstrings: - def revoke_token(self, token, check=True): Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.Acc...
Implement the Python class `TokenSteps` described below. Class description: Token steps. Method signatures and docstrings: - def revoke_token(self, token, check=True): Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.Acc...
e7583444cd24893ec6ae237b47db7c605b99b0c5
<|skeleton|> class TokenSteps: """Token steps.""" def revoke_token(self, token, check=True): """Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.AccessInfo: token""" <|body_0|> def check_token...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TokenSteps: """Token steps.""" def revoke_token(self, token, check=True): """Step to revoke a token. Args: token (str): The token to be revoked. check (bool): flag whether to check step or not Returns: keystoneclient.access.AccessInfo: token""" revoked_token = self._client.revoke_token(to...
the_stack_v2_python_sparse
stepler/keystone/steps/tokens.py
Mirantis/stepler
train
16
0c3bce9b67a34ced9fc31d42e5e753770d9e0ebe
[ "if name is not None:\n pulumi.set(__self__, 'name', name)\nif value is not None:\n pulumi.set(__self__, 'value', value)", "warnings.warn(\"Field 'parameters' has been deprecated from version 1.101.0. Use 'config' instead.\", DeprecationWarning)\npulumi.log.warn(\"name is deprecated: Field 'parameters' has ...
<|body_start_0|> if name is not None: pulumi.set(__self__, 'name', name) if value is not None: pulumi.set(__self__, 'value', value) <|end_body_0|> <|body_start_1|> warnings.warn("Field 'parameters' has been deprecated from version 1.101.0. Use 'config' instead.", Depreca...
InstanceParameter
[ "Apache-2.0", "MPL-2.0", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class InstanceParameter: def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): """:param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version...
stack_v2_sparse_classes_10k_train_005217
32,429
permissive
[ { "docstring": ":param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead.", "name": "__init__", "signature": "def __init__(__self__, *, name: Opt...
3
null
Implement the Python class `InstanceParameter` described below. Class description: Implement the InstanceParameter class. Method signatures and docstrings: - def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): :param str name: Field `parameters` has been deprecated from provider version 1....
Implement the Python class `InstanceParameter` described below. Class description: Implement the InstanceParameter class. Method signatures and docstrings: - def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): :param str name: Field `parameters` has been deprecated from provider version 1....
ffddb9036f7893fbd58863d8364a4977eb1bee17
<|skeleton|> class InstanceParameter: def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): """:param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class InstanceParameter: def __init__(__self__, *, name: Optional[str]=None, value: Optional[str]=None): """:param str name: Field `parameters` has been deprecated from provider version 1.101.0 and `config` instead. :param str value: Field `parameters` has been deprecated from provider version 1.101.0 and `...
the_stack_v2_python_sparse
sdk/python/pulumi_alicloud/kvstore/outputs.py
pulumi/pulumi-alicloud
train
56
4ba3a0702ff1443ae24fcee69062d3a38329a628
[ "if not head or not head.next:\n return head\ndummy = ListNode(0)\ndummy.next = head\nsize = 0\nwhile head:\n head = head.next\n size += 1\nstep = 1\nwhile step < size:\n curr, tail = (dummy.next, dummy)\n while curr:\n left = curr\n right = self.split(left, step)\n curr = self.s...
<|body_start_0|> if not head or not head.next: return head dummy = ListNode(0) dummy.next = head size = 0 while head: head = head.next size += 1 step = 1 while step < size: curr, tail = (dummy.next, dummy) ...
Node
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Node: def sorted(self, head: 'ListNode') -> 'ListNode': """Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return:""" <|body_0|> def merge(self, left: 'ListNode', right: ListNode, head: 'ListNode') -> 'ListNode': """Merges...
stack_v2_sparse_classes_10k_train_005218
2,250
no_license
[ { "docstring": "Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return:", "name": "sorted", "signature": "def sorted(self, head: 'ListNode') -> 'ListNode'" }, { "docstring": "Merges the left and right after the comparision. :param left: :param right: ...
3
null
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def sorted(self, head: 'ListNode') -> 'ListNode': Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return: - def merge(self, left: 'ListNode',...
Implement the Python class `Node` described below. Class description: Implement the Node class. Method signatures and docstrings: - def sorted(self, head: 'ListNode') -> 'ListNode': Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return: - def merge(self, left: 'ListNode',...
65cc78b5afa0db064f9fe8f06597e3e120f7363d
<|skeleton|> class Node: def sorted(self, head: 'ListNode') -> 'ListNode': """Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return:""" <|body_0|> def merge(self, left: 'ListNode', right: ListNode, head: 'ListNode') -> 'ListNode': """Merges...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Node: def sorted(self, head: 'ListNode') -> 'ListNode': """Sorts the given linked list Time Complexity: O(N log N) Space Complexity: O(1) :param head: :return:""" if not head or not head.next: return head dummy = ListNode(0) dummy.next = head size = 0 ...
the_stack_v2_python_sparse
revisited/linked_list/sort_list.py
Shiv2157k/leet_code
train
1
85f82fd233c92a6959977eda259030bfddc12bc5
[ "self.out = None\nself.in_shape = None\nself.work_shape = None", "assert x.ndim > 1, \"prysm's softmax is meant for use with multiple independent variables at once\"\nxx = x.reshape((-1, x.shape[-1]))\nself.in_shape = x.shape\nself.work_shape = xx.shape\nxnorm = xx - xx.max(axis=1)[:, np.newaxis]\ne_x = np.exp(xn...
<|body_start_0|> self.out = None self.in_shape = None self.work_shape = None <|end_body_0|> <|body_start_1|> assert x.ndim > 1, "prysm's softmax is meant for use with multiple independent variables at once" xx = x.reshape((-1, x.shape[-1])) self.in_shape = x.shape ...
Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and reverse() may take any number of dimensions. The understanding of the inputs...
Softmax
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Softmax: """Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and reverse() may take any number of dimensio...
stack_v2_sparse_classes_10k_train_005219
7,697
permissive
[ { "docstring": "Create a new Softmax node.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Perform Softmax activation on logits. Parameters ---------- x : numpy.ndarray, shape (A,B,C, ... K) any number of leading dimensions, required trailing dimension of size K, where...
3
stack_v2_sparse_classes_30k_train_004875
Implement the Python class `Softmax` described below. Class description: Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and re...
Implement the Python class `Softmax` described below. Class description: Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and re...
af89c94d500a274eda664188ddb97fcae30c6ac5
<|skeleton|> class Softmax: """Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and reverse() may take any number of dimensio...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Softmax: """Softmax activation function. Softmax is a soft, differntiable alternative to argmax. It is used as a component of GumbelSoftmaxEncoder to ecourage / softly force variables to take on one of K discrete states. The arrays passed to forward() and reverse() may take any number of dimensions. The under...
the_stack_v2_python_sparse
prysm/x/optym/activation.py
brandondube/prysm
train
192
06858e122cd77b5879f9ed866db061f9e15a40d8
[ "if 6 * n < s or n < 1 or s < n:\n return 0\nif n == 1:\n return 1\nreturn self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self.getNSumCount(n - 1, s - 4) + self.getNSumCount(n - 1, s - 5) + self.getNSumCount(n - 1, s - 6)", "num = [[0 for j in range(6 *...
<|body_start_0|> if 6 * n < s or n < 1 or s < n: return 0 if n == 1: return 1 return self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self.getNSumCount(n - 1, s - 4) + self.getNSumCount(n - 1, s - 5) + self.getNSumCount...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def getNSumCount(self, n, s): """递归版本 :param n: :param s: :return:""" <|body_0|> def getNSumCountNotRecusion(self, n, s): """非递归版本 :param n: :param s: :return:""" <|body_1|> <|end_skeleton|> <|body_start_0|> if 6 * n < s or n < 1 or s < n:...
stack_v2_sparse_classes_10k_train_005220
1,137
no_license
[ { "docstring": "递归版本 :param n: :param s: :return:", "name": "getNSumCount", "signature": "def getNSumCount(self, n, s)" }, { "docstring": "非递归版本 :param n: :param s: :return:", "name": "getNSumCountNotRecusion", "signature": "def getNSumCountNotRecusion(self, n, s)" } ]
2
stack_v2_sparse_classes_30k_train_006577
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getNSumCount(self, n, s): 递归版本 :param n: :param s: :return: - def getNSumCountNotRecusion(self, n, s): 非递归版本 :param n: :param s: :return:
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def getNSumCount(self, n, s): 递归版本 :param n: :param s: :return: - def getNSumCountNotRecusion(self, n, s): 非递归版本 :param n: :param s: :return: <|skeleton|> class Solution: d...
aec68ce90a9fbceaeb855efc2c83c047acbd53b5
<|skeleton|> class Solution: def getNSumCount(self, n, s): """递归版本 :param n: :param s: :return:""" <|body_0|> def getNSumCountNotRecusion(self, n, s): """非递归版本 :param n: :param s: :return:""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def getNSumCount(self, n, s): """递归版本 :param n: :param s: :return:""" if 6 * n < s or n < 1 or s < n: return 0 if n == 1: return 1 return self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self...
the_stack_v2_python_sparse
offer/offer 60 n个骰子点数.py
clhchtcjj/Algorithm
train
5
f97d52871ded62b9f26250f55632c6776ac9fce2
[ "if paydataobj.GetTrade_type() == 'JSAPI':\n result = WxPayApi.unifiedOrder(paydataobj)\n return result", "if not (unifiedorderresult.has_key('appid') and unifiedorderresult.has_key('prepay_id') and unifiedorderresult.get('prepay_id')):\n raise WxPayException(u'参数错误')\njsapi = WxPayJsApiPay()\njsapi.SetA...
<|body_start_0|> if paydataobj.GetTrade_type() == 'JSAPI': result = WxPayApi.unifiedOrder(paydataobj) return result <|end_body_0|> <|body_start_1|> if not (unifiedorderresult.has_key('appid') and unifiedorderresult.has_key('prepay_id') and unifiedorderresult.get('prepay_id')): ...
/** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */
JsApiPay
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JsApiPay: """/** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */""" def GetPayUrl(self, paydataobj): """生成直接支付url,支付url有效期为2小时 @param UnifiedOrderInput pa...
stack_v2_sparse_classes_10k_train_005221
1,899
no_license
[ { "docstring": "生成直接支付url,支付url有效期为2小时 @param UnifiedOrderInput paydataobj", "name": "GetPayUrl", "signature": "def GetPayUrl(self, paydataobj)" }, { "docstring": "/** * * 获取jsapi支付的参数 * @param array unifiedorderresult 统一支付接口返回的数据 * @throws WxPayException * * @return json数据,可直接填入js函数作为参数 */", ...
2
stack_v2_sparse_classes_30k_train_006867
Implement the Python class `JsApiPay` described below. Class description: /** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */ Method signatures and docstrings: - def GetPayUrl(self, paydat...
Implement the Python class `JsApiPay` described below. Class description: /** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */ Method signatures and docstrings: - def GetPayUrl(self, paydat...
007882f6fcdb85eaef7f40e3180d3c028189f981
<|skeleton|> class JsApiPay: """/** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */""" def GetPayUrl(self, paydataobj): """生成直接支付url,支付url有效期为2小时 @param UnifiedOrderInput pa...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class JsApiPay: """/** * * JSAPI支付实现类 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数 * * 该类是微信支付提供的样例程序,商户可根据自己的需求修改,或者使用lib中的api自行开发 * * @author minkedong * */""" def GetPayUrl(self, paydataobj): """生成直接支付url,支付url有效期为2小时 @param UnifiedOrderInput paydataobj""" ...
the_stack_v2_python_sparse
vip_ticketing_server/wechatpay/wxpay_sdk/WxPayJsApiPay.py
fuguangbei/dev_vip
train
0
a86b02581f06d22d5907fefdb2ff7bb64f911b59
[ "self._pol1, self._pol2 = (pol1, pol2)\nself.deg = self._pol1.deg * self._pol2.deg\n_pol1, _pol2 = (self._pol1.pol[::-1], self._pol2.pol[::-1])\nself.pol = np.zeros((1,))\nfor i in range(pol1.deg + 1):\n self.pol = polyadd(self.pol, _pol1[i] * polypow(_pol2, i))\nself.pol = self.pol[::-1]", "y = self._pol1.eva...
<|body_start_0|> self._pol1, self._pol2 = (pol1, pol2) self.deg = self._pol1.deg * self._pol2.deg _pol1, _pol2 = (self._pol1.pol[::-1], self._pol2.pol[::-1]) self.pol = np.zeros((1,)) for i in range(pol1.deg + 1): self.pol = polyadd(self.pol, _pol1[i] * polypow(_pol2,...
Create polynomial from composition of two others.
CompPol
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CompPol: """Create polynomial from composition of two others.""" def __init__(self, pol1, pol2): """Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\sum_i a_i x^i, g(x) = \\sum_j b_j x^j, with variances \\sigm...
stack_v2_sparse_classes_10k_train_005222
35,535
permissive
[ { "docstring": "Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\\\sum_i a_i x^i, g(x) = \\\\sum_j b_j x^j, with variances \\\\sigma_f and \\\\sigma_g when evaluated (see active_work.maths.Polynomial), we compute \\\\sigma_fg(x) = \\\\si...
2
stack_v2_sparse_classes_30k_train_000413
Implement the Python class `CompPol` described below. Class description: Create polynomial from composition of two others. Method signatures and docstrings: - def __init__(self, pol1, pol2): Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\sum...
Implement the Python class `CompPol` described below. Class description: Create polynomial from composition of two others. Method signatures and docstrings: - def __init__(self, pol1, pol2): Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\sum...
99107a0d4935296b673f67469c1e2bd258954b9b
<|skeleton|> class CompPol: """Create polynomial from composition of two others.""" def __init__(self, pol1, pol2): """Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\sum_i a_i x^i, g(x) = \\sum_j b_j x^j, with variances \\sigm...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CompPol: """Create polynomial from composition of two others.""" def __init__(self, pol1, pol2): """Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance matrices. Considering we have polynomials f(x) = \\sum_i a_i x^i, g(x) = \\sum_j b_j x^j, with variances \\sigma_f and \\sig...
the_stack_v2_python_sparse
maths.py
yketa/active_work
train
1
bee0836d1a0e9050ff63b65281205a654027f71c
[ "lists = filter(lambda x: x is not None, lists)\nif not lists:\n return\nlength = len(lists)\nfactor = 2\nwhile length > 0:\n i = 0\n while True:\n try:\n lists[i] = self.mergeTwoLists(lists[i], lists[i + factor / 2])\n except IndexError:\n break\n i += factor\n ...
<|body_start_0|> lists = filter(lambda x: x is not None, lists) if not lists: return length = len(lists) factor = 2 while length > 0: i = 0 while True: try: lists[i] = self.mergeTwoLists(lists[i], lists[i + f...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mergeKLists_TLE1(self, lists): """k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again...
stack_v2_sparse_classes_10k_train_005223
3,498
permissive
[ { "docstring": "k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again Complexity: T(N) = (k/2)*2N+(k/4)*4N..+(k/2^r)*2^r*N T(...
4
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists_TLE1(self, lists): k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) A...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mergeKLists_TLE1(self, lists): k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) A...
cbbd4a67ab342ada2421e13f82d660b1d47d4d20
<|skeleton|> class Solution: def mergeKLists_TLE1(self, lists): """k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def mergeKLists_TLE1(self, lists): """k lists; each list has N items Algorithm 1: Merge the lists 1 by 1, just add a loop outside the merge. Complexity: 2N+3N+4N+..kN = O(k^2 * N) Algorithm 2: Group the lists in pairs with every pair having 2 lists, merge two, then repeat again Complexity: T...
the_stack_v2_python_sparse
022 Merge k Sorted Lists.py
Aminaba123/LeetCode
train
1
69fdf7292ea892b1421982e198fa611bb973b4d1
[ "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!')" ]
<|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...
A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent]) method to determine user intent and respond.
SessionsServicer
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SessionsServicer: """A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent]) method to determine user intent...
stack_v2_sparse_classes_10k_train_005224
3,682
permissive
[ { "docstring": "Processes a natural language query and returns structured, actionable data as a result. This method is not idempotent, because it may cause contexts and session entity types to be updated, which in turn might affect results of future queries.", "name": "DetectIntent", "signature": "def D...
2
stack_v2_sparse_classes_30k_train_006671
Implement the Python class `SessionsServicer` described below. Class description: A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectI...
Implement the Python class `SessionsServicer` described below. Class description: A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectI...
c9c830feb6b66c2e362f8fb5d147ef0c4f4a08cf
<|skeleton|> class SessionsServicer: """A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent]) method to determine user intent...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SessionsServicer: """A session represents an interaction with a user. You retrieve user input and pass it to the [DetectIntent][google.cloud.dialogflow.v2.Sessions.DetectIntent] (or [StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent]) method to determine user intent and respond....
the_stack_v2_python_sparse
pyenv/lib/python3.6/site-packages/dialogflow_v2/proto/session_pb2_grpc.py
ronald-rgr/ai-chatbot-smartguide
train
0
0d60b7b8526aa669ba65b13104a262556c82576a
[ "if not image_key:\n image_key = 'image/encoded'\nif not format_key:\n format_key = 'image/format'\nsuper(Image, self).__init__([image_key, format_key])\nself._image_key = image_key\nself._format_key = format_key\nself._shape = shape\nself._channels = channels\nself._dtype = dtype\nself._repeated = repeated",...
<|body_start_0|> if not image_key: image_key = 'image/encoded' if not format_key: format_key = 'image/format' super(Image, self).__init__([image_key, format_key]) self._image_key = image_key self._format_key = format_key self._shape = shape ...
An ItemHandler that decodes a parsed Tensor as an image.
Image
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Image: """An ItemHandler that decodes a parsed Tensor as an image.""" def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): """Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded im...
stack_v2_sparse_classes_10k_train_005225
15,383
permissive
[ { "docstring": "Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored. format_key: the name of the TF-Example feature in which the image format is stored. shape: the output shape of the image as 1-D `Tensor` [height, width, channels]. If provided, the im...
3
null
Implement the Python class `Image` described below. Class description: An ItemHandler that decodes a parsed Tensor as an image. Method signatures and docstrings: - def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): Initializes the image. Args: image_key: t...
Implement the Python class `Image` described below. Class description: An ItemHandler that decodes a parsed Tensor as an image. Method signatures and docstrings: - def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): Initializes the image. Args: image_key: t...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class Image: """An ItemHandler that decodes a parsed Tensor as an image.""" def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): """Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded im...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Image: """An ItemHandler that decodes a parsed Tensor as an image.""" def __init__(self, image_key=None, format_key=None, shape=None, channels=3, dtype=dtypes.uint8, repeated=False): """Initializes the image. Args: image_key: the name of the TF-Example feature in which the encoded image is stored...
the_stack_v2_python_sparse
Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py
ryfeus/lambda-packs
train
1,283
44ce5d5fa5634915f70dbf9aed7447697dcb25b1
[ "sm = get_storage_manager()\naction_dict = rest_utils.get_json_and_verify_params({'action': {'type': str}})\nplugin = sm.get(models.Plugin, plugin_id)\nif action_dict.get('action') == 'install':\n install_dict = rest_utils.get_json_and_verify_params({'managers': {'type': list, 'optional': True}, 'agents': {'type...
<|body_start_0|> sm = get_storage_manager() action_dict = rest_utils.get_json_and_verify_params({'action': {'type': str}}) plugin = sm.get(models.Plugin, plugin_id) if action_dict.get('action') == 'install': install_dict = rest_utils.get_json_and_verify_params({'managers': {'...
PluginsId
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PluginsId: def post(self, plugin_id, **kwargs): """Force plugin installation on the given managers or agents. This method is for internal use only.""" <|body_0|> def put(self, plugin_id, **kwargs): """Update the plugin, specifically the installation state. Only updat...
stack_v2_sparse_classes_10k_train_005226
14,516
permissive
[ { "docstring": "Force plugin installation on the given managers or agents. This method is for internal use only.", "name": "post", "signature": "def post(self, plugin_id, **kwargs)" }, { "docstring": "Update the plugin, specifically the installation state. Only updating the state is supported ri...
3
null
Implement the Python class `PluginsId` described below. Class description: Implement the PluginsId class. Method signatures and docstrings: - def post(self, plugin_id, **kwargs): Force plugin installation on the given managers or agents. This method is for internal use only. - def put(self, plugin_id, **kwargs): Upda...
Implement the Python class `PluginsId` described below. Class description: Implement the PluginsId class. Method signatures and docstrings: - def post(self, plugin_id, **kwargs): Force plugin installation on the given managers or agents. This method is for internal use only. - def put(self, plugin_id, **kwargs): Upda...
c0de6442e1d7653fad824d75e571802a74eee605
<|skeleton|> class PluginsId: def post(self, plugin_id, **kwargs): """Force plugin installation on the given managers or agents. This method is for internal use only.""" <|body_0|> def put(self, plugin_id, **kwargs): """Update the plugin, specifically the installation state. Only updat...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PluginsId: def post(self, plugin_id, **kwargs): """Force plugin installation on the given managers or agents. This method is for internal use only.""" sm = get_storage_manager() action_dict = rest_utils.get_json_and_verify_params({'action': {'type': str}}) plugin = sm.get(model...
the_stack_v2_python_sparse
rest-service/manager_rest/rest/resources_v3_1/plugins.py
cloudify-cosmo/cloudify-manager
train
146
a94defafafac0185705096d8ca5fee70ecb04e9f
[ "self.capacity = capacity\nself.time = 0\nself.map = {}\nself.freq_time = {}\nself.priority_queue = []\nself.update = set()", "self.time += 1\nif key in self.map:\n freq, _ = self.freq_time[key]\n self.freq_time[key] = (freq + 1, self.time)\n self.update.add(key)\n return self.map[key]\nreturn -1", ...
<|body_start_0|> self.capacity = capacity self.time = 0 self.map = {} self.freq_time = {} self.priority_queue = [] self.update = set() <|end_body_0|> <|body_start_1|> self.time += 1 if key in self.map: freq, _ = self.freq_time[key] ...
LFUCache
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k_train_005227
3,017
no_license
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
null
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LFUCache` described below. Class description: Implement the LFUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
05e0beff0047f0ad399d0b46d625bb8d3459814e
<|skeleton|> class LFUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class LFUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.time = 0 self.map = {} self.freq_time = {} self.priority_queue = [] self.update = set() def get(self, key): """:type key: int :rtype: int""" ...
the_stack_v2_python_sparse
python_1_to_1000/460_LFU_Cache.py
jakehoare/leetcode
train
58
9b1b60a94c34ff4b295439abdff7378bfeabbe87
[ "self.file_data = []\nself.header = {}\ntot_filepath = 'Data/WDCGG-SurfaceData/' + country + '/'\ntot_filepath += load_filename + '.dat'\nwith open(tot_filepath, 'rb') as file:\n for row in file:\n string_row = row.decode()\n if string_row[0] == 'C':\n try:\n key, value = ...
<|body_start_0|> self.file_data = [] self.header = {} tot_filepath = 'Data/WDCGG-SurfaceData/' + country + '/' tot_filepath += load_filename + '.dat' with open(tot_filepath, 'rb') as file: for row in file: string_row = row.decode() if s...
Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html
WDCGG_TS
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WDCGG_TS: """Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html""" def __init__(self, country, load_filename): """Initialises the class based on data found in the .dat files. coun...
stack_v2_sparse_classes_10k_train_005228
28,351
no_license
[ { "docstring": "Initialises the class based on data found in the .dat files. country -- string; the nation where the data came from, this will be used in filepaths and plot titles; so make sure the folders exit before run time. load_filename -- string; the file name/file path + file name where the .dat file is ...
2
stack_v2_sparse_classes_30k_train_004627
Implement the Python class `WDCGG_TS` described below. Class description: Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html Method signatures and docstrings: - def __init__(self, country, load_filename): Initiali...
Implement the Python class `WDCGG_TS` described below. Class description: Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html Method signatures and docstrings: - def __init__(self, country, load_filename): Initiali...
69c3beb334cb64b257c4496607a9b70dd220098b
<|skeleton|> class WDCGG_TS: """Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html""" def __init__(self, country, load_filename): """Initialises the class based on data found in the .dat files. coun...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WDCGG_TS: """Defines a child class of AtmosGasTS, with methods used to read in and parse the .dat files used by the WDCGG: http://ds.data.jma.go.jp/gmd/wdcgg/wdcgg.html""" def __init__(self, country, load_filename): """Initialises the class based on data found in the .dat files. country -- string...
the_stack_v2_python_sparse
ScriptsMisc/AtmosGasTSclass (old).py
tmed2/Atmos2016
train
0
6100f1a09996674b67a958a7026ada368ae699fb
[ "nn.Module.__init__(self)\nself.reduction = reduction\nself.criterion = nn.MSELoss(reduction='none')", "loss = self.criterion(input * mask, target * mask)\nif self.reduction == 'mean':\n loss = torch.sum(loss) / torch.sum(mask)\nreturn loss" ]
<|body_start_0|> nn.Module.__init__(self) self.reduction = reduction self.criterion = nn.MSELoss(reduction='none') <|end_body_0|> <|body_start_1|> loss = self.criterion(input * mask, target * mask) if self.reduction == 'mean': loss = torch.sum(loss) / torch.sum(mask)...
Compute the MSE loss only on the masked region.
MaskedMSELoss
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MaskedMSELoss: """Compute the MSE loss only on the masked region.""" def __init__(self, reduction='mean'): """Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None""" <|body_0|> def forward(sel...
stack_v2_sparse_classes_10k_train_005229
18,386
permissive
[ { "docstring": "Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None", "name": "__init__", "signature": "def __init__(self, reduction='mean')" }, { "docstring": "Forard pass of the loss. The loss is computed only wher...
2
stack_v2_sparse_classes_30k_train_004423
Implement the Python class `MaskedMSELoss` described below. Class description: Compute the MSE loss only on the masked region. Method signatures and docstrings: - def __init__(self, reduction='mean'): Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUT...
Implement the Python class `MaskedMSELoss` described below. Class description: Compute the MSE loss only on the masked region. Method signatures and docstrings: - def __init__(self, reduction='mean'): Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUT...
850b6195d6290a50eee865b4d5a66f5db5260e8f
<|skeleton|> class MaskedMSELoss: """Compute the MSE loss only on the masked region.""" def __init__(self, reduction='mean'): """Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None""" <|body_0|> def forward(sel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MaskedMSELoss: """Compute the MSE loss only on the masked region.""" def __init__(self, reduction='mean'): """Loss Constructor. ---------- INPUT |---- reduction (str) the reduction to use on the loss. ONLY 'mean' or 'none'. OUTPUT |---- None""" nn.Module.__init__(self) self.reduct...
the_stack_v2_python_sparse
Code/src/models/optim/CustomLosses.py
antoine-spahr/X-ray-Anomaly-Detection
train
3
50b676de636bbed5272c4c0fea2f790feea5fc4c
[ "t = self.observation['t']\nx, y = model.get_x_y(t)\nreturn {'t': t, 'x': x, 'y': y}", "delta_x = observation['x'] - prediction['x']\ndelta_y = observation['y'] - prediction['y']\nerror = np.sqrt(delta_x ** 2 + delta_y ** 2)\npassing = bool(error < 100000.0 * pq.kilometer)\nscore = self.score_type(passing)\nscore...
<|body_start_0|> t = self.observation['t'] x, y = model.get_x_y(t) return {'t': t, 'x': x, 'y': y} <|end_body_0|> <|body_start_1|> delta_x = observation['x'] - prediction['x'] delta_y = observation['y'] - prediction['y'] error = np.sqrt(delta_x ** 2 + delta_y ** 2) ...
A test of a planetary position at some specified time.
PositionTest
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PositionTest: """A test of a planetary position at some specified time.""" def generate_prediction(self, model): """Generate a prediction from a model.""" <|body_0|> def compute_score(self, observation, prediction): """Compute a test score based on the agreement ...
stack_v2_sparse_classes_10k_train_005230
4,646
no_license
[ { "docstring": "Generate a prediction from a model.", "name": "generate_prediction", "signature": "def generate_prediction(self, model)" }, { "docstring": "Compute a test score based on the agreement between the observation (data) and prediction (model).", "name": "compute_score", "signa...
2
null
Implement the Python class `PositionTest` described below. Class description: A test of a planetary position at some specified time. Method signatures and docstrings: - def generate_prediction(self, model): Generate a prediction from a model. - def compute_score(self, observation, prediction): Compute a test score ba...
Implement the Python class `PositionTest` described below. Class description: A test of a planetary position at some specified time. Method signatures and docstrings: - def generate_prediction(self, model): Generate a prediction from a model. - def compute_score(self, observation, prediction): Compute a test score ba...
624bf82ce5c610c2ca83a0c4c49d3f4d0b92a1e2
<|skeleton|> class PositionTest: """A test of a planetary position at some specified time.""" def generate_prediction(self, model): """Generate a prediction from a model.""" <|body_0|> def compute_score(self, observation, prediction): """Compute a test score based on the agreement ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PositionTest: """A test of a planetary position at some specified time.""" def generate_prediction(self, model): """Generate a prediction from a model.""" t = self.observation['t'] x, y = model.get_x_y(t) return {'t': t, 'x': x, 'y': y} def compute_score(self, observa...
the_stack_v2_python_sparse
unittest/sciunittest.py
HussainAther/neuroscience
train
9
af1dade54e8aa2d4cc19216a1896cb7dd9184dfd
[ "version = pcs.Field('version', 4, default=4)\nhlen = pcs.Field('hlen', 4)\ntos = pcs.Field('tos', 8)\nlength = pcs.Field('length', 16)\nid = pcs.Field('id', 16)\nflags = pcs.Field('flags', 3)\noffset = pcs.Field('offset', 13)\nttl = pcs.Field('ttl', 8, default=64)\nprotocol = pcs.Field('protocol', 8)\nchecksum = p...
<|body_start_0|> version = pcs.Field('version', 4, default=4) hlen = pcs.Field('hlen', 4) tos = pcs.Field('tos', 8) length = pcs.Field('length', 16) id = pcs.Field('id', 16) flags = pcs.Field('flags', 3) offset = pcs.Field('offset', 13) ttl = pcs.Field('tt...
ipv4
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ipv4: def __init__(self, bytes=None): """define the fields of an IPv4 packet, from RFC 791 This version does not include options.""" <|body_0|> def __str__(self): """Walk the entire packet and pretty print the values of the fields.""" <|body_1|> def next...
stack_v2_sparse_classes_10k_train_005231
5,722
no_license
[ { "docstring": "define the fields of an IPv4 packet, from RFC 791 This version does not include options.", "name": "__init__", "signature": "def __init__(self, bytes=None)" }, { "docstring": "Walk the entire packet and pretty print the values of the fields.", "name": "__str__", "signatur...
4
stack_v2_sparse_classes_30k_train_000337
Implement the Python class `ipv4` described below. Class description: Implement the ipv4 class. Method signatures and docstrings: - def __init__(self, bytes=None): define the fields of an IPv4 packet, from RFC 791 This version does not include options. - def __str__(self): Walk the entire packet and pretty print the ...
Implement the Python class `ipv4` described below. Class description: Implement the ipv4 class. Method signatures and docstrings: - def __init__(self, bytes=None): define the fields of an IPv4 packet, from RFC 791 This version does not include options. - def __str__(self): Walk the entire packet and pretty print the ...
a070a39586b582fbeea72abf12bbfd812955ad81
<|skeleton|> class ipv4: def __init__(self, bytes=None): """define the fields of an IPv4 packet, from RFC 791 This version does not include options.""" <|body_0|> def __str__(self): """Walk the entire packet and pretty print the values of the fields.""" <|body_1|> def next...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ipv4: def __init__(self, bytes=None): """define the fields of an IPv4 packet, from RFC 791 This version does not include options.""" version = pcs.Field('version', 4, default=4) hlen = pcs.Field('hlen', 4) tos = pcs.Field('tos', 8) length = pcs.Field('length', 16) ...
the_stack_v2_python_sparse
src/pcs/packets/ipv4.py
bilouro/tcptest
train
0
93a7c2a9db6cdc0847db634aad809ecc038fe1ec
[ "super().__init__(base_url=base_url, proxy=proxy, verify=verify)\nself.api_key = api_key\nif self.api_key:\n self._headers = {'Key': self.api_key}", "request_params: Dict[str, Any] = {}\nif offset:\n request_params['offset'] = offset\nif max_results:\n request_params['limit'] = max_results\nif start_time...
<|body_start_0|> super().__init__(base_url=base_url, proxy=proxy, verify=verify) self.api_key = api_key if self.api_key: self._headers = {'Key': self.api_key} <|end_body_0|> <|body_start_1|> request_params: Dict[str, Any] = {} if offset: request_params['o...
This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.
Client
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Client: """This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.""" def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]): ...
stack_v2_sparse_classes_10k_train_005232
14,388
permissive
[ { "docstring": "This function initializes the connection with the API server by collecting curcial information from the users.", "name": "__init__", "signature": "def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool])" }, { "docstring":...
4
null
Implement the Python class `Client` described below. Class description: This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events. Method signatures and docstrings: - def __init__(self, api_key: Optional[str], base_url: ...
Implement the Python class `Client` described below. Class description: This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events. Method signatures and docstrings: - def __init__(self, api_key: Optional[str], base_url: ...
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
<|skeleton|> class Client: """This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.""" def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Client: """This class is responsible for dealing with the XDR api. It performs all the fetching related commands andensure proper pre processing ebfore forward events.""" def __init__(self, api_key: Optional[str], base_url: Optional[str], proxy: Optional[bool], verify: Optional[bool]): """This fu...
the_stack_v2_python_sparse
Packs/Zerohack_XDR/Integrations/ZerohackXDR/ZerohackXDR.py
demisto/content
train
1,023
36d68f5a360e7ee68991dafdd2b4b270e30a3e5b
[ "super().__init__(*args, **kwargs)\nself.value_shape = value_shape or ()\nself.num_values = int(np.prod(self.value_shape))\nself.iblt_values_shape = (self.repetitions, self.table_size) + self.value_shape\nif len(self.value_shape) > 1:\n self._tile_shape = [1] + [1 for _ in self.value_shape]\n self._tile_shape...
<|body_start_0|> super().__init__(*args, **kwargs) self.value_shape = value_shape or () self.num_values = int(np.prod(self.value_shape)) self.iblt_values_shape = (self.repetitions, self.table_size) + self.value_shape if len(self.value_shape) > 1: self._tile_shape = [1...
Encodes the strings into an IBLT data structure.
IbltTensorEncoder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class IbltTensorEncoder: """Encodes the strings into an IBLT data structure.""" def __init__(self, value_shape: Sequence[int], *args, **kwargs): """Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: See IbltEncoder. **kwargs: See IbltEncoder.""" <|...
stack_v2_sparse_classes_10k_train_005233
17,202
permissive
[ { "docstring": "Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: See IbltEncoder. **kwargs: See IbltEncoder.", "name": "__init__", "signature": "def __init__(self, value_shape: Sequence[int], *args, **kwargs)" }, { "docstring": "Returns SparseTensor with tenso...
3
stack_v2_sparse_classes_30k_train_006457
Implement the Python class `IbltTensorEncoder` described below. Class description: Encodes the strings into an IBLT data structure. Method signatures and docstrings: - def __init__(self, value_shape: Sequence[int], *args, **kwargs): Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: ...
Implement the Python class `IbltTensorEncoder` described below. Class description: Encodes the strings into an IBLT data structure. Method signatures and docstrings: - def __init__(self, value_shape: Sequence[int], *args, **kwargs): Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: ...
ad4bca66f4b483e09d8396e9948630813a343d27
<|skeleton|> class IbltTensorEncoder: """Encodes the strings into an IBLT data structure.""" def __init__(self, value_shape: Sequence[int], *args, **kwargs): """Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: See IbltEncoder. **kwargs: See IbltEncoder.""" <|...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class IbltTensorEncoder: """Encodes the strings into an IBLT data structure.""" def __init__(self, value_shape: Sequence[int], *args, **kwargs): """Initializes internal IBLT parameters. Args: value_shape: Shape of the values. *args: See IbltEncoder. **kwargs: See IbltEncoder.""" super().__init_...
the_stack_v2_python_sparse
tensorflow_federated/python/analytics/heavy_hitters/iblt/iblt_tensor.py
tensorflow/federated
train
2,297
178287d23c96c09c9a2d4c68d6f4547ab7cadaee
[ "magnitudes, edges = np.histogram(data, bins)\nbin_width = edges[1] - edges[0]\nbin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution)\nvalid_indices = np.where(bin_sizes >= 1)[0]\nif valid_indices.size == 0:\n raise ValueError('Resolution is too low. Cumulative distribution array is empty.')\...
<|body_start_0|> magnitudes, edges = np.histogram(data, bins) bin_width = edges[1] - edges[0] bin_sizes = magnitudes.astype(np.float) / (magnitudes.sum() * resolution) valid_indices = np.where(bin_sizes >= 1)[0] if valid_indices.size == 0: raise ValueError('Resolution...
Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler trades space for time by appro...
HistogramSampler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class HistogramSampler: """Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution....
stack_v2_sparse_classes_10k_train_005234
5,295
permissive
[ { "docstring": "Construct a new sampler object. :param data: Observations for a single random variable. :type data: 1D ndarray :param bins: Number of bins to use when generating the histogram. :type bins: positive int :param resolution: Resolution of each element of the cum-dist array. For example, a resolution...
2
stack_v2_sparse_classes_30k_train_005860
Implement the Python class `HistogramSampler` described below. Class description: Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v...
Implement the Python class `HistogramSampler` described below. Class description: Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new v...
8b98390850351385acfda5be3088cd4db4cc4a09
<|skeleton|> class HistogramSampler: """Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution....
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class HistogramSampler: """Random number generator based on a modelled distribution. Given repeated observations of a single random variable, this object first models the probability distribution that governs the variable using a histogram. It then generates new variates according to this distribution. This sampler...
the_stack_v2_python_sparse
glimpse/util/grandom.py
mthomure/glimpse-project
train
1
c7f0a39910e06dd77e74f07b26f5e4fa5ac9e1d3
[ "super(Annotation, self).__init__(*args, **kwargs)\nif not TOKEN:\n raise exceptions.InvalidCredentials('Missing the \"LIBRATO_TOKEN\" environment variable.')\nif not EMAIL:\n raise exceptions.InvalidCredentials('Missing the \"LIBRATO_EMAIL\" environment variable.')", "try:\n res = (yield self._fetch(*ar...
<|body_start_0|> super(Annotation, self).__init__(*args, **kwargs) if not TOKEN: raise exceptions.InvalidCredentials('Missing the "LIBRATO_TOKEN" environment variable.') if not EMAIL: raise exceptions.InvalidCredentials('Missing the "LIBRATO_EMAIL" environment variable.')...
Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librato.Annotation", "desc": "Mark our deployment", "options": { "title": "Deploy",...
Annotation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Annotation: """Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librato.Annotation", "desc": "Mark our deploy...
stack_v2_sparse_classes_10k_train_005235
5,119
permissive
[ { "docstring": "Check for the needed environment variables.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "Wrap the superclass _fetch method to catch known Librato errors.", "name": "_fetch_wrapper", "signature": "def _fetch_wrapper(self, *arg...
3
stack_v2_sparse_classes_30k_test_000335
Implement the Python class `Annotation` described below. Class description: Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librat...
Implement the Python class `Annotation` described below. Class description: Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librat...
d0abaf93ff321f12c0504c99eacb89f9288e892b
<|skeleton|> class Annotation: """Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librato.Annotation", "desc": "Mark our deploy...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Annotation: """Librato Annotation Actor Posts an Annotation to Librato. **Options** :title: The title of the annotation :description: The description of the annotation :name: Name of the metric to annotate **Examples** .. code-block:: json { "actor": "librato.Annotation", "desc": "Mark our deployment", "optio...
the_stack_v2_python_sparse
kingpin/actors/librato.py
Nextdoor/kingpin
train
29
40873b9e0ffaadb6451f553b15a061d4381f80da
[ "if not isinstance(filePath, str):\n raise Exceptions.IncorrectTypeException(filePath, 'path', (str,))\nsuper().__init__(currentVersion, hostNamespace=hostNamespace)\nself.FilePath = filePath", "operationSuccess = True\npersistentDataContainerString = '{}'\nif os.path.exists(self.FilePath):\n try:\n ...
<|body_start_0|> if not isinstance(filePath, str): raise Exceptions.IncorrectTypeException(filePath, 'path', (str,)) super().__init__(currentVersion, hostNamespace=hostNamespace) self.FilePath = filePath <|end_body_0|> <|body_start_1|> operationSuccess = True persist...
A class for handling persistent data. This version will read and write the data to a file through the load and save methods.
PersistentBranchedFile
[ "CC-BY-4.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PersistentBranchedFile: """A class for handling persistent data. This version will read and write the data to a file through the load and save methods.""" def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace): """:param filePath: Th...
stack_v2_sparse_classes_10k_train_005236
34,547
permissive
[ { "docstring": ":param filePath: The file path this persistence object will be written to and read from. :type filePath: str :param currentVersion: The current version of what ever will be controlling this persistence object. This value can allow you to correct outdated persistent data. :type currentVersion: Ve...
3
stack_v2_sparse_classes_30k_train_005178
Implement the Python class `PersistentBranchedFile` described below. Class description: A class for handling persistent data. This version will read and write the data to a file through the load and save methods. Method signatures and docstrings: - def __init__(self, filePath: str, currentVersion: Version.Version, ho...
Implement the Python class `PersistentBranchedFile` described below. Class description: A class for handling persistent data. This version will read and write the data to a file through the load and save methods. Method signatures and docstrings: - def __init__(self, filePath: str, currentVersion: Version.Version, ho...
2d85e6d4428f01294d2d34f1807287b753f7490c
<|skeleton|> class PersistentBranchedFile: """A class for handling persistent data. This version will read and write the data to a file through the load and save methods.""" def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace): """:param filePath: Th...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PersistentBranchedFile: """A class for handling persistent data. This version will read and write the data to a file through the load and save methods.""" def __init__(self, filePath: str, currentVersion: Version.Version, hostNamespace: str=This.Mod.Namespace): """:param filePath: The file path t...
the_stack_v2_python_sparse
Python/NeonOcean.S4.Main/NeonOcean/S4/Main/Data/PersistenceBranched.py
NeonOcean/S4.Main
train
1
f6a9da15cd7d656815adf5d4625f848a44487e39
[ "if la:\n return la.size() ** 2 + la[0]\nelse:\n return 0", "if sexpr == 0:\n return self(0)\nif sexpr.support() == [[]]:\n return self._from_dict({self.one_basis(): sexpr.coefficient([])}, remove_zeros=False)\nout = self.zero()\nwhile sexpr:\n mup = max(sexpr.support(), key=self._my_key)\n out ...
<|body_start_0|> if la: return la.size() ** 2 + la[0] else: return 0 <|end_body_0|> <|body_start_1|> if sexpr == 0: return self(0) if sexpr.support() == [[]]: return self._from_dict({self.one_basis(): sexpr.coefficient([])}, remove_zeros=F...
generic_character
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it i...
stack_v2_sparse_classes_10k_train_005237
16,482
no_license
[ { "docstring": "A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\\\lambda|^2 + \\\\lambda_0` and using the ``max`` function on a list of Partitions. Of course it is possible that this rank function is equal for s...
2
stack_v2_sparse_classes_30k_train_005192
Implement the Python class `generic_character` described below. Class description: Implement the generic_character class. Method signatures and docstrings: - def _my_key(self, la): A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key v...
Implement the Python class `generic_character` described below. Class description: Implement the generic_character class. Method signatures and docstrings: - def _my_key(self, la): A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key v...
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
<|skeleton|> class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it i...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class generic_character: def _my_key(self, la): """A rank function for partitions. The leading term of a homogeneous expression will be the partition with the largest key value. This key value is `|\\lambda|^2 + \\lambda_0` and using the ``max`` function on a list of Partitions. Of course it is possible tha...
the_stack_v2_python_sparse
sage/src/sage/combinat/sf/character.py
bopopescu/geosci
train
0
731e2a1ec51dd25ff6b080b779eb0578ce1f8ad9
[ "hour = 0\nfor count in piles:\n hour += count / k\n if count % k != 0:\n hour += 1\nreturn hour", "if not piles:\n return 0\nleft = 1\nright = max(piles)\nwhile left + 1 < right:\n middle = (left + right) / 2\n hour = self.calHour(middle, piles)\n if hour == H:\n right = middle\n ...
<|body_start_0|> hour = 0 for count in piles: hour += count / k if count % k != 0: hour += 1 return hour <|end_body_0|> <|body_start_1|> if not piles: return 0 left = 1 right = max(piles) while left + 1 < right:...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" <|body_0|> def minEatingSpeed(self, piles, H): """:type piles: List[int] :type H: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_10k_train_005238
1,004
no_license
[ { "docstring": "calculate how many hours koko takes eating up all piles of bananas", "name": "calHour", "signature": "def calHour(self, k, piles)" }, { "docstring": ":type piles: List[int] :type H: int :rtype: int", "name": "minEatingSpeed", "signature": "def minEatingSpeed(self, piles, ...
2
stack_v2_sparse_classes_30k_test_000119
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calHour(self, k, piles): calculate how many hours koko takes eating up all piles of bananas - def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def calHour(self, k, piles): calculate how many hours koko takes eating up all piles of bananas - def minEatingSpeed(self, piles, H): :type piles: List[int] :type H: int :rtype: ...
1d8821da01c9c200732a6b7037b8631689e2f7e7
<|skeleton|> class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" <|body_0|> def minEatingSpeed(self, piles, H): """:type piles: List[int] :type H: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def calHour(self, k, piles): """calculate how many hours koko takes eating up all piles of bananas""" hour = 0 for count in piles: hour += count / k if count % k != 0: hour += 1 return hour def minEatingSpeed(self, piles, H...
the_stack_v2_python_sparse
Leetcode0875_BinarySearch.py
xiaojinghu/Leetcode
train
0
248b4261ea8199e77a5478eafe17e8e2521894c4
[ "self._modules = args\nself._base_module = kwargs.get('base_module', 'galileo')\nif not self._modules:\n self._modules = [self._base_module]", "for module in self._modules:\n m = sys.modules[module]\n setattr(m, func.__name__, func)\nreturn func", "for module in self._modules:\n m = sys.modules[modu...
<|body_start_0|> self._modules = args self._base_module = kwargs.get('base_module', 'galileo') if not self._modules: self._modules = [self._base_module] <|end_body_0|> <|body_start_1|> for module in self._modules: m = sys.modules[module] setattr(m, fu...
\\brief Export galileo APIs
export
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-2-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" <|body_0|> def __cal...
stack_v2_sparse_classes_10k_train_005239
2,131
permissive
[ { "docstring": "\\\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\\\param **kwargs base_module Default is `galileo`.", "name": "__init__", "signature": "def __init__(self, *args, **kwargs)" }, { "docstring": "\\\\brief export c...
4
stack_v2_sparse_classes_30k_test_000184
Implement the Python class `export` described below. Class description: \\brief Export galileo APIs Method signatures and docstrings: - def __init__(self, *args, **kwargs): \\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module D...
Implement the Python class `export` described below. Class description: \\brief Export galileo APIs Method signatures and docstrings: - def __init__(self, *args, **kwargs): \\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module D...
48099ec3f0331196c6812208ceb080ba618a588b
<|skeleton|> class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" <|body_0|> def __cal...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class export: """\\brief Export galileo APIs""" def __init__(self, *args, **kwargs): """\\param *args modules, expected modules, dot delimited format. Default use base_module, e.g. galileo or galileo.tf \\param **kwargs base_module Default is `galileo`.""" self._modules = args self._bas...
the_stack_v2_python_sparse
galileo/platform/export.py
2012fang1/galileo
train
0
59b53af55bab5cc560fcb2243f77a5802002be72
[ "preorder, inorder = ([], [])\n\ndef helper(root):\n if not root:\n return\n preorder.append(root.val)\n helper(root.left)\n inorder.append(root.val)\n helper(root.right)\nhelper(root)\nreturn ':'.join(map(str, preorder)) + ':' + ':'.join(map(str, inorder))", "l = data.split(':')\nif l == ['...
<|body_start_0|> preorder, inorder = ([], []) def helper(root): if not root: return preorder.append(root.val) helper(root.left) inorder.append(root.val) helper(root.right) helper(root) return ':'.join(map(str, p...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|> <|body_...
stack_v2_sparse_classes_10k_train_005240
1,568
no_license
[ { "docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str", "name": "serialize", "signature": "def serialize(self, root)" }, { "docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode", "name": "deserialize", "signature": "def deserializ...
2
stack_v2_sparse_classes_30k_train_001857
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str - def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:...
4ef763841632f2ba0a616b13c70e8650ada4ae16
<|skeleton|> class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" <|body_0|> def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str""" preorder, inorder = ([], []) def helper(root): if not root: return preorder.append(root.val) helper(root.left) in...
the_stack_v2_python_sparse
leetcode449.py
kduan005/Leetcode
train
0
c32362a237de3cc389f85c7ae5e004c2bdb102fb
[ "super(mesh_to_mesh_petsc_dmda, self).__init__(fine_prob, coarse_prob, params)\nself.interp, _ = self.coarse_prob.init.createInterpolation(self.fine_prob.init)\nself.inject = self.coarse_prob.init.createInjection(self.fine_prob.init)", "if isinstance(F, petsc_vec):\n u_coarse = self.coarse_prob.dtype_u(self.co...
<|body_start_0|> super(mesh_to_mesh_petsc_dmda, self).__init__(fine_prob, coarse_prob, params) self.interp, _ = self.coarse_prob.init.createInterpolation(self.fine_prob.init) self.inject = self.coarse_prob.init.createInjection(self.fine_prob.init) <|end_body_0|> <|body_start_1|> if isin...
This implementation can restrict and prolong between PETSc DMDA grids
mesh_to_mesh_petsc_dmda
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""...
stack_v2_sparse_classes_10k_train_005241
2,871
permissive
[ { "docstring": "Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators", "name": "__init__", "signature": "def __init__(self, fine_prob, coarse_prob, params)" }, { "docstring": "Restriction implementation Args: F: the fine l...
3
null
Implement the Python class `mesh_to_mesh_petsc_dmda` described below. Class description: This implementation can restrict and prolong between PETSc DMDA grids Method signatures and docstrings: - def __init__(self, fine_prob, coarse_prob, params): Initialization routine Args: fine_prob: fine problem coarse_prob: coars...
Implement the Python class `mesh_to_mesh_petsc_dmda` described below. Class description: This implementation can restrict and prolong between PETSc DMDA grids Method signatures and docstrings: - def __init__(self, fine_prob, coarse_prob, params): Initialization routine Args: fine_prob: fine problem coarse_prob: coars...
1a51834bedffd4472e344bed28f4d766614b1537
<|skeleton|> class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class mesh_to_mesh_petsc_dmda: """This implementation can restrict and prolong between PETSc DMDA grids""" def __init__(self, fine_prob, coarse_prob, params): """Initialization routine Args: fine_prob: fine problem coarse_prob: coarse problem params: parameters for the transfer operators""" sup...
the_stack_v2_python_sparse
pySDC/implementations/transfer_classes/TransferPETScDMDA.py
Parallel-in-Time/pySDC
train
30
3ac688259da227071652034e0acaf2acf1f7fc31
[ "self.capacity = capacity\nself.map = {}\nself.cache = LinkedList()", "if key in self.map:\n node = self.map[key]\n self.cache.remove(node)\n self.cache.append(node)\n return node.value\nreturn -1", "if key not in self.map:\n if len(self.cache) == self.capacity:\n node = self.cache.pop()\n...
<|body_start_0|> self.capacity = capacity self.map = {} self.cache = LinkedList() <|end_body_0|> <|body_start_1|> if key in self.map: node = self.map[key] self.cache.remove(node) self.cache.append(node) return node.value return -1 ...
LRUCache
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k_train_005242
2,543
permissive
[ { "docstring": ":type capacity: int", "name": "__init__", "signature": "def __init__(self, capacity)" }, { "docstring": ":type key: int :rtype: int", "name": "get", "signature": "def get(self, key)" }, { "docstring": ":type key: int :type value: int :rtype: void", "name": "pu...
3
stack_v2_sparse_classes_30k_train_006706
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void
Implement the Python class `LRUCache` described below. Class description: Implement the LRUCache class. Method signatures and docstrings: - def __init__(self, capacity): :type capacity: int - def get(self, key): :type key: int :rtype: int - def put(self, key, value): :type key: int :type value: int :rtype: void <|sk...
ba84c192fb9995dd48ddc6d81c3153488dd3c698
<|skeleton|> class LRUCache: def __init__(self, capacity): """:type capacity: int""" <|body_0|> def get(self, key): """:type key: int :rtype: int""" <|body_1|> def put(self, key, value): """:type key: int :type value: int :rtype: void""" <|body_2|> <|end_s...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class LRUCache: def __init__(self, capacity): """:type capacity: int""" self.capacity = capacity self.map = {} self.cache = LinkedList() def get(self, key): """:type key: int :rtype: int""" if key in self.map: node = self.map[key] self.cac...
the_stack_v2_python_sparse
Python/lru-cache.py
phucle2411/LeetCode
train
0
9da2e5b13d4d669d3402defae75d2399f16b14f1
[ "e = 2.718281828459045\nctx.save_for_backward(x, l, u, g)\ny = l + (u - l) / (1 + e ** (-g * x))\nreturn y", "e = 2.718281828459045\nx, l, u, g = ctx.saved_tensors\ndzdx = dzdy * (g * (u - l) * e ** (-g * x) / (1 + e ** (-g * x)) ** 2)\ndzdl = dzdy * (1 / (e ** (g * x) + 1))\ndzdu = dzdy * (1 / (e ** (-g * x) + 1...
<|body_start_0|> e = 2.718281828459045 ctx.save_for_backward(x, l, u, g) y = l + (u - l) / (1 + e ** (-g * x)) return y <|end_body_0|> <|body_start_1|> e = 2.718281828459045 x, l, u, g = ctx.saved_tensors dzdx = dzdy * (g * (u - l) * e ** (-g * x) / (1 + e ** (-g...
GeneralizedLogistic
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GeneralizedLogistic: def forward(ctx, x, l, u, g): """Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Retu...
stack_v2_sparse_classes_10k_train_005243
1,489
no_license
[ { "docstring": "Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Returns ------- y: (Tensor) of size (T x n), the outputs of the ge...
2
stack_v2_sparse_classes_30k_train_003557
Implement the Python class `GeneralizedLogistic` described below. Class description: Implement the GeneralizedLogistic class. Method signatures and docstrings: - def forward(ctx, x, l, u, g): Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the ...
Implement the Python class `GeneralizedLogistic` described below. Class description: Implement the GeneralizedLogistic class. Method signatures and docstrings: - def forward(ctx, x, l, u, g): Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the ...
b6824c340272f65b8c5fd44fcea2a363a7e69f05
<|skeleton|> class GeneralizedLogistic: def forward(ctx, x, l, u, g): """Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Retu...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GeneralizedLogistic: def forward(ctx, x, l, u, g): """Computes the generalized logistic function Arguments --------- ctx: A PyTorch context object x: (Tensor) of size (T x n), the input features l, u, and g: (scalar tensors) representing the generalized logistic function parameters. Returns ------- y:...
the_stack_v2_python_sparse
homework/Kirsten_Ziman_HW1/generalized_logistic.py
KirstensGitHub/deep_learning
train
0
c427da84ab06c5444ba7a11ffcf50fe6081643b2
[ "if verbosity:\n (print >> self.stdout, 'Project settings:')\n (print >> self.stdout, 'Configuration definition file placed at %r\\n' % AVAILABLE_SETTINGS.path)\n for setting in AVAILABLE_SETTINGS:\n indent = ' ' * 4\n if is_settings_container(setting):\n (print >> self.stdout, '%s...
<|body_start_0|> if verbosity: (print >> self.stdout, 'Project settings:') (print >> self.stdout, 'Configuration definition file placed at %r\n' % AVAILABLE_SETTINGS.path) for setting in AVAILABLE_SETTINGS: indent = ' ' * 4 if is_settings_conta...
Command
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Command: def check_setman(self, verbosity): """Check setman configuration.""" <|body_0|> def handle_noargs(self, **options): """Do all necessary things.""" <|body_1|> def store_default_values(self, verbosity): """Store default values to Settings ...
stack_v2_sparse_classes_10k_train_005244
2,852
permissive
[ { "docstring": "Check setman configuration.", "name": "check_setman", "signature": "def check_setman(self, verbosity)" }, { "docstring": "Do all necessary things.", "name": "handle_noargs", "signature": "def handle_noargs(self, **options)" }, { "docstring": "Store default values ...
3
stack_v2_sparse_classes_30k_train_002850
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def check_setman(self, verbosity): Check setman configuration. - def handle_noargs(self, **options): Do all necessary things. - def store_default_values(self, verbosity): Store def...
Implement the Python class `Command` described below. Class description: Implement the Command class. Method signatures and docstrings: - def check_setman(self, verbosity): Check setman configuration. - def handle_noargs(self, **options): Do all necessary things. - def store_default_values(self, verbosity): Store def...
08fc786b0d7ad0216129c62e4907d6aa79643739
<|skeleton|> class Command: def check_setman(self, verbosity): """Check setman configuration.""" <|body_0|> def handle_noargs(self, **options): """Do all necessary things.""" <|body_1|> def store_default_values(self, verbosity): """Store default values to Settings ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Command: def check_setman(self, verbosity): """Check setman configuration.""" if verbosity: (print >> self.stdout, 'Project settings:') (print >> self.stdout, 'Configuration definition file placed at %r\n' % AVAILABLE_SETTINGS.path) for setting in AVAILABLE_...
the_stack_v2_python_sparse
setman/frameworks/django_setman/management/commands/setman_cmd.py
playpauseandstop/setman
train
2
8ff0d16459494647e04ac06b010654e2d9e6a7cd
[ "sanitized_week_day_str = week_day_str.upper()\nif sanitized_week_day_str not in cls.__members__:\n raise AttributeError(f'Invalid Week Day passed: \"{week_day_str}\"')\nreturn cls[sanitized_week_day_str]", "if isinstance(day, WeekDay):\n return day\nreturn cls.get_weekday_number(week_day_str=day)", "if n...
<|body_start_0|> sanitized_week_day_str = week_day_str.upper() if sanitized_week_day_str not in cls.__members__: raise AttributeError(f'Invalid Week Day passed: "{week_day_str}"') return cls[sanitized_week_day_str] <|end_body_0|> <|body_start_1|> if isinstance(day, WeekDay):...
Python Enum containing Days of the Week.
WeekDay
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WeekDay: """Python Enum containing Days of the Week.""" def get_weekday_number(cls, week_day_str: str): """Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekd...
stack_v2_sparse_classes_10k_train_005245
2,675
permissive
[ { "docstring": "Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: \"Sunday\" :return: ISO Week Day Number corresponding to the provided Weekday", "name": "get_weekday_number", "signature": "def get_weekday_number(cls, week_day_str: str)" }, { ...
3
null
Implement the Python class `WeekDay` described below. Class description: Python Enum containing Days of the Week. Method signatures and docstrings: - def get_weekday_number(cls, week_day_str: str): Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return...
Implement the Python class `WeekDay` described below. Class description: Python Enum containing Days of the Week. Method signatures and docstrings: - def get_weekday_number(cls, week_day_str: str): Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return...
1b122c15030e99cef9d4ff26d3781a7a9d6949bc
<|skeleton|> class WeekDay: """Python Enum containing Days of the Week.""" def get_weekday_number(cls, week_day_str: str): """Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekd...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WeekDay: """Python Enum containing Days of the Week.""" def get_weekday_number(cls, week_day_str: str): """Return the ISO Week Day Number for a Week Day. :param week_day_str: Full Name of the Week Day. Example: "Sunday" :return: ISO Week Day Number corresponding to the provided Weekday""" ...
the_stack_v2_python_sparse
airflow/utils/weekday.py
apache/airflow
train
22,756
00f91c62fd9a5410eb6cb531a9f5c199871001f4
[ "super(Stance, self).__init__()\nself.src_encoder = encoder\nif tgt_encoder is None:\n self.tgt_encoder = encoder\nelse:\n self.tgt_encoder = tgt_encoder\nself.CNN = CNN(cnn_increasing, cnn_num_layers, cnn_filter_counts)\nself.loss = BCEWithLogitsLoss()", "pos_score = self.score_pair(query, pos, query_mask,...
<|body_start_0|> super(Stance, self).__init__() self.src_encoder = encoder if tgt_encoder is None: self.tgt_encoder = encoder else: self.tgt_encoder = tgt_encoder self.CNN = CNN(cnn_increasing, cnn_num_layers, cnn_filter_counts) self.loss = BCEWith...
"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. Finally, CNN detects features in al...
Stance
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Stance: """"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. F...
stack_v2_sparse_classes_10k_train_005246
8,806
permissive
[ { "docstring": "param config: config object param vocab: vocab object param max_len_token: max number of tokens", "name": "__init__", "signature": "def __init__(self, encoder, cnn_increasing, cnn_num_layers, cnn_filter_counts, tgt_encoder=None)" }, { "docstring": "Compute loss for batch of query...
3
stack_v2_sparse_classes_30k_train_006207
Implement the Python class `Stance` described below. Class description: "STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over th...
Implement the Python class `Stance` described below. Class description: "STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over th...
5dca6fa477c6fdb93b042deb1b0212bb91ce7f00
<|skeleton|> class Stance: """"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. F...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Stance: """"STANCE first gets character embeddings. Next, LSTM runs over char embeddings to get char representations. Then, similarity matrix created where all LSTM embeddings are scored for similarity using dot product. Optimal Transport is then run over the similarity matrix to align weights. Finally, CNN d...
the_stack_v2_python_sparse
stance.py
jlibovicky/neural-string-edit-distance
train
2
252b5415aeb413e64e87b927c93f63474bf5ce65
[ "set_seed(int(time()))\ntokenizer = create_tokenizer(tokenizer)\nmodel = create_model(model)\nself._text_generation_pipiline = _create_pipiline(tokenizer, model, device, framework)", "seqs = [seqs] if isinstance(seqs, str) else seqs\nmax_length = max(map(len, seqs)) * 2\nreturn self._text_generation_pipiline(seqs...
<|body_start_0|> set_seed(int(time())) tokenizer = create_tokenizer(tokenizer) model = create_model(model) self._text_generation_pipiline = _create_pipiline(tokenizer, model, device, framework) <|end_body_0|> <|body_start_1|> seqs = [seqs] if isinstance(seqs, str) else seqs ...
Text generator pipiline.
TextGenerator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextGenerator: """Text generator pipiline.""" def __init__(self, tokenizer, model, device=-1, framework='pt'): """Init class object.""" <|body_0|> def __call__(self, seqs): """Call class object.""" <|body_1|> <|end_skeleton|> <|body_start_0|> se...
stack_v2_sparse_classes_10k_train_005247
1,880
no_license
[ { "docstring": "Init class object.", "name": "__init__", "signature": "def __init__(self, tokenizer, model, device=-1, framework='pt')" }, { "docstring": "Call class object.", "name": "__call__", "signature": "def __call__(self, seqs)" } ]
2
stack_v2_sparse_classes_30k_train_005917
Implement the Python class `TextGenerator` described below. Class description: Text generator pipiline. Method signatures and docstrings: - def __init__(self, tokenizer, model, device=-1, framework='pt'): Init class object. - def __call__(self, seqs): Call class object.
Implement the Python class `TextGenerator` described below. Class description: Text generator pipiline. Method signatures and docstrings: - def __init__(self, tokenizer, model, device=-1, framework='pt'): Init class object. - def __call__(self, seqs): Call class object. <|skeleton|> class TextGenerator: """Text ...
b6e52ed56928ea3e67327c46eb021dd3bfd5b4f3
<|skeleton|> class TextGenerator: """Text generator pipiline.""" def __init__(self, tokenizer, model, device=-1, framework='pt'): """Init class object.""" <|body_0|> def __call__(self, seqs): """Call class object.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TextGenerator: """Text generator pipiline.""" def __init__(self, tokenizer, model, device=-1, framework='pt'): """Init class object.""" set_seed(int(time())) tokenizer = create_tokenizer(tokenizer) model = create_model(model) self._text_generation_pipiline = _creat...
the_stack_v2_python_sparse
gpt/gptrun.py
erdzhemadinov/MADE_FINAL_PROJECT
train
0
cbb07959a07111fd9ce8e3da1b30504cfc95f76a
[ "super().__init__()\nself.forward_func = forward_func\nself.fgsm = FGSM(forward_func, loss_func)\nself.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound)", "def _clip(inputs: Tensor, outputs: Tensor) -> Tensor:\n diff = outputs - inputs\n if norm == 'Linf':\n return inputs + torch.cla...
<|body_start_0|> super().__init__() self.forward_func = forward_func self.fgsm = FGSM(forward_func, loss_func) self.bound = lambda x: torch.clamp(x, min=lower_bound, max=upper_bound) <|end_body_0|> <|body_start_1|> def _clip(inputs: Tensor, outputs: Tensor) -> Tensor: ...
Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the formulation is:: x_0 = x x_(t+1) = ...
PGD
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PGD: """Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the form...
stack_v2_sparse_classes_10k_train_005248
10,165
permissive
[ { "docstring": "Args: forward_func (Callable): The pytorch model for which the attack is computed. loss_func (Callable, optional): Loss function of which the gradient computed. The loss function should take in outputs of the model and labels, and return the loss for each input tensor. The default loss function ...
3
stack_v2_sparse_classes_30k_train_005534
Implement the Python class `PGD` described below. Class description: Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inp...
Implement the Python class `PGD` described below. Class description: Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inp...
945c582cc0b08885c4e2bfecb020abdfac0122f3
<|skeleton|> class PGD: """Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the form...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PGD: """Projected Gradient Descent is an iterative version of the one-step attack FGSM that can generate adversarial examples. It takes multiple gradient steps to search for an adversarial perturbation within the desired neighbor ball around the original inputs. In a non-targeted attack, the formulation is:: ...
the_stack_v2_python_sparse
captum/robust/_core/pgd.py
pytorch/captum
train
4,230
8413b7d86917ba9e26b2fc6aba161653862e9457
[ "if not self._errors:\n self._errors = ErrorDict()\nself._errors['upload_of_work'] = self.error_class([DEF_NO_UPLOAD])", "cleaned_data = self.cleaned_data\nupload = cleaned_data.get('upload_of_work')\nif not upload:\n raise gci_forms.ValidationError(DEF_NO_UPLOAD)\nreturn upload" ]
<|body_start_0|> if not self._errors: self._errors = ErrorDict() self._errors['upload_of_work'] = self.error_class([DEF_NO_UPLOAD]) <|end_body_0|> <|body_start_1|> cleaned_data = self.cleaned_data upload = cleaned_data.get('upload_of_work') if not upload: ...
Django form for submitting work as file.
WorkSubmissionFileForm
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class WorkSubmissionFileForm: """Django form for submitting work as file.""" def addFileRequiredError(self): """Appends a form error message indicating that this field is required.""" <|body_0|> def clean_upload_of_work(self): """Ensure that file field has data.""" ...
stack_v2_sparse_classes_10k_train_005249
26,251
permissive
[ { "docstring": "Appends a form error message indicating that this field is required.", "name": "addFileRequiredError", "signature": "def addFileRequiredError(self)" }, { "docstring": "Ensure that file field has data.", "name": "clean_upload_of_work", "signature": "def clean_upload_of_wor...
2
null
Implement the Python class `WorkSubmissionFileForm` described below. Class description: Django form for submitting work as file. Method signatures and docstrings: - def addFileRequiredError(self): Appends a form error message indicating that this field is required. - def clean_upload_of_work(self): Ensure that file f...
Implement the Python class `WorkSubmissionFileForm` described below. Class description: Django form for submitting work as file. Method signatures and docstrings: - def addFileRequiredError(self): Appends a form error message indicating that this field is required. - def clean_upload_of_work(self): Ensure that file f...
f581989f168189fa3a58c028eff327a16c03e438
<|skeleton|> class WorkSubmissionFileForm: """Django form for submitting work as file.""" def addFileRequiredError(self): """Appends a form error message indicating that this field is required.""" <|body_0|> def clean_upload_of_work(self): """Ensure that file field has data.""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class WorkSubmissionFileForm: """Django form for submitting work as file.""" def addFileRequiredError(self): """Appends a form error message indicating that this field is required.""" if not self._errors: self._errors = ErrorDict() self._errors['upload_of_work'] = self.error...
the_stack_v2_python_sparse
app/soc/modules/gci/views/task.py
sambitgaan/nupic.son
train
0
7b03886651aed082dbce29f2c2b6121a3af1a264
[ "ports = []\nfor start, end in self.term.destination_port:\n if start == end:\n ports.append(str(start))\n else:\n ports.append('%d-%d' % (start, end))\nreturn ports", "settings = [str(x) for x in self.term.logging]\nif any((value in settings for value in ['true', 'True'])):\n return True\n...
<|body_start_0|> ports = [] for start, end in self.term.destination_port: if start == end: ports.append(str(start)) else: ports.append('%d-%d' % (start, end)) return ports <|end_body_0|> <|body_start_1|> settings = [str(x) for x in...
A Term object.
Term
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Term: """A Term object.""" def _GetPorts(self): """Return a port or port range in string format.""" <|body_0|> def _GetLoggingSetting(self): """Return true if a term indicates that logging is desired.""" <|body_1|> <|end_skeleton|> <|body_start_0|> ...
stack_v2_sparse_classes_10k_train_005250
5,001
permissive
[ { "docstring": "Return a port or port range in string format.", "name": "_GetPorts", "signature": "def _GetPorts(self)" }, { "docstring": "Return true if a term indicates that logging is desired.", "name": "_GetLoggingSetting", "signature": "def _GetLoggingSetting(self)" } ]
2
stack_v2_sparse_classes_30k_train_007197
Implement the Python class `Term` described below. Class description: A Term object. Method signatures and docstrings: - def _GetPorts(self): Return a port or port range in string format. - def _GetLoggingSetting(self): Return true if a term indicates that logging is desired.
Implement the Python class `Term` described below. Class description: A Term object. Method signatures and docstrings: - def _GetPorts(self): Return a port or port range in string format. - def _GetLoggingSetting(self): Return true if a term indicates that logging is desired. <|skeleton|> class Term: """A Term o...
d145ca447e0e04895507777b8c5834c22e90df11
<|skeleton|> class Term: """A Term object.""" def _GetPorts(self): """Return a port or port range in string format.""" <|body_0|> def _GetLoggingSetting(self): """Return true if a term indicates that logging is desired.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Term: """A Term object.""" def _GetPorts(self): """Return a port or port range in string format.""" ports = [] for start, end in self.term.destination_port: if start == end: ports.append(str(start)) else: ports.append('%d-%d'...
the_stack_v2_python_sparse
capirca/lib/gcp.py
google/capirca
train
743
699ee7c085ae75873aad30a4a81c344c6e758275
[ "super().__init__()\nif nn_embedding is not None:\n self.embedding = nn.Embedding.from_pretrained(nn_embedding)\nelif sum(field_sizes) is not None and embed_size is not None:\n self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs)\nelse:\n raise ValueError('missing required arguments')\nsel...
<|body_start_0|> super().__init__() if nn_embedding is not None: self.embedding = nn.Embedding.from_pretrained(nn_embedding) elif sum(field_sizes) is not None and embed_size is not None: self.embedding = nn.Embedding(sum(field_sizes), embed_size, **kwargs) else: ...
Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.
MultiIndicesEmbedding
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MultiIndicesEmbedding: """Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.""" def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par...
stack_v2_sparse_classes_10k_train_005251
4,009
permissive
[ { "docstring": "Initialize MultiIndicesEmbedding. Args: embed_size (int): size of embedding tensor. Defaults to None field_sizes (List[int]): list of inputs fields' sizes. Defaults to None nn_embedding (nn.Parameter, optional): pretrained embedding values. Defaults to None device (str): device of torch. Default...
4
stack_v2_sparse_classes_30k_val_000090
Implement the Python class `MultiIndicesEmbedding` described below. Class description: Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding. Method signatures and docstrings: - def __init__(self, embed_size: Optional[int]=None, ...
Implement the Python class `MultiIndicesEmbedding` described below. Class description: Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding. Method signatures and docstrings: - def __init__(self, embed_size: Optional[int]=None, ...
751a43b9cd35e951d81c0d9cf46507b1777bb7ff
<|skeleton|> class MultiIndicesEmbedding: """Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.""" def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Par...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MultiIndicesEmbedding: """Base Input class for embedding indices in multi fields of inputs, which is more efficient than embedding with a number of SingleIndexEmbedding.""" def __init__(self, embed_size: Optional[int]=None, field_sizes: Optional[List[int]]=None, nn_embedding: Optional[nn.Parameter]=None,...
the_stack_v2_python_sparse
torecsys/inputs/base/multi_indices_emb.py
p768lwy3/torecsys
train
98
775c4e98a11283314c39bc56d3be0b1b42ab3c1d
[ "re = ''\nself.d[self.idx] = longUrl\nn = self.idx\nwhile n:\n re += self.code[n % 62]\n n /= 62\nself.idx += 1\nreturn re", "i = 0\nfor x in shortUrl:\n if 'a' <= x <= 'z':\n i = i * 62 + ord(x) - ord('a')\n elif 'A' <= x <= 'Z':\n i = i * 62 + ord(x) - ord('A') + 26\n else:\n ...
<|body_start_0|> re = '' self.d[self.idx] = longUrl n = self.idx while n: re += self.code[n % 62] n /= 62 self.idx += 1 return re <|end_body_0|> <|body_start_1|> i = 0 for x in shortUrl: if 'a' <= x <= 'z': ...
Codec
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str""" <|body_1|> <|end_skeleton|> <|...
stack_v2_sparse_classes_10k_train_005252
1,069
no_license
[ { "docstring": "Encodes a URL to a shortened URL. :type longUrl: str :rtype: str", "name": "encode", "signature": "def encode(self, longUrl)" }, { "docstring": "Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str", "name": "decode", "signature": "def decode(self,...
2
null
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s...
Implement the Python class `Codec` described below. Class description: Implement the Codec class. Method signatures and docstrings: - def encode(self, longUrl): Encodes a URL to a shortened URL. :type longUrl: str :rtype: str - def decode(self, shortUrl): Decodes a shortened URL to its original URL. :type shortUrl: s...
20623defecf65cbc35b194d8b60d8b211816ee4f
<|skeleton|> class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" <|body_0|> def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Codec: def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str""" re = '' self.d[self.idx] = longUrl n = self.idx while n: re += self.code[n % 62] n /= 62 self.idx += 1 return re def dec...
the_stack_v2_python_sparse
in_Python/0535 Encode and Decode TinyURL.py
YangLiyli131/Leetcode2020
train
0
28e494e4b8b335cd133e9b0871810fa45783225b
[ "setting = JsonSetting(settingFilePath)\nself.bd_rest_api = setting.get('bd_rest_api')\nself.oauth = setting.get('oauth')\nself.others = setting.get('others')\nself.access_token = self.get_oauth_token()", "headers = {'content-type': 'application/json'}\nurl = self.bd_rest_api['domain']\nurl += ':' + self.bd_rest_...
<|body_start_0|> setting = JsonSetting(settingFilePath) self.bd_rest_api = setting.get('bd_rest_api') self.oauth = setting.get('oauth') self.others = setting.get('others') self.access_token = self.get_oauth_token() <|end_body_0|> <|body_start_1|> headers = {'content-type...
Building Depot Helpe Class
BuildingDepotHelper
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BuildingDepotHelper: """Building Depot Helpe Class""" def __init__(self, settingFilePath='./knockingSettings.json'): """Initialize instance and load settings""" <|body_0|> def get_oauth_token(self): """Get OAuth access token""" <|body_1|> def get_tim...
stack_v2_sparse_classes_10k_train_005253
4,153
permissive
[ { "docstring": "Initialize instance and load settings", "name": "__init__", "signature": "def __init__(self, settingFilePath='./knockingSettings.json')" }, { "docstring": "Get OAuth access token", "name": "get_oauth_token", "signature": "def get_oauth_token(self)" }, { "docstring...
4
stack_v2_sparse_classes_30k_train_000781
Implement the Python class `BuildingDepotHelper` described below. Class description: Building Depot Helpe Class Method signatures and docstrings: - def __init__(self, settingFilePath='./knockingSettings.json'): Initialize instance and load settings - def get_oauth_token(self): Get OAuth access token - def get_timeser...
Implement the Python class `BuildingDepotHelper` described below. Class description: Building Depot Helpe Class Method signatures and docstrings: - def __init__(self, settingFilePath='./knockingSettings.json'): Initialize instance and load settings - def get_oauth_token(self): Get OAuth access token - def get_timeser...
d7e8237f13cb264f9c772b343e2830ebe1319662
<|skeleton|> class BuildingDepotHelper: """Building Depot Helpe Class""" def __init__(self, settingFilePath='./knockingSettings.json'): """Initialize instance and load settings""" <|body_0|> def get_oauth_token(self): """Get OAuth access token""" <|body_1|> def get_tim...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BuildingDepotHelper: """Building Depot Helpe Class""" def __init__(self, settingFilePath='./knockingSettings.json'): """Initialize instance and load settings""" setting = JsonSetting(settingFilePath) self.bd_rest_api = setting.get('bd_rest_api') self.oauth = setting.get('o...
the_stack_v2_python_sparse
BuildingDepotHelper.py
gs27/Edge-Analytics
train
0
dfe5b57c1f7747701557b2fd3e3d936fbce6c806
[ "loader = DatasetAnnotationLoader(is_full=self.is_full, data_path=self.data_path, cache_path=self.cache_path, verbose=self.verbose)\nyield {'train': loader.load_trainval_data()}\nyield {'train01': loader.load_train_data()}\nyield {'val01': loader.load_val_data()}\nyield {'test': loader.load_test_data()}", "args =...
<|body_start_0|> loader = DatasetAnnotationLoader(is_full=self.is_full, data_path=self.data_path, cache_path=self.cache_path, verbose=self.verbose) yield {'train': loader.load_trainval_data()} yield {'train01': loader.load_train_data()} yield {'val01': loader.load_val_data()} yie...
MPII Keypoints preprocessing functions.
Keypoints
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Keypoints: """MPII Keypoints preprocessing functions.""" def load_data(self): """Load data of the dataset (create a generator).""" <|body_0|> def process_set_metadata(self, data, set_name): """Saves the metadata of a set.""" <|body_1|> <|end_skeleton|> ...
stack_v2_sparse_classes_10k_train_005254
40,392
permissive
[ { "docstring": "Load data of the dataset (create a generator).", "name": "load_data", "signature": "def load_data(self)" }, { "docstring": "Saves the metadata of a set.", "name": "process_set_metadata", "signature": "def process_set_metadata(self, data, set_name)" } ]
2
stack_v2_sparse_classes_30k_train_007282
Implement the Python class `Keypoints` described below. Class description: MPII Keypoints preprocessing functions. Method signatures and docstrings: - def load_data(self): Load data of the dataset (create a generator). - def process_set_metadata(self, data, set_name): Saves the metadata of a set.
Implement the Python class `Keypoints` described below. Class description: MPII Keypoints preprocessing functions. Method signatures and docstrings: - def load_data(self): Load data of the dataset (create a generator). - def process_set_metadata(self, data, set_name): Saves the metadata of a set. <|skeleton|> class ...
e0be95d941b50a5b2e27ffa1c5be20dc6aa2d6a1
<|skeleton|> class Keypoints: """MPII Keypoints preprocessing functions.""" def load_data(self): """Load data of the dataset (create a generator).""" <|body_0|> def process_set_metadata(self, data, set_name): """Saves the metadata of a set.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Keypoints: """MPII Keypoints preprocessing functions.""" def load_data(self): """Load data of the dataset (create a generator).""" loader = DatasetAnnotationLoader(is_full=self.is_full, data_path=self.data_path, cache_path=self.cache_path, verbose=self.verbose) yield {'train': loa...
the_stack_v2_python_sparse
dbcollection/datasets/mpii_pose/keypoints.py
dbcollection/dbcollection
train
25
5a72f648c91433466e9fcaeca14595ef16a158db
[ "super(FSSD, self).__init__(p, alpha)\nself.k = k\nself.V = V\nself.null_sim = null_sim", "alpha = self.alpha\nnull_sim = self.null_sim\nn_simulate = null_sim.n_simulate\nn = X.shape[0]\nJ = self.V.shape[0]\nnfssd, fea_tensor = self.statistic(X, return_feature_tensor=True)\nsim_results = null_sim.simulate(self, X...
<|body_start_0|> super(FSSD, self).__init__(p, alpha) self.k = k self.V = V self.null_sim = null_sim <|end_body_0|> <|body_start_1|> alpha = self.alpha null_sim = self.null_sim n_simulate = null_sim.n_simulate n = X.shape[0] J = self.V.shape[0] ...
Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H1` : the sample does not follow :math:`p` :math:`p` is specified to the...
FSSD
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FSSD: """Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H1` : the sample does not follow :math:`...
stack_v2_sparse_classes_10k_train_005255
16,140
permissive
[ { "docstring": "Parameters ---------- p : an instance of UnnormalizedDensity k : a DifferentiableKernel object V : J x dx numpy array of J locations to test the difference null_sim : an instance of H0Simulator for simulating from the null distribution. alpha : significance level", "name": "__init__", "s...
5
stack_v2_sparse_classes_30k_train_003999
Implement the Python class `FSSD` described below. Class description: Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H...
Implement the Python class `FSSD` described below. Class description: Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H...
9e7fc39f215a7f2b9174ab02bcf71a36067d7e19
<|skeleton|> class FSSD: """Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H1` : the sample does not follow :math:`...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FSSD: """Goodness-of-fit test using The Finite Set Stein Discrepancy statistic. and a set of paired test locations. The statistic is n*FSSD^2. The statistic can be negative because of the unbiased estimator. :math:`H0` : the sample follows :math:`p` :math:`H1` : the sample does not follow :math:`p` :math:`p` ...
the_stack_v2_python_sparse
hyppo/kgof/fssd.py
neurodata/hyppo
train
186
2e75f3f70ab13799d3b163d4f2873035a0de5839
[ "self.active = False\nLabel.__init__(self, name, None, rect, background_color)\nself.return_callback = return_callback\nreturn", "if len(keydown_event.unicode) and unicodedata.category(keydown_event.unicode)[0] in 'LNPSZ':\n self.text = self.text + keydown_event.unicode\nelif keydown_event.key == pygame.K_BACK...
<|body_start_0|> self.active = False Label.__init__(self, name, None, rect, background_color) self.return_callback = return_callback return <|end_body_0|> <|body_start_1|> if len(keydown_event.unicode) and unicodedata.category(keydown_event.unicode)[0] in 'LNPSZ': se...
A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox is active, initally False.
TextBox
[ "Unlicense" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TextBox: """A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox ...
stack_v2_sparse_classes_10k_train_005256
27,668
permissive
[ { "docstring": "Initialise the TextBox. If return_callback is given, return_callback(TextBox.text) will be called when [RETURN] is pressed.", "name": "__init__", "signature": "def __init__(self, name, rect, return_callback=None, background_color=(250, 250, 250))" }, { "docstring": "If printable,...
5
stack_v2_sparse_classes_30k_val_000329
Implement the Python class `TextBox` described below. Class description: A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.ac...
Implement the Python class `TextBox` described below. Class description: A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.ac...
c2fc3d4e9beedb8487cfa4bfa13bdf55ec36af97
<|skeleton|> class TextBox: """A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TextBox: """A box where the user can type text. To actually receive key events, the TextBox must be registered with the Display using Display.key_sensitive(TextBox). Attributes: TextBox.text Standard Label attribute, holding the text typed so far. TextBox.active Boolean flag whether this TextBox is active, in...
the_stack_v2_python_sparse
reference_scripts/clickndrag-0.4.1/clickndrag/gui.py
stivosaurus/rpi-snippets
train
1
e50d4668751b33b8d5505a300d5236347070edc0
[ "if not isinstance(typecode, ElementDeclaration):\n return False\ntry:\n nsuri, ncname = typecode.substitutionGroup\nexcept (AttributeError, TypeError):\n return False\nif (nsuri, ncname) != (self.schema, self.literal):\n if not nsuri and (not self.schema) and (ncname == self.literal):\n return T...
<|body_start_0|> if not isinstance(typecode, ElementDeclaration): return False try: nsuri, ncname = typecode.substitutionGroup except (AttributeError, TypeError): return False if (nsuri, ncname) != (self.schema, self.literal): if not nsuri ...
Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)
ElementDeclaration
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ElementDeclaration: """Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)""" def checkSubstitute(self, typecode): """If th...
stack_v2_sparse_classes_10k_train_005257
14,557
permissive
[ { "docstring": "If this is True, allow typecode to be substituted for \"self\" typecode.", "name": "checkSubstitute", "signature": "def checkSubstitute(self, typecode)" }, { "docstring": "if elt matches a member of the head substitutionGroup, return the GED typecode representation of the member....
2
stack_v2_sparse_classes_30k_train_006124
Implement the Python class `ElementDeclaration` described below. Class description: Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName) Method signatures and...
Implement the Python class `ElementDeclaration` described below. Class description: Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName) Method signatures and...
9b890e6a25471037b7485e4999b480de7c86b656
<|skeleton|> class ElementDeclaration: """Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)""" def checkSubstitute(self, typecode): """If th...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ElementDeclaration: """Typecodes subclass to represent a Global Element Declaration by setting class variables schema and literal. schema = namespaceURI literal = NCName substitutionGroup -- GED reference of form, (namespaceURI,NCName)""" def checkSubstitute(self, typecode): """If this is True, a...
the_stack_v2_python_sparse
Libraries/DUTs/Community/di_vsphere/pysphere/pysphere/ZSI/schema.py
Spirent/iTest-assets
train
10
6de0436abd47ba94fac9bb05fdbe77550bf7c91f
[ "super().__init__(*args, **kargs)\nself.set_field_from_dict('token')\nself.fields['token'].help_text = _('Authentication token provided by the external platform.')", "form_data = super().clean()\nself.store_field_in_dict('token')\nreturn form_data" ]
<|body_start_0|> super().__init__(*args, **kargs) self.set_field_from_dict('token') self.fields['token'].help_text = _('Authentication token provided by the external platform.') <|end_body_0|> <|body_start_1|> form_data = super().clean() self.store_field_in_dict('token') ...
Form to include a token field.
JSONTokenForm
[ "MIT", "LGPL-2.0-or-later", "Python-2.0", "BSD-3-Clause", "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" <|body_0|> def clean(self): """Verify form values.""" <|body_1|> <|end_skeleton|> <|body_start_0|> sup...
stack_v2_sparse_classes_10k_train_005258
20,237
permissive
[ { "docstring": "Modify the fields with the adequate information.", "name": "__init__", "signature": "def __init__(self, *args, **kargs)" }, { "docstring": "Verify form values.", "name": "clean", "signature": "def clean(self)" } ]
2
stack_v2_sparse_classes_30k_train_005316
Implement the Python class `JSONTokenForm` described below. Class description: Form to include a token field. Method signatures and docstrings: - def __init__(self, *args, **kargs): Modify the fields with the adequate information. - def clean(self): Verify form values.
Implement the Python class `JSONTokenForm` described below. Class description: Form to include a token field. Method signatures and docstrings: - def __init__(self, *args, **kargs): Modify the fields with the adequate information. - def clean(self): Verify form values. <|skeleton|> class JSONTokenForm: """Form t...
5473e9faa24c71a2a1102d47ebc2cbf27608e42a
<|skeleton|> class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" <|body_0|> def clean(self): """Verify form values.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class JSONTokenForm: """Form to include a token field.""" def __init__(self, *args, **kargs): """Modify the fields with the adequate information.""" super().__init__(*args, **kargs) self.set_field_from_dict('token') self.fields['token'].help_text = _('Authentication token provid...
the_stack_v2_python_sparse
ontask/action/forms/run.py
LucasFranciscoCorreia/ontask_b
train
0
c820c3c7e7dcfe12689941e64853d6cfd77af07a
[ "RadianceMaterial.__init__(self, name, materialType='glow', modifier='void')\nself.red = red\n'A positive value for the Red channel of the glow'\nself.green = green\n'A positive value for the Green channel of the glow'\nself.blue = blue\n'A positive value for the Blue channel of the glow'\nself.maxRadius = maxRadiu...
<|body_start_0|> RadianceMaterial.__init__(self, name, materialType='glow', modifier='void') self.red = red 'A positive value for the Red channel of the glow' self.green = green 'A positive value for the Green channel of the glow' self.blue = blue 'A positive valu...
Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue channel of the glow maxRadius: ---.
GlowMaterial
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GlowMaterial: """Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue chann...
stack_v2_sparse_classes_10k_train_005259
2,004
permissive
[ { "docstring": "Init Glow material.", "name": "__init__", "signature": "def __init__(self, name, red=0, green=0, blue=0, maxRadius=0)" }, { "docstring": "Return full Radiance definition", "name": "toRadString", "signature": "def toRadString(self, minimal=False)" } ]
2
stack_v2_sparse_classes_30k_train_000632
Implement the Python class `GlowMaterial` described below. Class description: Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow bl...
Implement the Python class `GlowMaterial` described below. Class description: Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow bl...
983fccc934e5546082557f6c2d1f2d9e00eba332
<|skeleton|> class GlowMaterial: """Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue chann...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GlowMaterial: """Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue channel of the glo...
the_stack_v2_python_sparse
honeybee/radiance/material/glow.py
ladybug-tools/honeybee-server
train
7
852d86266232703c304e5b8618d514285eb59aad
[ "assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.'\nself.sample_id_set = set(sample_ids)\nself.scope_type = scope_type", "if self.scope_type == FILTER_SCOPE__ALL:\n intersection = samples_passing_for_variant & self.sample_id_set\n return intersection == self.sample_id_set\nelif self.scope_type...
<|body_start_0|> assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.' self.sample_id_set = set(sample_ids) self.scope_type = scope_type <|end_body_0|> <|body_start_1|> if self.scope_type == FILTER_SCOPE__ALL: intersection = samples_passing_for_variant & self.sampl...
Represents the scope that a filter should be applied over.
FilterScope
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FilterScope: """Represents the scope that a filter should be applied over.""" def __init__(self, scope_type, sample_ids): """Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.""" <|body_0|> def do_passing_samples_satisfy_scope(self, samples_...
stack_v2_sparse_classes_10k_train_005260
2,031
permissive
[ { "docstring": "Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.", "name": "__init__", "signature": "def __init__(self, scope_type, sample_ids)" }, { "docstring": "Returns a Boolean indicating whether the samples satisfy the scope.", "name": "do_passing_sample...
3
stack_v2_sparse_classes_30k_train_001781
Implement the Python class `FilterScope` described below. Class description: Represents the scope that a filter should be applied over. Method signatures and docstrings: - def __init__(self, scope_type, sample_ids): Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES. - def do_passing_samp...
Implement the Python class `FilterScope` described below. Class description: Represents the scope that a filter should be applied over. Method signatures and docstrings: - def __init__(self, scope_type, sample_ids): Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES. - def do_passing_samp...
898936072a716a799462c113286056690a7723d1
<|skeleton|> class FilterScope: """Represents the scope that a filter should be applied over.""" def __init__(self, scope_type, sample_ids): """Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.""" <|body_0|> def do_passing_samples_satisfy_scope(self, samples_...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FilterScope: """Represents the scope that a filter should be applied over.""" def __init__(self, scope_type, sample_ids): """Args: sample_ids: Set of sample ids. scope_type: A scope in VALID_FILTER_SCOPES.""" assert scope_type in VALID_FILTER_SCOPES, 'Invalid scope type.' self.sam...
the_stack_v2_python_sparse
genome_designer/variants/filter_scope.py
RubensZimbres/millstone
train
1
ebd0adda3d25ec5a178f55e622ebaa639de6de45
[ "if image_meta is None:\n image_meta = {}\nimage_meta = copy.deepcopy(image_meta)\nimage_meta['properties'] = objects.ImageMetaProps.from_dict(image_meta.get('properties', {}))\nfor fld in NULLABLE_STRING_FIELDS:\n if fld in image_meta and image_meta[fld] is None:\n image_meta[fld] = ''\nfor fld in NUL...
<|body_start_0|> if image_meta is None: image_meta = {} image_meta = copy.deepcopy(image_meta) image_meta['properties'] = objects.ImageMetaProps.from_dict(image_meta.get('properties', {})) for fld in NULLABLE_STRING_FIELDS: if fld in image_meta and image_meta[fld]...
ImageMeta
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ImageMeta: def from_dict(cls, image_meta): """Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance""" <|bod...
stack_v2_sparse_classes_10k_train_005261
31,126
permissive
[ { "docstring": "Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance", "name": "from_dict", "signature": "def from_dict(cls, image_...
3
stack_v2_sparse_classes_30k_train_004661
Implement the Python class `ImageMeta` described below. Class description: Implement the ImageMeta class. Method signatures and docstrings: - def from_dict(cls, image_meta): Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the prope...
Implement the Python class `ImageMeta` described below. Class description: Implement the ImageMeta class. Method signatures and docstrings: - def from_dict(cls, image_meta): Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the prope...
065c5906d2da3e2bb6eeb3a7a15d4cd8d98b35e9
<|skeleton|> class ImageMeta: def from_dict(cls, image_meta): """Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance""" <|bod...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ImageMeta: def from_dict(cls, image_meta): """Create instance from image metadata dict :param image_meta: image metadata dictionary Creates a new object instance, initializing from the properties associated with the image metadata instance :returns: an ImageMeta instance""" if image_meta is No...
the_stack_v2_python_sparse
nova/objects/image_meta.py
openstack/nova
train
2,287
8af38bc258b027642cf1db7d75621e7c25c195eb
[ "self.model = KNeighborsClassifier(n_neighbors=3)\nself.X = X\nself.Y = Y", "if params is None:\n params = [{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20], 'weights': ['uniform', 'distance']}]\nself.CV = KFoldCrossVal(self.X, self.Y, folds=kfold)\nself.CV.tune_and_evaluate(self.model, parameters=param...
<|body_start_0|> self.model = KNeighborsClassifier(n_neighbors=3) self.X = X self.Y = Y <|end_body_0|> <|body_start_1|> if params is None: params = [{'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20], 'weights': ['uniform', 'distance']}] self.CV = KFoldCrossVal(...
K-nearest neighbor classifier
KNN
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class KNN: """K-nearest neighbor classifier""" def __init__(self, X, Y): """:param X: :param Y:""" <|body_0|> def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): """:param results_file: :param params: :param njobs: :param kfold: :return:""" ...
stack_v2_sparse_classes_10k_train_005262
10,404
permissive
[ { "docstring": ":param X: :param Y:", "name": "__init__", "signature": "def __init__(self, X, Y)" }, { "docstring": ":param results_file: :param params: :param njobs: :param kfold: :return:", "name": "tune_and_eval", "signature": "def tune_and_eval(self, results_file, params=None, njobs=...
3
stack_v2_sparse_classes_30k_train_003275
Implement the Python class `KNN` described below. Class description: K-nearest neighbor classifier Method signatures and docstrings: - def __init__(self, X, Y): :param X: :param Y: - def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): :param results_file: :param params: :param njobs: :param kfold:...
Implement the Python class `KNN` described below. Class description: K-nearest neighbor classifier Method signatures and docstrings: - def __init__(self, X, Y): :param X: :param Y: - def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): :param results_file: :param params: :param njobs: :param kfold:...
127177deb630ad66520a2fdae1793417cd77ee99
<|skeleton|> class KNN: """K-nearest neighbor classifier""" def __init__(self, X, Y): """:param X: :param Y:""" <|body_0|> def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): """:param results_file: :param params: :param njobs: :param kfold: :return:""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class KNN: """K-nearest neighbor classifier""" def __init__(self, X, Y): """:param X: :param Y:""" self.model = KNeighborsClassifier(n_neighbors=3) self.X = X self.Y = Y def tune_and_eval(self, results_file, params=None, njobs=50, kfold=10): """:param results_file: ...
the_stack_v2_python_sparse
classifier/classical_classifiers.py
seedpcseed/DiTaxa
train
0
72a5672a6bae08e14ece7c8a608b058e163012e6
[ "startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('cici_fyl', 'cici_fyl')\npropertydata = repo['cici_fyl.property'].find()\nrestaurantdata = repo['cici_fyl.restaurant'].find()\ncoor = methods.selectcoordinate(restaurantdata)\nx = methods.appendattribute(...
<|body_start_0|> startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cici_fyl', 'cici_fyl') propertydata = repo['cici_fyl.property'].find() restaurantdata = repo['cici_fyl.restaurant'].find() coor = methods....
processrestaurant
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class processrestaurant: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everyt...
stack_v2_sparse_classes_10k_train_005263
3,335
permissive
[ { "docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).", "name": "execute", "signature": "def execute(trial=False)" }, { "docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d...
2
null
Implement the Python class `processrestaurant` described below. Class description: Implement the processrestaurant class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime...
Implement the Python class `processrestaurant` described below. Class description: Implement the processrestaurant class. Method signatures and docstrings: - def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity). - def provenance(doc=prov.model.ProvDocument(), startTime...
0df485d0469c5451ebdcd684bed2a0960ba3ab84
<|skeleton|> class processrestaurant: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" <|body_0|> def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None): """Create the provenance document describing everyt...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class processrestaurant: def execute(trial=False): """Retrieve some data sets (not using the API here for the sake of simplicity).""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('cici_fyl', 'cici_fyl') pr...
the_stack_v2_python_sparse
cici_fyl/project/cici_fyl/processrestaurant.py
lingyigu/course-2017-spr-proj
train
0
90d9ba94b2779fe3901790cb22932ed1e80e98c9
[ "if x < 0:\n raise Exception('不能输入负数')\nif x == 0:\n return 0\ncur = -5\nwhile True:\n pre = cur\n cur = (cur + x / cur) / 2\n if abs(cur - pre) < 1e-06:\n return cur", "if x < 0:\n raise Exception('不能输入负数')\nif x == 0:\n return 0\ncur = 1\nwhile True:\n pre = cur\n cur = (cur + ...
<|body_start_0|> if x < 0: raise Exception('不能输入负数') if x == 0: return 0 cur = -5 while True: pre = cur cur = (cur + x / cur) / 2 if abs(cur - pre) < 1e-06: return cur <|end_body_0|> <|body_start_1|> if ...
Solution
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def mySqrt(self, x): """:type x: int :rtype: int""" <|body_0|> def mySqrt1(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|> <|body_start_0|> if x < 0: raise Exception('不能输入负数') if x == 0: ...
stack_v2_sparse_classes_10k_train_005264
1,203
permissive
[ { "docstring": ":type x: int :rtype: int", "name": "mySqrt", "signature": "def mySqrt(self, x)" }, { "docstring": ":type x: int :rtype: int", "name": "mySqrt1", "signature": "def mySqrt1(self, x)" } ]
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mySqrt(self, x): :type x: int :rtype: int - def mySqrt1(self, x): :type x: int :rtype: int
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def mySqrt(self, x): :type x: int :rtype: int - def mySqrt1(self, x): :type x: int :rtype: int <|skeleton|> class Solution: def mySqrt(self, x): """:type x: int :rt...
b484ae4c4e9f9186232e31f2de11720aebb42968
<|skeleton|> class Solution: def mySqrt(self, x): """:type x: int :rtype: int""" <|body_0|> def mySqrt1(self, x): """:type x: int :rtype: int""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def mySqrt(self, x): """:type x: int :rtype: int""" if x < 0: raise Exception('不能输入负数') if x == 0: return 0 cur = -5 while True: pre = cur cur = (cur + x / cur) / 2 if abs(cur - pre) < 1e-06: ...
the_stack_v2_python_sparse
17-二分查找/0069_1.py
Sytx74/LeetCode-Solution-Python
train
0
da693becd45b726478b01c075df233acff71672f
[ "self.current_dir = os.getcwd()\nnow = datetime.now().strftime('%I%p_%m_%d_%Y')\ntest_name = self.__class__.__name__\nself.tempdir = '{}_{}'.format(test_name, now)\nif not os.path.isdir(self.tempdir):\n os.mkdir(self.tempdir)\nos.chdir(self.tempdir)\nopen('test.pdb', 'w').write(test_pdb_str)", "params_phil = i...
<|body_start_0|> self.current_dir = os.getcwd() now = datetime.now().strftime('%I%p_%m_%d_%Y') test_name = self.__class__.__name__ self.tempdir = '{}_{}'.format(test_name, now) if not os.path.isdir(self.tempdir): os.mkdir(self.tempdir) os.chdir(self.tempdir) ...
TestPDBinterpretationNCSSearch
[ "BSD-3-Clause-LBNL", "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestPDBinterpretationNCSSearch: def setUp(self): """Create temporary folder for temp files produced during test""" <|body_0|> def test_calling_pdb_interpretation(self): """Make sure can create NCS object and change search parameters""" <|body_1|> def tea...
stack_v2_sparse_classes_10k_train_005265
6,330
permissive
[ { "docstring": "Create temporary folder for temp files produced during test", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Make sure can create NCS object and change search parameters", "name": "test_calling_pdb_interpretation", "signature": "def test_calling_pdb_in...
3
null
Implement the Python class `TestPDBinterpretationNCSSearch` described below. Class description: Implement the TestPDBinterpretationNCSSearch class. Method signatures and docstrings: - def setUp(self): Create temporary folder for temp files produced during test - def test_calling_pdb_interpretation(self): Make sure ca...
Implement the Python class `TestPDBinterpretationNCSSearch` described below. Class description: Implement the TestPDBinterpretationNCSSearch class. Method signatures and docstrings: - def setUp(self): Create temporary folder for temp files produced during test - def test_calling_pdb_interpretation(self): Make sure ca...
77d66c719b5746f37af51ad593e2941ed6fbba17
<|skeleton|> class TestPDBinterpretationNCSSearch: def setUp(self): """Create temporary folder for temp files produced during test""" <|body_0|> def test_calling_pdb_interpretation(self): """Make sure can create NCS object and change search parameters""" <|body_1|> def tea...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestPDBinterpretationNCSSearch: def setUp(self): """Create temporary folder for temp files produced during test""" self.current_dir = os.getcwd() now = datetime.now().strftime('%I%p_%m_%d_%Y') test_name = self.__class__.__name__ self.tempdir = '{}_{}'.format(test_name, ...
the_stack_v2_python_sparse
modules/cctbx_project/mmtbx/monomer_library/tst_pdb_interpretation_ncs_processing.py
jorgediazjr/dials-dev20191018
train
0
4e795d4488a814ebc494485f02c8f499cea11005
[ "try:\n blog = Blog.find(year, month, day, slug)\nexcept Blog.DoesNotExist:\n abort(404, message='No such blog')\nexcept ValueError:\n abort(409, message='Multiple blogs found')\nreturn blog", "try:\n blog = Blog.find(year, month, day, slug)\nexcept Blog.DoesNotExist:\n abort(404, message='No such ...
<|body_start_0|> try: blog = Blog.find(year, month, day, slug) except Blog.DoesNotExist: abort(404, message='No such blog') except ValueError: abort(409, message='Multiple blogs found') return blog <|end_body_0|> <|body_start_1|> try: ...
BlogAPI
[ "BSD-2-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BlogAPI: def get(self, year, month, day, slug): """Get blog post details""" <|body_0|> def patch(self, args, year, month, day, slug): """Edit blog post details""" <|body_1|> def delete(self, year, month, day, slug): """Delete blog post""" ...
stack_v2_sparse_classes_10k_train_005266
4,891
permissive
[ { "docstring": "Get blog post details", "name": "get", "signature": "def get(self, year, month, day, slug)" }, { "docstring": "Edit blog post details", "name": "patch", "signature": "def patch(self, args, year, month, day, slug)" }, { "docstring": "Delete blog post", "name": ...
3
stack_v2_sparse_classes_30k_train_002099
Implement the Python class `BlogAPI` described below. Class description: Implement the BlogAPI class. Method signatures and docstrings: - def get(self, year, month, day, slug): Get blog post details - def patch(self, args, year, month, day, slug): Edit blog post details - def delete(self, year, month, day, slug): Del...
Implement the Python class `BlogAPI` described below. Class description: Implement the BlogAPI class. Method signatures and docstrings: - def get(self, year, month, day, slug): Get blog post details - def patch(self, args, year, month, day, slug): Edit blog post details - def delete(self, year, month, day, slug): Del...
dffc3b1e16c24dd49e516e36aaa731a8dd299e66
<|skeleton|> class BlogAPI: def get(self, year, month, day, slug): """Get blog post details""" <|body_0|> def patch(self, args, year, month, day, slug): """Edit blog post details""" <|body_1|> def delete(self, year, month, day, slug): """Delete blog post""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BlogAPI: def get(self, year, month, day, slug): """Get blog post details""" try: blog = Blog.find(year, month, day, slug) except Blog.DoesNotExist: abort(404, message='No such blog') except ValueError: abort(409, message='Multiple blogs found...
the_stack_v2_python_sparse
tilda/api/blog.py
tilda-center/backend
train
0
eed1f56088fe29b3dd51b95f2696fb74890ddf4d
[ "invalid = self.get_invalid(instance)\nif invalid:\n raise RuntimeError('Nodes found with non-unique asset IDs: {0}'.format(invalid))", "others = [i for i in list(instance.context) if i is not instance and set(cls.families) & get_families(i)]\nif not others:\n return []\nother_ids = defaultdict(list)\nfor o...
<|body_start_0|> invalid = self.get_invalid(instance) if invalid: raise RuntimeError('Nodes found with non-unique asset IDs: {0}'.format(invalid)) <|end_body_0|> <|body_start_1|> others = [i for i in list(instance.context) if i is not instance and set(cls.families) & get_families(i)...
Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This will *NOT* validate against previous publishes or publishes be...
ValidateNodeIdsUniqueInstanceClash
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This ...
stack_v2_sparse_classes_10k_train_005267
2,944
no_license
[ { "docstring": "Process all meshes", "name": "process", "signature": "def process(self, instance)" }, { "docstring": "Return the member nodes that are invalid", "name": "get_invalid", "signature": "def get_invalid(cls, instance)" } ]
2
stack_v2_sparse_classes_30k_train_001908
Implement the Python class `ValidateNodeIdsUniqueInstanceClash` described below. Class description: Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DI...
Implement the Python class `ValidateNodeIdsUniqueInstanceClash` described below. Class description: Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DI...
fa1a22297c1b2cfd48c88372958360fe4004524b
<|skeleton|> class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ValidateNodeIdsUniqueInstanceClash: """Validate nodes across model instances have a unique Colorbleed Id This validates whether the node ids to be published are unique across all model instances currently being published (even if those other instances are DISABLED currently for publishing). This will *NOT* va...
the_stack_v2_python_sparse
colorbleed/plugins/maya/publish/validate_node_ids_unique_in_asset.py
BigRoy/colorbleed-config
train
3
545d15c4ae69c6b5ce1bdec93aadf562840fdac5
[ "if node_type == None:\n node_type = node_base\nif edge_type == None:\n edge_type = edge_base\nsuper().__init__()\nself.node_type = node_type\nself.edge_type = edge_type\nself.node_list = []\nself.edge_list = []\nself.mst = None", "self.unionset = unionset(len(self.node_list), int)\nself.edge_list.sort()\ns...
<|body_start_0|> if node_type == None: node_type = node_base if edge_type == None: edge_type = edge_base super().__init__() self.node_type = node_type self.edge_type = edge_type self.node_list = [] self.edge_list = [] self.mst = Non...
mst_base
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class mst_base: def __init__(self, node_type=None, edge_type=None): """vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix""" <|body_0|> def generate_mst(self): """The base function for ...
stack_v2_sparse_classes_10k_train_005268
1,213
no_license
[ { "docstring": "vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix", "name": "__init__", "signature": "def __init__(self, node_type=None, edge_type=None)" }, { "docstring": "The base function for mst Using Kr...
2
stack_v2_sparse_classes_30k_train_002046
Implement the Python class `mst_base` described below. Class description: Implement the mst_base class. Method signatures and docstrings: - def __init__(self, node_type=None, edge_type=None): vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adj...
Implement the Python class `mst_base` described below. Class description: Implement the mst_base class. Method signatures and docstrings: - def __init__(self, node_type=None, edge_type=None): vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adj...
2bd6aaadb8f6abcc13e9c468adff74c93b0ae6b2
<|skeleton|> class mst_base: def __init__(self, node_type=None, edge_type=None): """vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix""" <|body_0|> def generate_mst(self): """The base function for ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class mst_base: def __init__(self, node_type=None, edge_type=None): """vector_list: list, with node value edge_list: list, with edge value edge_type: str, 'list' for adjacent list, 'matrix' for adjacent matrix""" if node_type == None: node_type = node_base if edge_type == None: ...
the_stack_v2_python_sparse
graph_utils/mstpy/mst_base.py
jrahim/graph_clean
train
0
1211e5b131221213cb19ce2d4b47a69eb29ed613
[ "super().__init__(infile, outfile)\nself.infile2 = infile2\nself._default_method = 'fastqutils'", "self.install_tool('fastqutils')\nif self.infile2 is not None:\n cmd = 'fastqutils tobam -1 {} -2 {} -o {}'.format(self.infile, self.infile2, self.outfile)\nelse:\n cmd = 'fastqutils tobam -1 {} -o {}'.format(s...
<|body_start_0|> super().__init__(infile, outfile) self.infile2 = infile2 self._default_method = 'fastqutils' <|end_body_0|> <|body_start_1|> self.install_tool('fastqutils') if self.infile2 is not None: cmd = 'fastqutils tobam -1 {} -2 {} -o {}'.format(self.infile, s...
Convert :term:`FASTQ` to :term:`BAM`
FASTQ2BAM
[ "BSD-3-Clause" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class FASTQ2BAM: """Convert :term:`FASTQ` to :term:`BAM`""" def __init__(self, infile, outfile, infile2=None, *args, **kwargs): """:param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.""" <|body_0|> def _method_fastqutils(self, *...
stack_v2_sparse_classes_10k_train_005269
1,716
permissive
[ { "docstring": ":param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.", "name": "__init__", "signature": "def __init__(self, infile, outfile, infile2=None, *args, **kwargs)" }, { "docstring": "Converts a fastq file to an unaligned bam file", "n...
2
stack_v2_sparse_classes_30k_train_004769
Implement the Python class `FASTQ2BAM` described below. Class description: Convert :term:`FASTQ` to :term:`BAM` Method signatures and docstrings: - def __init__(self, infile, outfile, infile2=None, *args, **kwargs): :param str infile: The path to the input FASTA file. :param str outfile: The path to the output file. ...
Implement the Python class `FASTQ2BAM` described below. Class description: Convert :term:`FASTQ` to :term:`BAM` Method signatures and docstrings: - def __init__(self, infile, outfile, infile2=None, *args, **kwargs): :param str infile: The path to the input FASTA file. :param str outfile: The path to the output file. ...
60a746290e763fd1041732dab0bda123841e5b26
<|skeleton|> class FASTQ2BAM: """Convert :term:`FASTQ` to :term:`BAM`""" def __init__(self, infile, outfile, infile2=None, *args, **kwargs): """:param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.""" <|body_0|> def _method_fastqutils(self, *...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class FASTQ2BAM: """Convert :term:`FASTQ` to :term:`BAM`""" def __init__(self, infile, outfile, infile2=None, *args, **kwargs): """:param str infile: The path to the input FASTA file. :param str outfile: The path to the output file.""" super().__init__(infile, outfile) self.infile2 = in...
the_stack_v2_python_sparse
bioconvert/fastq2bam.py
ddesvillechabrol/bioconvert
train
1
0d60b7b8526aa669ba65b13104a262556c82576a
[ "if keys is None:\n keys = ['ymin', 'xmin', 'ymax', 'xmax']\nelif len(keys) != 4:\n raise ValueError('BoundingBox expects 4 keys but got {}'.format(len(keys)))\nself._prefix = prefix\nself._keys = keys\nself._full_keys = [prefix + k for k in keys]\nsuper(BoundingBox, self).__init__(self._full_keys)", "sides...
<|body_start_0|> if keys is None: keys = ['ymin', 'xmin', 'ymax', 'xmax'] elif len(keys) != 4: raise ValueError('BoundingBox expects 4 keys but got {}'.format(len(keys))) self._prefix = prefix self._keys = keys self._full_keys = [prefix + k for k in keys] ...
An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes.
BoundingBox
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BoundingBox: """An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes.""" def __init__(self, keys=None, prefix=None): """Initialize the bounding box handler. Args: keys: A list of four key names representing the ymin, xmin, ymax, mmax prefix: An optional prefix f...
stack_v2_sparse_classes_10k_train_005270
15,383
permissive
[ { "docstring": "Initialize the bounding box handler. Args: keys: A list of four key names representing the ymin, xmin, ymax, mmax prefix: An optional prefix for each of the bounding box keys. If provided, `prefix` is appended to each key in `keys`. Raises: ValueError: if keys is not `None` and also not a list o...
2
null
Implement the Python class `BoundingBox` described below. Class description: An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes. Method signatures and docstrings: - def __init__(self, keys=None, prefix=None): Initialize the bounding box handler. Args: keys: A list of four key names representin...
Implement the Python class `BoundingBox` described below. Class description: An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes. Method signatures and docstrings: - def __init__(self, keys=None, prefix=None): Initialize the bounding box handler. Args: keys: A list of four key names representin...
cabf6e4f1970dc14302f87414f170de19944bac2
<|skeleton|> class BoundingBox: """An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes.""" def __init__(self, keys=None, prefix=None): """Initialize the bounding box handler. Args: keys: A list of four key names representing the ymin, xmin, ymax, mmax prefix: An optional prefix f...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BoundingBox: """An ItemHandler that concatenates a set of parsed Tensors to Bounding Boxes.""" def __init__(self, keys=None, prefix=None): """Initialize the bounding box handler. Args: keys: A list of four key names representing the ymin, xmin, ymax, mmax prefix: An optional prefix for each of th...
the_stack_v2_python_sparse
Tensorflow_OpenCV_Nightly/source/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py
ryfeus/lambda-packs
train
1,283
cb3734155c0c730f3d201e966eed33c3a665a7a9
[ "pu = ground_level_m\nlatitude, longitude, _alt = pm.enu2geodetic(pe_m, pn_m, pu, lat0_rad, lon0_rad, ground_level_m, ell=None, deg=False)\necef_x, ecef_y, ecef_z = pm.enu2ecef(pe_m, pn_m, pu, lat0_rad, lon0_rad, ground_level_m, ell=None, deg=False)\nglobal_rotation = Rotation.from_quat(Dubins2DConverter.quaternion...
<|body_start_0|> pu = ground_level_m latitude, longitude, _alt = pm.enu2geodetic(pe_m, pn_m, pu, lat0_rad, lon0_rad, ground_level_m, ell=None, deg=False) ecef_x, ecef_y, ecef_z = pm.enu2ecef(pe_m, pn_m, pu, lat0_rad, lon0_rad, ground_level_m, ell=None, deg=False) global_rotation = Rotati...
Dubins2DConverter
[ "GPL-3.0-only", "BSD-3-Clause", "GPL-1.0-or-later" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Dubins2DConverter: def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list: """This method takes in a dictionary of "raw" 2D Dubins log data, as read from the LogReader class, and returns a populated Episode object.""" <|body_0|> def qua...
stack_v2_sparse_classes_10k_train_005271
2,905
permissive
[ { "docstring": "This method takes in a dictionary of \"raw\" 2D Dubins log data, as read from the LogReader class, and returns a populated Episode object.", "name": "convert_data", "signature": "def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list" }, { "...
2
stack_v2_sparse_classes_30k_val_000400
Implement the Python class `Dubins2DConverter` described below. Class description: Implement the Dubins2DConverter class. Method signatures and docstrings: - def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list: This method takes in a dictionary of "raw" 2D Dubins log data, as...
Implement the Python class `Dubins2DConverter` described below. Class description: Implement the Dubins2DConverter class. Method signatures and docstrings: - def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list: This method takes in a dictionary of "raw" 2D Dubins log data, as...
c90a7346f3a2a651adda5b6ead47d4989af59dcc
<|skeleton|> class Dubins2DConverter: def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list: """This method takes in a dictionary of "raw" 2D Dubins log data, as read from the LogReader class, and returns a populated Episode object.""" <|body_0|> def qua...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Dubins2DConverter: def convert_data(cls, pn_m, pe_m, alt_m, psi_rad, lat0_rad, lon0_rad, ground_level_m) -> list: """This method takes in a dictionary of "raw" 2D Dubins log data, as read from the LogReader class, and returns a populated Episode object.""" pu = ground_level_m latitude,...
the_stack_v2_python_sparse
csaf_f16/fgconverter.py
GaloisInc/csaf
train
11
3844f1743d91d1dde5f0db73e19da8caea6a9f89
[ "self._delta_t_minutes = delta_time_minutes\nself._t_fusion_mode = t_fusion_mode\nself._transition_matrices = transition_matrices\nself._all_transitions = build_flat_list_of_visits(transition_matrices)\nself._root_node = None", "for transition in self._all_transitions:\n baby_node = SpatialTimeModelNode.build_...
<|body_start_0|> self._delta_t_minutes = delta_time_minutes self._t_fusion_mode = t_fusion_mode self._transition_matrices = transition_matrices self._all_transitions = build_flat_list_of_visits(transition_matrices) self._root_node = None <|end_body_0|> <|body_start_1|> f...
SpatialTimeModelBuilder
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SpatialTimeModelBuilder: def __init__(self, transition_matrices: List[TransitionMatrix], delta_time_minutes, t_fusion_mode): """Basic constructor :param transition_matrices: The transition matrices representing all of the mobility data windows. :param delta_time_minutes: The time interva...
stack_v2_sparse_classes_10k_train_005272
5,379
permissive
[ { "docstring": "Basic constructor :param transition_matrices: The transition matrices representing all of the mobility data windows. :param delta_time_minutes: The time interval used for considering similarities of nodes during. :param t_fusion_mode: The time fusion mode to employ when consolidating different d...
6
stack_v2_sparse_classes_30k_train_007076
Implement the Python class `SpatialTimeModelBuilder` described below. Class description: Implement the SpatialTimeModelBuilder class. Method signatures and docstrings: - def __init__(self, transition_matrices: List[TransitionMatrix], delta_time_minutes, t_fusion_mode): Basic constructor :param transition_matrices: Th...
Implement the Python class `SpatialTimeModelBuilder` described below. Class description: Implement the SpatialTimeModelBuilder class. Method signatures and docstrings: - def __init__(self, transition_matrices: List[TransitionMatrix], delta_time_minutes, t_fusion_mode): Basic constructor :param transition_matrices: Th...
b058185ca028abd1902edbb35a52d3565b06f8b0
<|skeleton|> class SpatialTimeModelBuilder: def __init__(self, transition_matrices: List[TransitionMatrix], delta_time_minutes, t_fusion_mode): """Basic constructor :param transition_matrices: The transition matrices representing all of the mobility data windows. :param delta_time_minutes: The time interva...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SpatialTimeModelBuilder: def __init__(self, transition_matrices: List[TransitionMatrix], delta_time_minutes, t_fusion_mode): """Basic constructor :param transition_matrices: The transition matrices representing all of the mobility data windows. :param delta_time_minutes: The time interval used for con...
the_stack_v2_python_sparse
stm/SpatialTimeModelBuilder.py
s0lver/stm-creator
train
0
38603ef08b999a2ea644b28054d4b631ceac36f1
[ "rndstate = randstate(seed)\nrnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0]\nnbindings = rndstate.choice(self.nbindings)\nsize = rnd(self.size)\nbins = self.bins[1] * scale\nmaxv = min(self.bins[0] - bias, int(size / bins))\npos = np.empty(0, 'f4')\nwhile len(pos) != nbindings:\n pos = np.unique(rn...
<|body_start_0|> rndstate = randstate(seed) rnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0] nbindings = rndstate.choice(self.nbindings) size = rnd(self.size) bins = self.bins[1] * scale maxv = min(self.bins[0] - bias, int(size / bins)) pos = np.empty(...
Create random experiments & images
ExperimentCreator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ExperimentCreator: """Create random experiments & images""" def experiment(self, seed=None, bias=10, scale=2): """create an experiment""" <|body_0|> def createimage(self, info, bead): """transform bead data into an image""" <|body_1|> def createtruth...
stack_v2_sparse_classes_10k_train_005273
26,924
no_license
[ { "docstring": "create an experiment", "name": "experiment", "signature": "def experiment(self, seed=None, bias=10, scale=2)" }, { "docstring": "transform bead data into an image", "name": "createimage", "signature": "def createimage(self, info, bead)" }, { "docstring": "transfor...
4
stack_v2_sparse_classes_30k_train_001278
Implement the Python class `ExperimentCreator` described below. Class description: Create random experiments & images Method signatures and docstrings: - def experiment(self, seed=None, bias=10, scale=2): create an experiment - def createimage(self, info, bead): transform bead data into an image - def createtruth(sel...
Implement the Python class `ExperimentCreator` described below. Class description: Create random experiments & images Method signatures and docstrings: - def experiment(self, seed=None, bias=10, scale=2): create an experiment - def createimage(self, info, bead): transform bead data into an image - def createtruth(sel...
f9534e4fff9775ff45d08d401de61015d4a69e76
<|skeleton|> class ExperimentCreator: """Create random experiments & images""" def experiment(self, seed=None, bias=10, scale=2): """create an experiment""" <|body_0|> def createimage(self, info, bead): """transform bead data into an image""" <|body_1|> def createtruth...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ExperimentCreator: """Create random experiments & images""" def experiment(self, seed=None, bias=10, scale=2): """create an experiment""" rndstate = randstate(seed) rnd = lambda x, *y: rndstate.rand(*y) * (x[1] - x[0]) + x[0] nbindings = rndstate.choice(self.nbindings) ...
the_stack_v2_python_sparse
src/simulator/bindings.py
depixusgenome/trackanalysis
train
0
f72b942970e8d27d1939c7d400d412bad7831328
[ "for vals in vals_list:\n if vals.get('origin', False) and vals['origin'][0] == ':':\n vals.update({'origin': vals['origin'][1:]})\n if vals.get('origin', False) and vals['origin'][-1] == ':':\n vals.update({'origin': vals['origin'][:-1]})\n return super(StockPicking, self).create(vals)", "...
<|body_start_0|> for vals in vals_list: if vals.get('origin', False) and vals['origin'][0] == ':': vals.update({'origin': vals['origin'][1:]}) if vals.get('origin', False) and vals['origin'][-1] == ':': vals.update({'origin': vals['origin'][:-1]}) ...
Stock Picking.
StockPicking
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class StockPicking: """Stock Picking.""" def create(self, vals_list): """Overridden create method.""" <|body_0|> def write(self, vals): """Overridden write method.""" <|body_1|> <|end_skeleton|> <|body_start_0|> for vals in vals_list: if v...
stack_v2_sparse_classes_10k_train_005274
49,476
no_license
[ { "docstring": "Overridden create method.", "name": "create", "signature": "def create(self, vals_list)" }, { "docstring": "Overridden write method.", "name": "write", "signature": "def write(self, vals)" } ]
2
stack_v2_sparse_classes_30k_train_002913
Implement the Python class `StockPicking` described below. Class description: Stock Picking. Method signatures and docstrings: - def create(self, vals_list): Overridden create method. - def write(self, vals): Overridden write method.
Implement the Python class `StockPicking` described below. Class description: Stock Picking. Method signatures and docstrings: - def create(self, vals_list): Overridden create method. - def write(self, vals): Overridden write method. <|skeleton|> class StockPicking: """Stock Picking.""" def create(self, val...
7618a365ac78c0f59390a3a6b5fcdd9f76a5ddec
<|skeleton|> class StockPicking: """Stock Picking.""" def create(self, vals_list): """Overridden create method.""" <|body_0|> def write(self, vals): """Overridden write method.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class StockPicking: """Stock Picking.""" def create(self, vals_list): """Overridden create method.""" for vals in vals_list: if vals.get('origin', False) and vals['origin'][0] == ':': vals.update({'origin': vals['origin'][1:]}) if vals.get('origin', False...
the_stack_v2_python_sparse
fleet_operations/models/fleet_service.py
JayVora-SerpentCS/fleet_management
train
29
d73af10547f6b8d92a5debc38b9ffd2694363908
[ "news = response.xpath(\"//a[@target='_blank']\")\nfor new in news:\n item = CDagency()\n item['col_name'] = 'CD06dangxiao'\n href = new.xpath('./@href').extract_first()\n detail_url = 'https://www.cddx.gov.cn' + href\n item['detail_url'] = detail_url\n yield scrapy.Request(detail_url, callback=se...
<|body_start_0|> news = response.xpath("//a[@target='_blank']") for new in news: item = CDagency() item['col_name'] = 'CD06dangxiao' href = new.xpath('./@href').extract_first() detail_url = 'https://www.cddx.gov.cn' + href item['detail_url'] = ...
CdDangxiaoSpider
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CdDangxiaoSpider: def parse(self, response): """"默认的解析回调函数""" <|body_0|> def get_text(self, response): """获取详细的文本信息""" <|body_1|> <|end_skeleton|> <|body_start_0|> news = response.xpath("//a[@target='_blank']") for new in news: i...
stack_v2_sparse_classes_10k_train_005275
2,954
no_license
[ { "docstring": "\"默认的解析回调函数", "name": "parse", "signature": "def parse(self, response)" }, { "docstring": "获取详细的文本信息", "name": "get_text", "signature": "def get_text(self, response)" } ]
2
stack_v2_sparse_classes_30k_train_003771
Implement the Python class `CdDangxiaoSpider` described below. Class description: Implement the CdDangxiaoSpider class. Method signatures and docstrings: - def parse(self, response): "默认的解析回调函数 - def get_text(self, response): 获取详细的文本信息
Implement the Python class `CdDangxiaoSpider` described below. Class description: Implement the CdDangxiaoSpider class. Method signatures and docstrings: - def parse(self, response): "默认的解析回调函数 - def get_text(self, response): 获取详细的文本信息 <|skeleton|> class CdDangxiaoSpider: def parse(self, response): """"...
d2d66206d799afbfe68cafcc9bd7cd6d9533685d
<|skeleton|> class CdDangxiaoSpider: def parse(self, response): """"默认的解析回调函数""" <|body_0|> def get_text(self, response): """获取详细的文本信息""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CdDangxiaoSpider: def parse(self, response): """"默认的解析回调函数""" news = response.xpath("//a[@target='_blank']") for new in news: item = CDagency() item['col_name'] = 'CD06dangxiao' href = new.xpath('./@href').extract_first() detail_url = 'ht...
the_stack_v2_python_sparse
CDagency/spiders/cd06_dangxiao.py
gongdx/CDagency
train
0
81f0d921f6bda0dcc0fd4617ba98e08ac85130a3
[ "super(BasicAligner, self).__init__()\nself._extensions = [palign().extension]\nself._outext = palign().extension\nself._name = 'basic'", "if isinstance(input_wav, float) is True:\n duration = input_wav\nelse:\n try:\n wav_speech = sppas.src.audiodata.aio.open(input_wav)\n duration = wav_speec...
<|body_start_0|> super(BasicAligner, self).__init__() self._extensions = [palign().extension] self._outext = palign().extension self._name = 'basic' <|end_body_0|> <|body_start_1|> if isinstance(input_wav, float) is True: duration = input_wav else: ...
Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phoneme. In case of phonetic variants, the fir...
BasicAligner
[ "GFDL-1.1-or-later", "GPL-3.0-only", "GPL-3.0-or-later", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phonem...
stack_v2_sparse_classes_10k_train_005276
6,949
permissive
[ { "docstring": "Create a BasicAligner instance. This class allows to align one unit assigning the same duration to each phoneme. It selects the shortest sequence in case of variants. :param model_dir: (str) Ignored.", "name": "__init__", "signature": "def __init__(self, model_dir=None)" }, { "do...
5
null
Implement the Python class `BasicAligner` described below. Class description: Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation ...
Implement the Python class `BasicAligner` described below. Class description: Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation ...
3167b65f576abcc27a8767d24c274a04712bd948
<|skeleton|> class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phonem...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class BasicAligner: """Basic automatic alignment system. :author: Brigitte Bigi :organization: Laboratoire Parole et Langage, Aix-en-Provence, France :contact: develop@sppas.org :license: GPL, v3 :copyright: Copyright (C) 2011-2018 Brigitte Bigi This segmentation assign the same duration to each phoneme. In case of...
the_stack_v2_python_sparse
sppas/sppas/src/annotations/Align/aligners/basicalign.py
mirfan899/MTTS
train
0
019c9362a9d03118b14561e470d5de8aafeae4aa
[ "threading.Thread.__init__(self)\nself.direction = 'neutral'\nself.id = identity\nself.position = position\nself.move_joint(self.position, 900)", "while self.direction != '':\n if self.direction == 'decrease':\n if self.position > 200:\n self.position -= 15\n elif self.direction == 'increa...
<|body_start_0|> threading.Thread.__init__(self) self.direction = 'neutral' self.id = identity self.position = position self.move_joint(self.position, 900) <|end_body_0|> <|body_start_1|> while self.direction != '': if self.direction == 'decrease': ...
A Joint class representing a moving node on parts of the emubot
Joint
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Joint: """A Joint class representing a moving node on parts of the emubot""" def __init__(self, identity, position): """__init__(identity, position): parameters represent identification and position""" <|body_0|> def run(self): """Step through a sequence of moves...
stack_v2_sparse_classes_10k_train_005277
2,748
permissive
[ { "docstring": "__init__(identity, position): parameters represent identification and position", "name": "__init__", "signature": "def __init__(self, identity, position)" }, { "docstring": "Step through a sequence of moves", "name": "run", "signature": "def run(self)" }, { "docst...
3
stack_v2_sparse_classes_30k_train_000772
Implement the Python class `Joint` described below. Class description: A Joint class representing a moving node on parts of the emubot Method signatures and docstrings: - def __init__(self, identity, position): __init__(identity, position): parameters represent identification and position - def run(self): Step throug...
Implement the Python class `Joint` described below. Class description: A Joint class representing a moving node on parts of the emubot Method signatures and docstrings: - def __init__(self, identity, position): __init__(identity, position): parameters represent identification and position - def run(self): Step throug...
a39dc01f7c1213c8079216d49d376b317efbf5f3
<|skeleton|> class Joint: """A Joint class representing a moving node on parts of the emubot""" def __init__(self, identity, position): """__init__(identity, position): parameters represent identification and position""" <|body_0|> def run(self): """Step through a sequence of moves...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Joint: """A Joint class representing a moving node on parts of the emubot""" def __init__(self, identity, position): """__init__(identity, position): parameters represent identification and position""" threading.Thread.__init__(self) self.direction = 'neutral' self.id = id...
the_stack_v2_python_sparse
Client-Code-2018/CurrentEmuBotCode2/basic_classes.py
maxgodfrey2004/RoboCup-2018-Driving-Code
train
1
44635dea5130342b4c472cd00307d82ed1808b76
[ "if isinstance(value, dict):\n value = BytesIO(bytes(value.values()))\nmultipolygon = value\nif multipolygon is not None:\n try:\n zip_file = zipfile.ZipFile(value.temporary_file_path())\n except AttributeError:\n zip_file = zipfile.ZipFile(value)\n try:\n shpfile = get_shapefile(zi...
<|body_start_0|> if isinstance(value, dict): value = BytesIO(bytes(value.values())) multipolygon = value if multipolygon is not None: try: zip_file = zipfile.ZipFile(value.temporary_file_path()) except AttributeError: zip_file =...
Custom Field for Shapefile
ShapeFileField
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ShapeFileField: """Custom Field for Shapefile""" def to_internal_value(self, value): """Custom Conversion for shapefile field""" <|body_0|> def to_representation(self, value): """Custom conversion to representation for ShapeFileField""" <|body_1|> <|end_...
stack_v2_sparse_classes_10k_train_005278
6,527
permissive
[ { "docstring": "Custom Conversion for shapefile field", "name": "to_internal_value", "signature": "def to_internal_value(self, value)" }, { "docstring": "Custom conversion to representation for ShapeFileField", "name": "to_representation", "signature": "def to_representation(self, value)...
2
stack_v2_sparse_classes_30k_train_006106
Implement the Python class `ShapeFileField` described below. Class description: Custom Field for Shapefile Method signatures and docstrings: - def to_internal_value(self, value): Custom Conversion for shapefile field - def to_representation(self, value): Custom conversion to representation for ShapeFileField
Implement the Python class `ShapeFileField` described below. Class description: Custom Field for Shapefile Method signatures and docstrings: - def to_internal_value(self, value): Custom Conversion for shapefile field - def to_representation(self, value): Custom conversion to representation for ShapeFileField <|skele...
5faff50a2f3575f0df91a6b20afe37d43a592381
<|skeleton|> class ShapeFileField: """Custom Field for Shapefile""" def to_internal_value(self, value): """Custom Conversion for shapefile field""" <|body_0|> def to_representation(self, value): """Custom conversion to representation for ShapeFileField""" <|body_1|> <|end_...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ShapeFileField: """Custom Field for Shapefile""" def to_internal_value(self, value): """Custom Conversion for shapefile field""" if isinstance(value, dict): value = BytesIO(bytes(value.values())) multipolygon = value if multipolygon is not None: try...
the_stack_v2_python_sparse
tasking/serializers/location.py
onaio/tasking
train
6
44ce3adabec2f72deb48105623e1b45820cd7580
[ "self.VirtuosoObj = Virtuoso(netlist, wave_names)\nself.netlist = self.VirtuosoObj.netlist\nself.waves = self.VirtuosoObj.waves\npass", "self.assertIsInstance(self.netlist, str)\nself.assertIsInstance(self.waves, dict)\npass" ]
<|body_start_0|> self.VirtuosoObj = Virtuoso(netlist, wave_names) self.netlist = self.VirtuosoObj.netlist self.waves = self.VirtuosoObj.waves pass <|end_body_0|> <|body_start_1|> self.assertIsInstance(self.netlist, str) self.assertIsInstance(self.waves, dict) pas...
TestVirtuosoTypes
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TestVirtuosoTypes: def setUp(self): """Setup function TestTypes for class Virtuoso""" <|body_0|> def test_types(self): """Function to test data types for class Virtuoso""" <|body_1|> <|end_skeleton|> <|body_start_0|> self.VirtuosoObj = Virtuoso(netl...
stack_v2_sparse_classes_10k_train_005279
973
permissive
[ { "docstring": "Setup function TestTypes for class Virtuoso", "name": "setUp", "signature": "def setUp(self)" }, { "docstring": "Function to test data types for class Virtuoso", "name": "test_types", "signature": "def test_types(self)" } ]
2
stack_v2_sparse_classes_30k_train_006055
Implement the Python class `TestVirtuosoTypes` described below. Class description: Implement the TestVirtuosoTypes class. Method signatures and docstrings: - def setUp(self): Setup function TestTypes for class Virtuoso - def test_types(self): Function to test data types for class Virtuoso
Implement the Python class `TestVirtuosoTypes` described below. Class description: Implement the TestVirtuosoTypes class. Method signatures and docstrings: - def setUp(self): Setup function TestTypes for class Virtuoso - def test_types(self): Function to test data types for class Virtuoso <|skeleton|> class TestVirt...
825a0eab64be709efe161b9a48eb54c4bc5c1bef
<|skeleton|> class TestVirtuosoTypes: def setUp(self): """Setup function TestTypes for class Virtuoso""" <|body_0|> def test_types(self): """Function to test data types for class Virtuoso""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TestVirtuosoTypes: def setUp(self): """Setup function TestTypes for class Virtuoso""" self.VirtuosoObj = Virtuoso(netlist, wave_names) self.netlist = self.VirtuosoObj.netlist self.waves = self.VirtuosoObj.waves pass def test_types(self): """Function to test...
the_stack_v2_python_sparse
VLC_devel/class_structure/__auto_gen__/test_Virtuoso.py
wenh81/vlc_simulator
train
0
f8847d1c5a362efb57abaa7c0831d17b4d569a38
[ "self._reauth_entry = None\nself._email = None\nself._region = None", "errors = {}\nif user_input is not None:\n self._email = user_input[CONF_EMAIL]\n self._region = user_input[CONF_REGION]\n unique_id = user_input[CONF_EMAIL].lower()\n await self.async_set_unique_id(unique_id)\n if not self._reau...
<|body_start_0|> self._reauth_entry = None self._email = None self._region = None <|end_body_0|> <|body_start_1|> errors = {} if user_input is not None: self._email = user_input[CONF_EMAIL] self._region = user_input[CONF_REGION] unique_id = us...
Handle a config flow for Mazda Connected Services.
MazdaConfigFlow
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MazdaConfigFlow: """Handle a config flow for Mazda Connected Services.""" def __init__(self): """Start the mazda config flow.""" <|body_0|> async def async_step_user(self, user_input=None): """Handle the initial step.""" <|body_1|> async def async_st...
stack_v2_sparse_classes_10k_train_005280
3,926
permissive
[ { "docstring": "Start the mazda config flow.", "name": "__init__", "signature": "def __init__(self)" }, { "docstring": "Handle the initial step.", "name": "async_step_user", "signature": "async def async_step_user(self, user_input=None)" }, { "docstring": "Perform reauth if the u...
3
null
Implement the Python class `MazdaConfigFlow` described below. Class description: Handle a config flow for Mazda Connected Services. Method signatures and docstrings: - def __init__(self): Start the mazda config flow. - async def async_step_user(self, user_input=None): Handle the initial step. - async def async_step_r...
Implement the Python class `MazdaConfigFlow` described below. Class description: Handle a config flow for Mazda Connected Services. Method signatures and docstrings: - def __init__(self): Start the mazda config flow. - async def async_step_user(self, user_input=None): Handle the initial step. - async def async_step_r...
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
<|skeleton|> class MazdaConfigFlow: """Handle a config flow for Mazda Connected Services.""" def __init__(self): """Start the mazda config flow.""" <|body_0|> async def async_step_user(self, user_input=None): """Handle the initial step.""" <|body_1|> async def async_st...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MazdaConfigFlow: """Handle a config flow for Mazda Connected Services.""" def __init__(self): """Start the mazda config flow.""" self._reauth_entry = None self._email = None self._region = None async def async_step_user(self, user_input=None): """Handle the in...
the_stack_v2_python_sparse
homeassistant/components/mazda/config_flow.py
home-assistant/core
train
35,501
5bb7d761e08fd0c0af2d6a3bc672e97838a4f6e2
[ "total = 0\nfor counter in SimpleCounterShard.objects.all():\n total += counter.count\nreturn total", "index = random.randint(0, SimpleCounterShard.NUM_SHARDS - 1)\nshard_name = 'shard' + str(index)\ncounter = SimpleCounterShard.objects.get_or_create(pk=shard_name)[0]\ncounter.count += 1\ncounter.save()" ]
<|body_start_0|> total = 0 for counter in SimpleCounterShard.objects.all(): total += counter.count return total <|end_body_0|> <|body_start_1|> index = random.randint(0, SimpleCounterShard.NUM_SHARDS - 1) shard_name = 'shard' + str(index) counter = SimpleCoun...
Shards for the counter
SimpleCounterShard
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SimpleCounterShard: """Shards for the counter""" def get_count(cls): """Retrieve the value for a given sharded counter.""" <|body_0|> def increment(cls): """Increment the value for a given sharded counter.""" <|body_1|> <|end_skeleton|> <|body_start_0|>...
stack_v2_sparse_classes_10k_train_005281
4,135
no_license
[ { "docstring": "Retrieve the value for a given sharded counter.", "name": "get_count", "signature": "def get_count(cls)" }, { "docstring": "Increment the value for a given sharded counter.", "name": "increment", "signature": "def increment(cls)" } ]
2
stack_v2_sparse_classes_30k_val_000303
Implement the Python class `SimpleCounterShard` described below. Class description: Shards for the counter Method signatures and docstrings: - def get_count(cls): Retrieve the value for a given sharded counter. - def increment(cls): Increment the value for a given sharded counter.
Implement the Python class `SimpleCounterShard` described below. Class description: Shards for the counter Method signatures and docstrings: - def get_count(cls): Retrieve the value for a given sharded counter. - def increment(cls): Increment the value for a given sharded counter. <|skeleton|> class SimpleCounterSha...
2e3f1bdce124738e1bed2e648826ca819e0bcc57
<|skeleton|> class SimpleCounterShard: """Shards for the counter""" def get_count(cls): """Retrieve the value for a given sharded counter.""" <|body_0|> def increment(cls): """Increment the value for a given sharded counter.""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SimpleCounterShard: """Shards for the counter""" def get_count(cls): """Retrieve the value for a given sharded counter.""" total = 0 for counter in SimpleCounterShard.objects.all(): total += counter.count return total def increment(cls): """Increme...
the_stack_v2_python_sparse
sharded_counters/models.py
WAYbetter/waybetter
train
2
190e934f86f9696378d34ce76759b0e595837599
[ "while True:\n measurement = self.generate_message()\n measurement.save()\n print('Storing new measurement')\n time.sleep(10)", "meter = Meter.objects.get_or_create(name='4530303237303030303130313334353136')[0]\nmeasurement = Measurement()\nmeasurement.meter = meter\nmeasurement.power_usage_current = ...
<|body_start_0|> while True: measurement = self.generate_message() measurement.save() print('Storing new measurement') time.sleep(10) <|end_body_0|> <|body_start_1|> meter = Meter.objects.get_or_create(name='4530303237303030303130313334353136')[0] ...
"Class responsible for generating fake measurements just for development and debugging purposes
Generator
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Generator: """"Class responsible for generating fake measurements just for development and debugging purposes""" def start(self): """Starting the generator to create messages""" <|body_0|> def generate_message(self): """Genereates a new message""" <|body_...
stack_v2_sparse_classes_10k_train_005282
1,335
no_license
[ { "docstring": "Starting the generator to create messages", "name": "start", "signature": "def start(self)" }, { "docstring": "Genereates a new message", "name": "generate_message", "signature": "def generate_message(self)" } ]
2
stack_v2_sparse_classes_30k_train_004188
Implement the Python class `Generator` described below. Class description: "Class responsible for generating fake measurements just for development and debugging purposes Method signatures and docstrings: - def start(self): Starting the generator to create messages - def generate_message(self): Genereates a new messa...
Implement the Python class `Generator` described below. Class description: "Class responsible for generating fake measurements just for development and debugging purposes Method signatures and docstrings: - def start(self): Starting the generator to create messages - def generate_message(self): Genereates a new messa...
34f7c60d029b450e567150a8ed3714604a8504d0
<|skeleton|> class Generator: """"Class responsible for generating fake measurements just for development and debugging purposes""" def start(self): """Starting the generator to create messages""" <|body_0|> def generate_message(self): """Genereates a new message""" <|body_...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Generator: """"Class responsible for generating fake measurements just for development and debugging purposes""" def start(self): """Starting the generator to create messages""" while True: measurement = self.generate_message() measurement.save() print(...
the_stack_v2_python_sparse
src/processor/generator.py
maarten-kieft/ASMP
train
5
cdffdb6d8daa7dfcd99d078c0525ce41aeb678ac
[ "playlist_model = Playlist.get_by_id(int(playlist_id))\njson = []\nfor key in playlist_model.followers:\n youtify_user_model = db.get(key)\n json.append(get_youtify_user_struct(youtify_user_model))\nself.response.headers['Content-Type'] = 'application/json'\nself.response.out.write(simplejson.dumps(json))", ...
<|body_start_0|> playlist_model = Playlist.get_by_id(int(playlist_id)) json = [] for key in playlist_model.followers: youtify_user_model = db.get(key) json.append(get_youtify_user_struct(youtify_user_model)) self.response.headers['Content-Type'] = 'application/jso...
PlaylistFollowersHandler
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class PlaylistFollowersHandler: def get(self, playlist_id): """Gets the list of users that follow a playlist""" <|body_0|> def post(self, playlist_id): """Follows a playlist""" <|body_1|> def delete(self, playlist_id): """Unfollows a playlist""" ...
stack_v2_sparse_classes_10k_train_005283
6,976
permissive
[ { "docstring": "Gets the list of users that follow a playlist", "name": "get", "signature": "def get(self, playlist_id)" }, { "docstring": "Follows a playlist", "name": "post", "signature": "def post(self, playlist_id)" }, { "docstring": "Unfollows a playlist", "name": "delet...
3
stack_v2_sparse_classes_30k_val_000364
Implement the Python class `PlaylistFollowersHandler` described below. Class description: Implement the PlaylistFollowersHandler class. Method signatures and docstrings: - def get(self, playlist_id): Gets the list of users that follow a playlist - def post(self, playlist_id): Follows a playlist - def delete(self, pla...
Implement the Python class `PlaylistFollowersHandler` described below. Class description: Implement the PlaylistFollowersHandler class. Method signatures and docstrings: - def get(self, playlist_id): Gets the list of users that follow a playlist - def post(self, playlist_id): Follows a playlist - def delete(self, pla...
1855f242f15a9a66a8868ced849ddd77385426e7
<|skeleton|> class PlaylistFollowersHandler: def get(self, playlist_id): """Gets the list of users that follow a playlist""" <|body_0|> def post(self, playlist_id): """Follows a playlist""" <|body_1|> def delete(self, playlist_id): """Unfollows a playlist""" ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class PlaylistFollowersHandler: def get(self, playlist_id): """Gets the list of users that follow a playlist""" playlist_model = Playlist.get_by_id(int(playlist_id)) json = [] for key in playlist_model.followers: youtify_user_model = db.get(key) json.append(ge...
the_stack_v2_python_sparse
playlists.py
blen2r/youtify
train
0
1b5caaf8edd93e3f28dbdee27db9e5d5714030ca
[ "super().__init__()\nself.dense_feature_extractor = dense_feature_extractor\nself.seg_classifier = seg_classifier\nself.changemixin = changemixin\nif inference_mode not in ['t1t2', 't2t1', 'mean']:\n raise ValueError(f'Unknown inference_mode: {inference_mode}')\nself.inference_mode = inference_mode", "b, t, c,...
<|body_start_0|> super().__init__() self.dense_feature_extractor = dense_feature_extractor self.seg_classifier = seg_classifier self.changemixin = changemixin if inference_mode not in ['t1t2', 't2t1', 'mean']: raise ValueError(f'Unknown inference_mode: {inference_mode...
The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the property of segmentation architecture re...
ChangeStar
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class ChangeStar: """The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the pr...
stack_v2_sparse_classes_10k_train_005284
7,715
permissive
[ { "docstring": "Initializes a new ChangeStar model. Args: dense_feature_extractor: module for dense feature extraction, typically a semantic segmentation model without semantic segmentation head. seg_classifier: semantic segmentation head, typically a convolutional layer followed by an upsampling layer. changem...
2
stack_v2_sparse_classes_30k_train_005989
Implement the Python class `ChangeStar` described below. Class description: The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-t...
Implement the Python class `ChangeStar` described below. Class description: The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-t...
29985861614b3b93f9ef5389469ebb98570de7dd
<|skeleton|> class ChangeStar: """The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the pr...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class ChangeStar: """The base class of the network architecture of ChangeStar. ChangeStar is composed of an any segmentation model and a ChangeMixin module. This model is mainly used for binary/multi-class change detection under bitemporal supervision and single-temporal supervision. It features the property of seg...
the_stack_v2_python_sparse
torchgeo/models/changestar.py
microsoft/torchgeo
train
1,724
9b42a9cdebe9c8d70d467c6afe09e9f31d74560e
[ "self.continue_on_error = continue_on_error\nself.file_recovery_method = file_recovery_method\nself.filenames = filenames\nself.filter_ip_config = filter_ip_config\nself.is_file_based_volume_restore = is_file_based_volume_restore\nself.mount_disks_on_vm = mount_disks_on_vm\nself.name = name\nself.new_base_directory...
<|body_start_0|> self.continue_on_error = continue_on_error self.file_recovery_method = file_recovery_method self.filenames = filenames self.filter_ip_config = filter_ip_config self.is_file_based_volume_restore = is_file_based_volume_restore self.mount_disks_on_vm = mount...
Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders fails. If true, the Cohesity Cluster ignores intermi...
RestoreFilesTaskRequest
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders f...
stack_v2_sparse_classes_10k_train_005285
10,417
permissive
[ { "docstring": "Constructor for the RestoreFilesTaskRequest class", "name": "__init__", "signature": "def __init__(self, continue_on_error=None, file_recovery_method=None, filenames=None, filter_ip_config=None, is_file_based_volume_restore=None, mount_disks_on_vm=None, name=None, new_base_directory=None...
2
stack_v2_sparse_classes_30k_train_000177
Implement the Python class `RestoreFilesTaskRequest` described below. Class description: Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the cop...
Implement the Python class `RestoreFilesTaskRequest` described below. Class description: Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the cop...
e4973dfeb836266904d0369ea845513c7acf261e
<|skeleton|> class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders f...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RestoreFilesTaskRequest: """Implementation of the 'RestoreFilesTaskRequest' model. Specifies information about a Restore Task that recovers files and folders. Attributes: continue_on_error (bool): Specifies if the Restore Task should continue even if the copy operation of some files and folders fails. If true...
the_stack_v2_python_sparse
cohesity_management_sdk/models/restore_files_task_request.py
cohesity/management-sdk-python
train
24
6635b58e3e193db9c876f0c944948c37beeaaaef
[ "import bisect\na = sorted(A)\nresult = []\nfor b in B:\n p = bisect.bisect(a, b)\n if p < len(a):\n result.append(a[p])\n a.pop(p)\n else:\n result.append(a[0])\n a.pop(0)\nreturn result", "l = len(A)\nres = [0] * l\nidx = range(l)\nidx.sort(key=lambda x: B[x])\nA.sort()\nlef...
<|body_start_0|> import bisect a = sorted(A) result = [] for b in B: p = bisect.bisect(a, b) if p < len(a): result.append(a[p]) a.pop(p) else: result.append(a[0]) a.pop(0) return r...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" <|body_0|> def advantageCount_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 220ms""" <|body_1|> <|end_skeleton|> <|bod...
stack_v2_sparse_classes_10k_train_005286
1,670
no_license
[ { "docstring": ":type A: List[int] :type B: List[int] :rtype: List[int] 316 ms", "name": "advantageCount", "signature": "def advantageCount(self, A, B)" }, { "docstring": ":type A: List[int] :type B: List[int] :rtype: List[int] 220ms", "name": "advantageCount_1", "signature": "def advant...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def advantageCount(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int] 316 ms - def advantageCount_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: L...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def advantageCount(self, A, B): :type A: List[int] :type B: List[int] :rtype: List[int] 316 ms - def advantageCount_1(self, A, B): :type A: List[int] :type B: List[int] :rtype: L...
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
<|skeleton|> class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" <|body_0|> def advantageCount_1(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 220ms""" <|body_1|> <|end_skeleton|>
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def advantageCount(self, A, B): """:type A: List[int] :type B: List[int] :rtype: List[int] 316 ms""" import bisect a = sorted(A) result = [] for b in B: p = bisect.bisect(a, b) if p < len(a): result.append(a[p]) ...
the_stack_v2_python_sparse
AdvantageShuffle_MID_870.py
953250587/leetcode-python
train
2
a37c02a80373a12f9bf9c3db57155b7b974f2f49
[ "super().__init__(name)\nself.model = model\nself.alphabet = alphabet", "one_hots = np.array([s_utils.string_to_one_hot(seq, self.alphabet) for seq in sequences])\nflattened = one_hots.reshape(one_hots.shape[0], one_hots.shape[1] * one_hots.shape[2])\nself.model.fit(flattened, labels)" ]
<|body_start_0|> super().__init__(name) self.model = model self.alphabet = alphabet <|end_body_0|> <|body_start_1|> one_hots = np.array([s_utils.string_to_one_hot(seq, self.alphabet) for seq in sequences]) flattened = one_hots.reshape(one_hots.shape[0], one_hots.shape[1] * one_h...
Base sklearn model wrapper.
SklearnModel
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" <|body_0|> def train(self, sequences, labels): ...
stack_v2_sparse_classes_10k_train_005287
2,860
permissive
[ { "docstring": "Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).", "name": "__init__", "signature": "def __init__(self, model, alphabet, name)" }, { "docstring": "Flatten one-hot sequences and train model using `model.fit...
2
stack_v2_sparse_classes_30k_train_001759
Implement the Python class `SklearnModel` described below. Class description: Base sklearn model wrapper. Method signatures and docstrings: - def __init__(self, model, alphabet, name): Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging). - def tra...
Implement the Python class `SklearnModel` described below. Class description: Base sklearn model wrapper. Method signatures and docstrings: - def __init__(self, model, alphabet, name): Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging). - def tra...
744e792456d93e8c48fc58220689c0b4cff6ded9
<|skeleton|> class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" <|body_0|> def train(self, sequences, labels): ...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SklearnModel: """Base sklearn model wrapper.""" def __init__(self, model, alphabet, name): """Args: model: sklearn model to wrap. alphabet: Alphabet string. name: Human-readable short model descriptipon (for logging).""" super().__init__(name) self.model = model self.alpha...
the_stack_v2_python_sparse
flexs/baselines/models/sklearn_models.py
jonshao/FLEXS
train
0
80f395b024f362925ada43334b415ffb18d71c11
[ "command_name = command_node.get('CommandName')\ncommand_id = command_node.get('CommandId')\ncommand_params = defaultdict(list)\nnamespace = XMLHelper.get_node_namespace(command_node)\nparameters_node = command_node.find(namespace + 'Parameters')\nif parameters_node is not None:\n for param_node in parameters_no...
<|body_start_0|> command_name = command_node.get('CommandName') command_id = command_node.get('CommandId') command_params = defaultdict(list) namespace = XMLHelper.get_node_namespace(command_node) parameters_node = command_node.find(namespace + 'Parameters') if parameters...
Parse request data and build command requests.
RequestsParser
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" <|body_0|> def parse_request_commands(xml_request: str) -> list: """Parse xml...
stack_v2_sparse_classes_10k_train_005288
1,428
no_license
[ { "docstring": "Build command instance for command node.", "name": "_build_command_instance", "signature": "def _build_command_instance(command_node: Element) -> CommandRequest" }, { "docstring": "Parse xml request and create command instances.", "name": "parse_request_commands", "signat...
2
stack_v2_sparse_classes_30k_train_001817
Implement the Python class `RequestsParser` described below. Class description: Parse request data and build command requests. Method signatures and docstrings: - def _build_command_instance(command_node: Element) -> CommandRequest: Build command instance for command node. - def parse_request_commands(xml_request: st...
Implement the Python class `RequestsParser` described below. Class description: Parse request data and build command requests. Method signatures and docstrings: - def _build_command_instance(command_node: Element) -> CommandRequest: Build command instance for command node. - def parse_request_commands(xml_request: st...
82562665834908294136bbe8e7bc46da1a21b8e2
<|skeleton|> class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" <|body_0|> def parse_request_commands(xml_request: str) -> list: """Parse xml...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RequestsParser: """Parse request data and build command requests.""" def _build_command_instance(command_node: Element) -> CommandRequest: """Build command instance for command node.""" command_name = command_node.get('CommandName') command_id = command_node.get('CommandId') ...
the_stack_v2_python_sparse
cloudshell/layer_one/core/request/requests_parser.py
QualiSystems/cloudshell-L1-networking-core
train
1
e251d622490df247303aaa275371321013e0363f
[ "n1, n2 = (len(self), len(other))\nv1, v2 = (self._data.var(), other._data.var())\nx1, x2 = (self._data.mean(), other._data.mean())\ns = (((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)) ** 0.5\nreturn (x1 - x2) / s", "dists: Dict[str, DCDM] = {category: self.filter_to(categorical.keep(category)).rename(category)...
<|body_start_0|> n1, n2 = (len(self), len(other)) v1, v2 = (self._data.var(), other._data.var()) x1, x2 = (self._data.mean(), other._data.mean()) s = (((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)) ** 0.5 return (x1 - x2) / s <|end_body_0|> <|body_start_1|> dists: Dict...
DataCohensDMixin
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class DataCohensDMixin: def cohens_d(self: DCDM, other: DCDM) -> float: """Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d""" <|body_0|> def conditional_cohens_d(self: DCDM, categorical: DataCateg...
stack_v2_sparse_classes_10k_train_005289
2,575
permissive
[ { "docstring": "Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d", "name": "cohens_d", "signature": "def cohens_d(self: DCDM, other: DCDM) -> float" }, { "docstring": "Return a matrix of the Cohen's d of the Rati...
2
stack_v2_sparse_classes_30k_train_002460
Implement the Python class `DataCohensDMixin` described below. Class description: Implement the DataCohensDMixin class. Method signatures and docstrings: - def cohens_d(self: DCDM, other: DCDM) -> float: Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Eff...
Implement the Python class `DataCohensDMixin` described below. Class description: Implement the DataCohensDMixin class. Method signatures and docstrings: - def cohens_d(self: DCDM, other: DCDM) -> float: Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Eff...
ff3f5434d3da0d46b127b02cf733699e5a43c904
<|skeleton|> class DataCohensDMixin: def cohens_d(self: DCDM, other: DCDM) -> float: """Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d""" <|body_0|> def conditional_cohens_d(self: DCDM, categorical: DataCateg...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class DataCohensDMixin: def cohens_d(self: DCDM, other: DCDM) -> float: """Calculate the Cohen's d standardized difference of means between self and other. https://en.wikipedia.org/wiki/Effect_size#Cohen's_d""" n1, n2 = (len(self), len(other)) v1, v2 = (self._data.var(), other._data.var()) ...
the_stack_v2_python_sparse
probability/distributions/mixins/data/data_comparison_mixins.py
vahndi/probability
train
3
e0c26bfdb27fee2eb9eb2b33840c0005e36987d1
[ "self.batched_inputs = inputs\nproposals_boxes = proposals[PD_BOXES]\nif self.is_training:\n proposals = self.label_and_sample_proposals(inputs, proposals_boxes)\nfeatures_list = [features[f] for f in self.in_features]\nimg_size = get_img_size_from_batched_inputs(inputs)\nif self.is_training:\n pred_instances...
<|body_start_0|> self.batched_inputs = inputs proposals_boxes = proposals[PD_BOXES] if self.is_training: proposals = self.label_and_sample_proposals(inputs, proposals_boxes) features_list = [features[f] for f in self.in_features] img_size = get_img_size_from_batched_i...
RepeatableROIHeads
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class RepeatableROIHeads: def forward(self, inputs, features, proposals: ProposalsData): """See :class:`ROIHeads.forward`.""" <|body_0|> def forward_with_given_boxes(self, inputs, features, instances, img_size): """Use the given boxes in `instances` to produce other (non-b...
stack_v2_sparse_classes_10k_train_005290
6,801
permissive
[ { "docstring": "See :class:`ROIHeads.forward`.", "name": "forward", "signature": "def forward(self, inputs, features, proposals: ProposalsData)" }, { "docstring": "Use the given boxes in `instances` to produce other (non-box) per-ROI outputs. This is useful for downstream tasks where a box is kn...
3
null
Implement the Python class `RepeatableROIHeads` described below. Class description: Implement the RepeatableROIHeads class. Method signatures and docstrings: - def forward(self, inputs, features, proposals: ProposalsData): See :class:`ROIHeads.forward`. - def forward_with_given_boxes(self, inputs, features, instances...
Implement the Python class `RepeatableROIHeads` described below. Class description: Implement the RepeatableROIHeads class. Method signatures and docstrings: - def forward(self, inputs, features, proposals: ProposalsData): See :class:`ROIHeads.forward`. - def forward_with_given_boxes(self, inputs, features, instances...
8fbf060088816cd1a366d7cbd5dfe1a0e00f8d79
<|skeleton|> class RepeatableROIHeads: def forward(self, inputs, features, proposals: ProposalsData): """See :class:`ROIHeads.forward`.""" <|body_0|> def forward_with_given_boxes(self, inputs, features, instances, img_size): """Use the given boxes in `instances` to produce other (non-b...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class RepeatableROIHeads: def forward(self, inputs, features, proposals: ProposalsData): """See :class:`ROIHeads.forward`.""" self.batched_inputs = inputs proposals_boxes = proposals[PD_BOXES] if self.is_training: proposals = self.label_and_sample_proposals(inputs, propos...
the_stack_v2_python_sparse
object_detection2/modeling/roi_heads/repeatable_roi_heads.py
seantangtao/wml
train
0
cc75f4d7e6e06f88bf84376aed119aee8edd272d
[ "files = self._get_filesfixedforvulnerability()\nids = self._get_missedvulnerabilityreviewids(files)\nReview.objects.filter(id__in=ids).update(missed_vulnerability=True)\nreturn len(ids)", "reviews = set()\nfor vulnerability in Vulnerability.objects.all():\n for bug in vulnerability.bugs.all():\n for re...
<|body_start_0|> files = self._get_filesfixedforvulnerability() ids = self._get_missedvulnerabilityreviewids(files) Review.objects.filter(id__in=ids).update(missed_vulnerability=True) return len(ids) <|end_body_0|> <|body_start_1|> reviews = set() for vulnerability in Vu...
Implements tagger object.
MissedVulnerabilityTagger
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class MissedVulnerabilityTagger: """Implements tagger object.""" def _tag(self): """Tag all of the reviews that missed a vulnerability.""" <|body_0|> def _get_vulnerabilityfixingreviews(self): """Returns a list of reviews that fixed a vulnerability.""" <|body_1...
stack_v2_sparse_classes_10k_train_005291
2,297
no_license
[ { "docstring": "Tag all of the reviews that missed a vulnerability.", "name": "_tag", "signature": "def _tag(self)" }, { "docstring": "Returns a list of reviews that fixed a vulnerability.", "name": "_get_vulnerabilityfixingreviews", "signature": "def _get_vulnerabilityfixingreviews(self...
5
stack_v2_sparse_classes_30k_test_000199
Implement the Python class `MissedVulnerabilityTagger` described below. Class description: Implements tagger object. Method signatures and docstrings: - def _tag(self): Tag all of the reviews that missed a vulnerability. - def _get_vulnerabilityfixingreviews(self): Returns a list of reviews that fixed a vulnerability...
Implement the Python class `MissedVulnerabilityTagger` described below. Class description: Implements tagger object. Method signatures and docstrings: - def _tag(self): Tag all of the reviews that missed a vulnerability. - def _get_vulnerabilityfixingreviews(self): Returns a list of reviews that fixed a vulnerability...
b027a5d7407043b6541e2aa02704a7239f109485
<|skeleton|> class MissedVulnerabilityTagger: """Implements tagger object.""" def _tag(self): """Tag all of the reviews that missed a vulnerability.""" <|body_0|> def _get_vulnerabilityfixingreviews(self): """Returns a list of reviews that fixed a vulnerability.""" <|body_1...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class MissedVulnerabilityTagger: """Implements tagger object.""" def _tag(self): """Tag all of the reviews that missed a vulnerability.""" files = self._get_filesfixedforvulnerability() ids = self._get_missedvulnerabilityreviewids(files) Review.objects.filter(id__in=ids).update(...
the_stack_v2_python_sparse
app/lib/taggers/missedvulnerability.py
andymeneely/sira-nlp
train
1
e4aac5a626b90c096618d91e89663a6019c9bc4c
[ "if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SecurityResource()", "from .security_resource_type import SecurityResourceType\nfrom .security_resource_type import SecurityResourceType\nfields: Dict[str, Callable[[Any], None]] = {'@odata.type': lambda n: setattr(self, 'odata_type', ...
<|body_start_0|> if not parse_node: raise TypeError('parse_node cannot be null.') return SecurityResource() <|end_body_0|> <|body_start_1|> from .security_resource_type import SecurityResourceType from .security_resource_type import SecurityResourceType fields: Dict[...
SecurityResource
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """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 R...
stack_v2_sparse_classes_10k_train_005292
3,039
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: SecurityResource", "name": "create_from_discriminator_value", "signature": "def create_from_discriminator_va...
3
stack_v2_sparse_classes_30k_val_000317
Implement the Python class `SecurityResource` described below. Class description: Implement the SecurityResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: Creates a new instance of the appropriate class based on discrimina...
Implement the Python class `SecurityResource` described below. Class description: Implement the SecurityResource class. Method signatures and docstrings: - def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: Creates a new instance of the appropriate class based on discrimina...
27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949
<|skeleton|> class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """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 R...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class SecurityResource: def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SecurityResource: """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: Securi...
the_stack_v2_python_sparse
msgraph/generated/models/security_resource.py
microsoftgraph/msgraph-sdk-python
train
135
a3787bdaf667f3b1b2bb9707a64752739d6307af
[ "dict = {}\nfor i in strs:\n sort_s = ''.join((lambda x: (x.sort(), x)[1])(list(i)))\n if not dict:\n dict[sort_s] = [i]\n elif sort_s in dict.keys():\n dict[sort_s].append(i)\n else:\n dict[sort_s] = [i]\nreturn dict.values()", "result_dict = collections.defaultdict(list)\nfor s ...
<|body_start_0|> dict = {} for i in strs: sort_s = ''.join((lambda x: (x.sort(), x)[1])(list(i))) if not dict: dict[sort_s] = [i] elif sort_s in dict.keys(): dict[sort_s].append(i) else: dict[sort_s] = [i] ...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def groupAnagrams0(self, strs): """:type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串""" <|body_0|> def groupAnagrams1(self, strs): """使用python的collections模块实现, 简化代码 思路与groupAnagrams0 相同""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_10k_train_005293
2,115
permissive
[ { "docstring": ":type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串", "name": "groupAnagrams0", "signature": "def groupAnagrams0(self, strs)" }, { "docstring": "使用python的collections模块实现, 简化代码 思路与groupAnagrams0 相同", "name": "groupAnagrams1", "signature"...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams0(self, strs): :type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串 - def groupAnagrams1(self, strs): 使用python的collections模块实现...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def groupAnagrams0(self, strs): :type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串 - def groupAnagrams1(self, strs): 使用python的collections模块实现...
60e9ef1051a1d0441ab1c5484a51ab77a306bf5b
<|skeleton|> class Solution: def groupAnagrams0(self, strs): """:type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串""" <|body_0|> def groupAnagrams1(self, strs): """使用python的collections模块实现, 简化代码 思路与groupAnagrams0 相同""" <|body_1|> <|end_skel...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def groupAnagrams0(self, strs): """:type strs: List[str] :rtype: List[List[str]] 解题思路: 定义一个字典: key为字符串排序后的字符串; value为原始字符串""" dict = {} for i in strs: sort_s = ''.join((lambda x: (x.sort(), x)[1])(list(i))) if not dict: dict[sort_s] = [...
the_stack_v2_python_sparse
Week 2/id_710/LeetCode_49_710.py
chenlei65368/algorithm004-05
train
1
635c6cf359ae76df657825622c906038cf48c194
[ "if self.field:\n return f'Top results for \"{self.field:s}\"'\nreturn 'Top results for an unknown field'", "self.field = field\nformatted_field_name = self.format_field_by_type(field)\nencoding = {'x': {'field': field, 'type': 'nominal', 'sort': {'op': 'sum', 'field': order_field, 'order': 'descending'}}, 'y'...
<|body_start_0|> if self.field: return f'Top results for "{self.field:s}"' return 'Top results for an unknown field' <|end_body_0|> <|body_start_1|> self.field = field formatted_field_name = self.format_field_by_type(field) encoding = {'x': {'field': field, 'type': '...
Terms Bucket Aggregation.
TermsAggregation
[ "Apache-2.0" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class TermsAggregation: """Terms Bucket Aggregation.""" def chart_title(self): """Returns a title for the chart.""" <|body_0|> def run(self, field, limit=10, supported_charts='table', start_time='', end_time='', order_field='count'): """Run the aggregation. Args: field...
stack_v2_sparse_classes_10k_train_005294
5,187
permissive
[ { "docstring": "Returns a title for the chart.", "name": "chart_title", "signature": "def chart_title(self)" }, { "docstring": "Run the aggregation. Args: field: What field to aggregate on. limit: How many buckets to return. supported_charts: Chart type to render. Defaults to table. start_time: ...
2
null
Implement the Python class `TermsAggregation` described below. Class description: Terms Bucket Aggregation. Method signatures and docstrings: - def chart_title(self): Returns a title for the chart. - def run(self, field, limit=10, supported_charts='table', start_time='', end_time='', order_field='count'): Run the agg...
Implement the Python class `TermsAggregation` described below. Class description: Terms Bucket Aggregation. Method signatures and docstrings: - def chart_title(self): Returns a title for the chart. - def run(self, field, limit=10, supported_charts='table', start_time='', end_time='', order_field='count'): Run the agg...
24f471b58ca4a87cb053961b5f05c07a544ca7b8
<|skeleton|> class TermsAggregation: """Terms Bucket Aggregation.""" def chart_title(self): """Returns a title for the chart.""" <|body_0|> def run(self, field, limit=10, supported_charts='table', start_time='', end_time='', order_field='count'): """Run the aggregation. Args: field...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class TermsAggregation: """Terms Bucket Aggregation.""" def chart_title(self): """Returns a title for the chart.""" if self.field: return f'Top results for "{self.field:s}"' return 'Top results for an unknown field' def run(self, field, limit=10, supported_charts='table...
the_stack_v2_python_sparse
timesketch/lib/aggregators/bucket.py
google/timesketch
train
2,263
79c6fd96ee3fa40e17e393494783294e2869252f
[ "for name, working_partitions in cls.data_source.working_partitions.items():\n try:\n partition = partitions[name]\n except KeyError:\n raise ValueError(f\"{cls.__name__} is missing required '{name}' field.\")\n if not partitions[name]:\n partition = working_partitions\n partitions_...
<|body_start_0|> for name, working_partitions in cls.data_source.working_partitions.items(): try: partition = partitions[name] except KeyError: raise ValueError(f"{cls.__name__} is missing required '{name}' field.") if not partitions[name]: ...
An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset.
GenericDatasetSettings
[ "CC-BY-4.0", "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class GenericDatasetSettings: """An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset.""" def validate_partitions(cls, partitions): """Valid...
stack_v2_sparse_classes_10k_train_005295
24,804
permissive
[ { "docstring": "Validate the requested data partitions. Check that all the partitions defined in the ``working_partitions`` of the associated ``data_source`` (e.g. years or states) have been assigned in the definition of the class, and that the requested values are a subset of the allowable values defined by th...
2
stack_v2_sparse_classes_30k_train_004880
Implement the Python class `GenericDatasetSettings` described below. Class description: An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset. Method signatures and docs...
Implement the Python class `GenericDatasetSettings` described below. Class description: An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset. Method signatures and docs...
6afae8aade053408f23ac4332d5cbb438ab72dc6
<|skeleton|> class GenericDatasetSettings: """An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset.""" def validate_partitions(cls, partitions): """Valid...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class GenericDatasetSettings: """An abstract pydantic model for generic datasets. Each dataset must specify working partitions. A dataset can have an arbitrary number of partitions. Args: disabled: if true, skip processing this dataset.""" def validate_partitions(cls, partitions): """Validate the reque...
the_stack_v2_python_sparse
src/pudl/settings.py
catalyst-cooperative/pudl
train
382
06054eac6355f83806d5f06d5a5287a5724efae8
[ "if not heights:\n return 0\nstack = []\nmax_area, index = (0, 0)\nlength = len(heights)\nwhile index <= length:\n if not stack or (index < length and heights[index] >= heights[stack[-1]]):\n stack.append(index)\n index += 1\n else:\n old_index = stack.pop()\n width = index if l...
<|body_start_0|> if not heights: return 0 stack = [] max_area, index = (0, 0) length = len(heights) while index <= length: if not stack or (index < length and heights[index] >= heights[stack[-1]]): stack.append(index) index ...
Solution
[ "MIT" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def largest_rectangle_histogram(self, heights: List[int]) -> int: """计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积""" <|body_0|> def largest_rectangle_histogram2(self, heights: List[int]) -> int: """计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积""" <|b...
stack_v2_sparse_classes_10k_train_005296
2,962
permissive
[ { "docstring": "计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积", "name": "largest_rectangle_histogram", "signature": "def largest_rectangle_histogram(self, heights: List[int]) -> int" }, { "docstring": "计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积", "name": "largest_rectangle_histogram2", ...
2
stack_v2_sparse_classes_30k_train_005975
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largest_rectangle_histogram(self, heights: List[int]) -> int: 计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积 - def largest_rectangle_histogram2(self, heights: List[int]) -> int...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def largest_rectangle_histogram(self, heights: List[int]) -> int: 计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积 - def largest_rectangle_histogram2(self, heights: List[int]) -> int...
50f35eef6a0ad63173efed10df3c835b1dceaa3f
<|skeleton|> class Solution: def largest_rectangle_histogram(self, heights: List[int]) -> int: """计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积""" <|body_0|> def largest_rectangle_histogram2(self, heights: List[int]) -> int: """计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积""" <|b...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def largest_rectangle_histogram(self, heights: List[int]) -> int: """计算最大矩形长度 Args: heights: 数组长度 Returns: 矩形最大面积""" if not heights: return 0 stack = [] max_area, index = (0, 0) length = len(heights) while index <= length: if no...
the_stack_v2_python_sparse
src/leetcodepython/array/largest_rectangle_histogram_84.py
zhangyu345293721/leetcode
train
101
ebfe3525b7dd4f9ec0f5ee73aa2f050d288677ca
[ "assert all((len(c) == 2 and isinstance(c[0], str) and isinstance(c[1], int) for c in columns)), columns\nself.use_cr_only = True\nself.unfinished_commands = set()\nself.start = time.time()\nself._last_printed_line = ''\nself._columns = [c[1] for c in columns]\nself._columns_lookup = dict(((c[0], i) for i, c in enu...
<|body_start_0|> assert all((len(c) == 2 and isinstance(c[0], str) and isinstance(c[1], int) for c in columns)), columns self.use_cr_only = True self.unfinished_commands = set() self.start = time.time() self._last_printed_line = '' self._columns = [c[1] for c in columns] ...
Prints progress and accepts updates thread-safely.
Progress
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Progress: """Prints progress and accepts updates thread-safely.""" def __init__(self, columns): """Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initialvalue), defines both the number of columns and their init...
stack_v2_sparse_classes_10k_train_005297
27,770
permissive
[ { "docstring": "Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initialvalue), defines both the number of columns and their initial values.", "name": "__init__", "signature": "def __init__(self, columns)" }, { "docstring": ...
5
null
Implement the Python class `Progress` described below. Class description: Prints progress and accepts updates thread-safely. Method signatures and docstrings: - def __init__(self, columns): Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initial...
Implement the Python class `Progress` described below. Class description: Prints progress and accepts updates thread-safely. Method signatures and docstrings: - def __init__(self, columns): Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initial...
10cc5fdcca53e2a1690867acbe6fce099273f092
<|skeleton|> class Progress: """Prints progress and accepts updates thread-safely.""" def __init__(self, columns): """Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initialvalue), defines both the number of columns and their init...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Progress: """Prints progress and accepts updates thread-safely.""" def __init__(self, columns): """Creates a Progress bar that will updates asynchronously from the worker threads. Arguments: columns: list of tuple(name, initialvalue), defines both the number of columns and their initial values.""...
the_stack_v2_python_sparse
client/utils/threading_utils.py
luci/luci-py
train
84
cb5800570c14ff3897a8a6e66f3b9a5e44c616cb
[ "N = len(nums)\ns, l, ans = (sum(nums), 1, float('inf'))\nnums.insert(0, 0)\nfor r in range(N + 1):\n s -= nums[r]\n while l < r and s < x:\n s += nums[l]\n l += 1\n if s == x:\n ans = min(ans, l - 1 + N - r)\nreturn ans if ans != float('inf') else -1", "N = len(nums)\nd = {0: -1}\ns...
<|body_start_0|> N = len(nums) s, l, ans = (sum(nums), 1, float('inf')) nums.insert(0, 0) for r in range(N + 1): s -= nums[r] while l < r and s < x: s += nums[l] l += 1 if s == x: ans = min(ans, l - 1 + N...
Solution
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class Solution: def minOperations(self, nums: List[int], x: int) -> int: """Sliding Window O(N) / O(1)""" <|body_0|> def minOperations1(self, nums: List[int], x: int) -> int: """Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_10k_train_005298
1,322
no_license
[ { "docstring": "Sliding Window O(N) / O(1)", "name": "minOperations", "signature": "def minOperations(self, nums: List[int], x: int) -> int" }, { "docstring": "Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)", "name": "minOperations1", "signature": "def minOperations1(self...
2
null
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minOperations(self, nums: List[int], x: int) -> int: Sliding Window O(N) / O(1) - def minOperations1(self, nums: List[int], x: int) -> int: Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 ...
Implement the Python class `Solution` described below. Class description: Implement the Solution class. Method signatures and docstrings: - def minOperations(self, nums: List[int], x: int) -> int: Sliding Window O(N) / O(1) - def minOperations1(self, nums: List[int], x: int) -> int: Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 ...
c26aef2a59e5cc2d9b0658b9c7386a43267ff8a1
<|skeleton|> class Solution: def minOperations(self, nums: List[int], x: int) -> int: """Sliding Window O(N) / O(1)""" <|body_0|> def minOperations1(self, nums: List[int], x: int) -> int: """Prefix Sum 왼쪽의 합을 미리 저장해놓고, 오른쪽에서 시작해서 최소의 길이를 구함. O(N) / O(N)""" <|body_1|> <|end_ske...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class Solution: def minOperations(self, nums: List[int], x: int) -> int: """Sliding Window O(N) / O(1)""" N = len(nums) s, l, ans = (sum(nums), 1, float('inf')) nums.insert(0, 0) for r in range(N + 1): s -= nums[r] while l < r and s < x: ...
the_stack_v2_python_sparse
Leetcode/1658.py
hanwgyu/algorithm_problem_solving
train
5
2bfd235494d5c9710a4c67cd610b5bced84ba325
[ "LOG.debug('Setting register {:#0x} to value {}'.format(p_register, p_values))\nBuildCommand.write_register_command(p_controller_obj, p_register, p_values)\npass", "l_val = bytearray(1)\nl_val[0] = 3\nself.set_register_value(255, 112, l_val)" ]
<|body_start_0|> LOG.debug('Setting register {:#0x} to value {}'.format(p_register, p_values)) BuildCommand.write_register_command(p_controller_obj, p_register, p_values) pass <|end_body_0|> <|body_start_1|> l_val = bytearray(1) l_val[0] = 3 self.set_register_value(255, ...
CreateCommands
[]
stack_v2_sparse_python_classes_v1
<|skeleton|> class CreateCommands: def set_register_value(self, p_controller_obj, p_register, p_values): """Set one of the device's registers.""" <|body_0|> def set_pim_mode(self): """Set the PIM operating mode: Page 6 of UPB Powerline Interface Module (PIM) Description Version 1.6 The...
stack_v2_sparse_classes_10k_train_005299
17,549
permissive
[ { "docstring": "Set one of the device's registers.", "name": "set_register_value", "signature": "def set_register_value(self, p_controller_obj, p_register, p_values)" }, { "docstring": "Set the PIM operating mode: Page 6 of UPB Powerline Interface Module (PIM) Description Version 1.6 The PIM mod...
2
null
Implement the Python class `CreateCommands` described below. Class description: Implement the CreateCommands class. Method signatures and docstrings: - def set_register_value(self, p_controller_obj, p_register, p_values): Set one of the device's registers. - def set_pim_mode(self): Set the PIM operating mode: Page 6 ...
Implement the Python class `CreateCommands` described below. Class description: Implement the CreateCommands class. Method signatures and docstrings: - def set_register_value(self, p_controller_obj, p_register, p_values): Set one of the device's registers. - def set_pim_mode(self): Set the PIM operating mode: Page 6 ...
a100fc67761a22ae47ed6f21f3c9464e2de5d54f
<|skeleton|> class CreateCommands: def set_register_value(self, p_controller_obj, p_register, p_values): """Set one of the device's registers.""" <|body_0|> def set_pim_mode(self): """Set the PIM operating mode: Page 6 of UPB Powerline Interface Module (PIM) Description Version 1.6 The...
stack_v2_sparse_classes_10k
data/stack_v2_sparse_classes_30k
class CreateCommands: def set_register_value(self, p_controller_obj, p_register, p_values): """Set one of the device's registers.""" LOG.debug('Setting register {:#0x} to value {}'.format(p_register, p_values)) BuildCommand.write_register_command(p_controller_obj, p_register, p_values) ...
the_stack_v2_python_sparse
Project/src/Modules/House/Family/Upb/upb_pim.py
DBrianKimmel/PyHouse
train
3