uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f08514e3a320b2e787977f96 | train | function | def test_2d_sequence_sparse_one_hot():
x = C.sequence.input_variable((2,))
num_classes = 3
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
indices = [np.asarray([[2, 1], [0, 2]]), np.asarray([[1, 0]])]
result = sparse_one_hot.eval({x : indices}, as_numpy=False)
result_dense = _to... | def test_2d_sequence_sparse_one_hot():
| x = C.sequence.input_variable((2,))
num_classes = 3
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
indices = [np.asarray([[2, 1], [0, 2]]), np.asarray([[1, 0]])]
result = sparse_one_hot.eval({x : indices}, as_numpy=False)
result_dense = _to_dense(result, True)
assert np.arra... | 2], [1, 0]])
result = sparse_one_hot.eval({x : indices}, as_numpy=False)
result_dense = _to_dense(result)
assert np.array_equal(result_dense, np.eye(num_classes, dtype=np.float32)[indices])
def test_2d_sequence_sparse_one_hot():
| 64 | 64 | 147 | 10 | 54 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_2d_sequence_sparse_one_hot | test_2d_sequence_sparse_one_hot | 230 | 239 | 230 | 230 | 17ec23f975274f63f3414fbd8083c31735ecf248 | bigcode/the-stack | train |
1a79e089bec5fb324f0c1b69 | train | function | def test_times_2d_sparse_sequence_operand(device_id):
from .. import times
dev = cntk_device(device_id)
vocab_size = 6
sample_shape = (2, vocab_size)
input_sparse_indices = [[1, 3, 4, 2, 0, 5], [2, 4], [0, 2]]
input_data = C.Value.one_hot(input_sparse_indices, sample_shape, device=dev)
a ... | def test_times_2d_sparse_sequence_operand(device_id):
| from .. import times
dev = cntk_device(device_id)
vocab_size = 6
sample_shape = (2, vocab_size)
input_sparse_indices = [[1, 3, 4, 2, 0, 5], [2, 4], [0, 2]]
input_data = C.Value.one_hot(input_sparse_indices, sample_shape, device=dev)
a = C.sequence.input_variable(shape=sample_shape, is_spa... | =sample_shape, is_sparse=True, name='a')
a_no_sequence_dense = times(a_no_sequence, w)
res = a_no_sequence_dense.eval({a_no_sequence : input_data}, device=dev)
assert np.array_equal(res, [w_init[input_sparse_indices[0]], w_init[input_sparse_indices[1]], w_init[input_sparse_indices[2]]])
def test_times_2d_sp... | 90 | 90 | 302 | 12 | 78 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_times_2d_sparse_sequence_operand | test_times_2d_sparse_sequence_operand | 47 | 69 | 47 | 47 | 59e02acbbe9fd8ed2f9d6ece7dfa51999ddb1eaf | bigcode/the-stack | train |
927c2519736ed5c714fd21a0 | train | function | def test_non_sequence_sparse_one_hot():
i = C.input_variable(())
sparse_one_hot = C.one_hot(i, num_classes=3, sparse_output=True)
indices = np.asarray([2, 0, 1])
result = sparse_one_hot.eval({i : indices})
result_indices = result.dot(np.array([0, 1, 2]))
assert np.array_equal(result_indices, ind... | def test_non_sequence_sparse_one_hot():
| i = C.input_variable(())
sparse_one_hot = C.one_hot(i, num_classes=3, sparse_output=True)
indices = np.asarray([2, 0, 1])
result = sparse_one_hot.eval({i : indices})
result_indices = result.dot(np.array([0, 1, 2]))
assert np.array_equal(result_indices, indices)
| _axis_dim1, additional_axis_dim2, vocab_size)
a = C.input_variable(shape=input_shape, is_sparse=True, name='input')
w = C.parameter(init=w_init)
with pytest.raises(RuntimeError):
a_projection = times(a, w)
def test_non_sequence_sparse_one_hot():
| 64 | 64 | 87 | 8 | 56 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_non_sequence_sparse_one_hot | test_non_sequence_sparse_one_hot | 198 | 204 | 198 | 198 | faaa34bcdac542002cd6cef86e4cbe2e442bfc60 | bigcode/the-stack | train |
eab05b366966b8b51a61737c | train | function | def test_times_2d_sparse_operand(device_id):
from .. import times
dev = cntk_device(device_id)
vocab_size = 6
sample_shape = (2, vocab_size)
input_sparse_indices = [[1, 3], [2, 4], [0, 2]]
input_data = C.Value.one_hot(input_sparse_indices, sample_shape, device=dev)
a = C.sequence.input_va... | def test_times_2d_sparse_operand(device_id):
| from .. import times
dev = cntk_device(device_id)
vocab_size = 6
sample_shape = (2, vocab_size)
input_sparse_indices = [[1, 3], [2, 4], [0, 2]]
input_data = C.Value.one_hot(input_sparse_indices, sample_shape, device=dev)
a = C.sequence.input_variable(shape=sample_shape, is_sparse=True, ne... | under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
"""
Unit tests for reshaping operations.
"""
import numpy as np
import scipy as sp
import pytest
import cntk as C
from .ops_test_utils import... | 96 | 96 | 322 | 11 | 84 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_times_2d_sparse_operand | test_times_2d_sparse_operand | 20 | 44 | 20 | 20 | bcc8baac7aff6eced5722685213adb8741dbf1b6 | bigcode/the-stack | train |
fe59bb301f9d2cac38f3f56f | train | function | def test_2d_sparse_csr_batch_input(device_id):
dev = cntk_device(device_id)
features = C.input_variable((2, 3), is_sparse=True)
w = C.parameter(init=np.asarray([[0.5, 1], [-.5, 2], [1., 1.5]], dtype=np.float32), device=dev)
t = C.times(features, w)
features_data = [sp.sparse.csr_matrix(np.asarray([[... | def test_2d_sparse_csr_batch_input(device_id):
| dev = cntk_device(device_id)
features = C.input_variable((2, 3), is_sparse=True)
w = C.parameter(init=np.asarray([[0.5, 1], [-.5, 2], [1., 1.5]], dtype=np.float32), device=dev)
t = C.times(features, w)
features_data = [sp.sparse.csr_matrix(np.asarray([[1.,0.,0.], [0.,1.,0.]], dtype=np.float32)),
... | })
expected_result = np.asarray([[[ 0., 1.], [ 6., 7.]], [[ 4., 5.], [ 2., 3.]]])
assert np.array_equal(result, expected_result)
def test_2d_sparse_csr_batch_input(device_id):
| 64 | 64 | 202 | 13 | 51 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_2d_sparse_csr_batch_input | test_2d_sparse_csr_batch_input | 257 | 265 | 257 | 257 | 2e2dda87cd15622a296d91e0c81a690e7db32917 | bigcode/the-stack | train |
a67368a27fb7e1b10309f9eb | train | function | def test_2d_non_sequence_sparse_one_hot():
x = C.input_variable((2,))
num_classes = 3
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
indices = np.asarray([[2, 1], [0, 2], [1, 0]])
result = sparse_one_hot.eval({x : indices}, as_numpy=False)
result_dense = _to_dense(result)
as... | def test_2d_non_sequence_sparse_one_hot():
| x = C.input_variable((2,))
num_classes = 3
sparse_one_hot = C.one_hot(x, num_classes, sparse_output=True)
indices = np.asarray([[2, 1], [0, 2], [1, 0]])
result = sparse_one_hot.eval({x : indices}, as_numpy=False)
result_dense = _to_dense(result)
assert np.array_equal(result_dense, np.eye(nu... | .stack([np.expand_dims(np.asarray(w_value[idx]), axis=0) for idx in seq]) for seq in indices]
assert np.array_equal(result[0], expected_result[0])
assert np.array_equal(result[1], expected_result[1])
def test_2d_non_sequence_sparse_one_hot():
| 64 | 64 | 112 | 11 | 53 | burhandodhy/CNTK | bindings/python/cntk/ops/tests/sparse_test.py | Python | test_2d_non_sequence_sparse_one_hot | test_2d_non_sequence_sparse_one_hot | 219 | 227 | 219 | 219 | 28eb745421470098fdc225e6d6c19d09fcdd8a55 | bigcode/the-stack | train |
59119909635be8a4cf94181c | train | class | @registry.register_metric("macro_ap")
class MacroAP(AveragePrecision):
"""Metric for calculating Macro Average Precision.
**Key:** ``macro_ap``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_ap"
| @registry.register_metric("macro_ap")
class MacroAP(AveragePrecision):
| """Metric for calculating Macro Average Precision.
**Key:** ``macro_ap``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_ap"
| calculating Micro Average Precision.
**Key:** ``micro_ap``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_ap"
@registry.register_metric("macro_ap")
class MacroAP(AveragePrecision):
| 64 | 64 | 68 | 15 | 49 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MacroAP | MacroAP | 960 | 969 | 960 | 961 | 2beadbc60466b85f66b076f01e0a6b9755cf8d93 | bigcode/the-stack | train |
095fc580adea6ae805e10cfd | train | class | @registry.register_metric("stvqa_accuracy")
class STVQAAccuracy(TextVQAAccuracy):
def __init__(self):
super().__init__()
self.name = "stvqa_accuracy"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAAccuracyEvaluator()
| @registry.register_metric("stvqa_accuracy")
class STVQAAccuracy(TextVQAAccuracy):
| def __init__(self):
super().__init__()
self.name = "stvqa_accuracy"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAAccuracyEvaluator()
| super().__init__()
self.name = "stvqa_anls"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAANLSEvaluator()
@registry.register_metric("stvqa_accuracy")
class STVQAAccuracy(TextVQAAccuracy):
| 64 | 64 | 68 | 19 | 45 | lilyli2004/mmf | mmf/modules/metrics.py | Python | STVQAAccuracy | STVQAAccuracy | 669 | 676 | 669 | 670 | 147de6d57bc9942024812b31bc2f3fc7387a1177 | bigcode/the-stack | train |
ee4688f50ecea66eb32ed044 | train | class | @registry.register_metric("micro_f1")
class MicroF1(F1):
"""Metric for calculating Micro F1.
**Key:** ``micro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_f1"
| @registry.register_metric("micro_f1")
class MicroF1(F1):
| """Metric for calculating Micro F1.
**Key:** ``micro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_f1"
| 1.
**Key:** ``macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_f1"
@registry.register_metric("micro_f1")
class MicroF1(F1):
| 64 | 64 | 71 | 16 | 48 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MicroF1 | MicroF1 | 754 | 763 | 754 | 755 | f8c338394594bcd602decca1e0e762bf8d1dcd04 | bigcode/the-stack | train |
fce0314ec7825df3ad0a4a3e | train | class | @registry.register_metric("multilabel_micro_f1")
class MultiLabelMicroF1(MultiLabelF1):
"""Metric for calculating Multilabel Micro F1.
**Key:** ``multilabel_micro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "multilabel_micro_f1"... | @registry.register_metric("multilabel_micro_f1")
class MultiLabelMicroF1(MultiLabelF1):
| """Metric for calculating Multilabel Micro F1.
**Key:** ``multilabel_micro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "multilabel_micro_f1"
| `
"""
def __init__(self, *args, **kwargs):
super().__init__(multilabel=True, **kwargs)
self.name = "multilabel_f1"
@registry.register_metric("multilabel_micro_f1")
class MultiLabelMicroF1(MultiLabelF1):
| 64 | 64 | 88 | 24 | 40 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MultiLabelMicroF1 | MultiLabelMicroF1 | 790 | 799 | 790 | 791 | 7a6eb89d3f3af89787610c4ea24f68b87433e869 | bigcode/the-stack | train |
9938ed3c86c7cf656d8f4882 | train | class | @registry.register_metric("r@1")
class RecallAt1(RecallAtK):
"""
Calculate Recall@1 which specifies how many time the chosen candidate
was rank 1.
**Key**: ``r@1``.
"""
def __init__(self):
super().__init__("r@1")
def calculate(self, sample_list, model_output, *args, **kwargs):
... | @registry.register_metric("r@1")
class RecallAt1(RecallAtK):
| """
Calculate Recall@1 which specifies how many time the chosen candidate
was rank 1.
**Key**: ``r@1``.
"""
def __init__(self):
super().__init__("r@1")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Recall@1 and return it back.
Args:... | _output, k, *args, **kwargs):
ranks = self.get_ranks(sample_list, model_output)
recall = float(torch.sum(torch.le(ranks, k))) / ranks.size(0)
return recall
@registry.register_metric("r@1")
class RecallAt1(RecallAtK):
| 64 | 64 | 158 | 18 | 45 | lilyli2004/mmf | mmf/modules/metrics.py | Python | RecallAt1 | RecallAt1 | 476 | 500 | 476 | 477 | 71fea3056d5560bf65ff959385d9841a71e3a791 | bigcode/the-stack | train |
b32d761cf3936aab7cd2be4e | train | class | @registry.register_metric("roc_auc")
class ROC_AUC(BaseMetric):
"""Metric for calculating ROC_AUC.
See more details at `sklearn.metrics.roc_auc_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score>`_ # noqa
**Note**: ROC_AUC is not defined... | @registry.register_metric("roc_auc")
class ROC_AUC(BaseMetric):
| """Metric for calculating ROC_AUC.
See more details at `sklearn.metrics.roc_auc_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html#sklearn.metrics.roc_auc_score>`_ # noqa
**Note**: ROC_AUC is not defined when expected tensor only contains one
label. Make sure you... | ("multilabel_macro_f1")
class MultiLabelMacroF1(F1):
"""Metric for calculating Multilabel Macro F1.
**Key:** ``multilabel_macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "multilabel_macro_f1"
@registry.register_metric("roc_auc... | 96 | 96 | 321 | 15 | 81 | lilyli2004/mmf | mmf/modules/metrics.py | Python | ROC_AUC | ROC_AUC | 814 | 848 | 814 | 815 | d7eaecbe2cd9e11a9c5aa4a2ead5d5f0682e4824 | bigcode/the-stack | train |
126f28304470a1ec6b6a49c2 | train | class | @registry.register_metric("macro_f1")
class MacroF1(F1):
"""Metric for calculating Macro F1.
**Key:** ``macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_f1"
| @registry.register_metric("macro_f1")
class MacroF1(F1):
| """Metric for calculating Macro F1.
**Key:** ``macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_f1"
| one-hot, convert back to class indices array
expected = expected.argmax(dim=-1)
value = f1_score(expected.cpu(), output.cpu(), **self._sk_kwargs)
return expected.new_tensor(value, dtype=torch.float)
@registry.register_metric("macro_f1")
class MacroF1(F1):
| 64 | 64 | 71 | 16 | 48 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MacroF1 | MacroF1 | 742 | 751 | 742 | 743 | b2643fa3dfbc524a5f3965c6effb58f97fb8e7d8 | bigcode/the-stack | train |
11fbc3628fe8d188098cbf58 | train | class | @registry.register_metric("textvqa_accuracy")
class TextVQAAccuracy(BaseMetric):
def __init__(self):
super().__init__("textvqa_accuracy")
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.TextVQAAccuracyEvaluator()
self.required_params = ["scores", "answers",... | @registry.register_metric("textvqa_accuracy")
class TextVQAAccuracy(BaseMetric):
| def __init__(self):
super().__init__("textvqa_accuracy")
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.TextVQAAccuracyEvaluator()
self.required_params = ["scores", "answers", "context_tokens"]
self.gt_key = "answers"
def calculate(self, sampl... | (self, sample_list, model_output, *args, **kwargs):
"""Calculate Mean Reciprocal Rank and return it back.
Args:
sample_list (SampleList): SampleList provided by DataLoader for
current iteration
model_output (Dict): Dict returned by model.
... | 116 | 116 | 388 | 18 | 98 | lilyli2004/mmf | mmf/modules/metrics.py | Python | TextVQAAccuracy | TextVQAAccuracy | 612 | 656 | 612 | 613 | dd69499d3278bfdbc41f5f50a11090756cc0721f | bigcode/the-stack | train |
16b724203820c72fbfd294b1 | train | class | @registry.register_metric("micro_roc_auc")
class MicroROC_AUC(ROC_AUC):
"""Metric for calculating Micro ROC_AUC.
**Key:** ``micro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_roc_auc"
| @registry.register_metric("micro_roc_auc")
class MicroROC_AUC(ROC_AUC):
| """Metric for calculating Micro ROC_AUC.
**Key:** ``micro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_roc_auc"
| ["targets"]
expected = _convert_to_one_hot(expected, output)
value = roc_auc_score(expected.cpu(), output.cpu(), **self._sk_kwargs)
return expected.new_tensor(value, dtype=torch.float)
@registry.register_metric("micro_roc_auc")
class MicroROC_AUC(ROC_AUC):
| 64 | 64 | 78 | 20 | 44 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MicroROC_AUC | MicroROC_AUC | 851 | 860 | 851 | 852 | d939a3258c2e6bc07a90b69f36311c43a4849a88 | bigcode/the-stack | train |
039cde2be7dc617a2c2815a1 | train | class | @registry.register_metric("ocrvqa_accuracy")
class OCRVQAAccuracy(STVQAAccuracy):
def __init__(self):
super().__init__()
# same as STVQAAccuracy except for the name
self.name = "ocrvqa_accuracy"
| @registry.register_metric("ocrvqa_accuracy")
class OCRVQAAccuracy(STVQAAccuracy):
| def __init__(self):
super().__init__()
# same as STVQAAccuracy except for the name
self.name = "ocrvqa_accuracy"
| self):
super().__init__()
self.name = "stvqa_accuracy"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAAccuracyEvaluator()
@registry.register_metric("ocrvqa_accuracy")
class OCRVQAAccuracy(STVQAAccuracy):
| 64 | 64 | 55 | 20 | 44 | lilyli2004/mmf | mmf/modules/metrics.py | Python | OCRVQAAccuracy | OCRVQAAccuracy | 679 | 684 | 679 | 680 | 302d30bca1933a439c70b5f3191978bdd13b4491 | bigcode/the-stack | train |
c2b512e249e375852902a3e1 | train | class | @registry.register_metric("stvqa_anls")
class STVQAANLS(TextVQAAccuracy):
def __init__(self):
super().__init__()
self.name = "stvqa_anls"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAANLSEvaluator()
| @registry.register_metric("stvqa_anls")
class STVQAANLS(TextVQAAccuracy):
| def __init__(self):
super().__init__()
self.name = "stvqa_anls"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.STVQAANLSEvaluator()
| _answer": pred_answer, "gt_answers": gt_answers})
accuracy = self.evaluator.eval_pred_list(predictions)
accuracy = torch.tensor(accuracy).to(sample_list.context_tokens.device)
return accuracy
@registry.register_metric("stvqa_anls")
class STVQAANLS(TextVQAAccuracy):
| 64 | 64 | 73 | 21 | 42 | lilyli2004/mmf | mmf/modules/metrics.py | Python | STVQAANLS | STVQAANLS | 659 | 666 | 659 | 660 | 4bde21754894385b560f53c2e25697a284050fdc | bigcode/the-stack | train |
b90f427a431462faa7664a4f | train | class | @registry.register_metric("f1")
class F1(BaseMetric):
"""Metric for calculating F1. Can be used with type and params
argument for customization. params will be directly passed to sklearn
f1 function.
**Key:** ``f1``
"""
def __init__(self, *args, **kwargs):
super().__init__("f1")
... | @registry.register_metric("f1")
class F1(BaseMetric):
| """Metric for calculating F1. Can be used with type and params
argument for customization. params will be directly passed to sklearn
f1 function.
**Key:** ``f1``
"""
def __init__(self, *args, **kwargs):
super().__init__("f1")
self._multilabel = kwargs.pop("multilabel", False)
... | def __init__(self):
super().__init__()
self.name = "textcaps_bleu4"
self.required_params = ["scores", "ref_strs", "context_tokens"]
self.gt_key = "ref_strs"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.TextCapsBleu4Evaluator()
@registry.r... | 93 | 93 | 310 | 14 | 79 | lilyli2004/mmf | mmf/modules/metrics.py | Python | F1 | F1 | 699 | 739 | 699 | 700 | 9a77712e02db51f4005111e3cce77cd4a088676f | bigcode/the-stack | train |
4e2dc3af45f7655658cd7bc5 | train | class | @registry.register_metric("binary_f1")
class BinaryF1(F1):
"""Metric for calculating Binary F1.
**Key:** ``binary_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", labels=[1], **kwargs)
self.name = "binary_f1"
| @registry.register_metric("binary_f1")
class BinaryF1(F1):
| """Metric for calculating Binary F1.
**Key:** ``binary_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", labels=[1], **kwargs)
self.name = "binary_f1"
| 1.
**Key:** ``micro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_f1"
@registry.register_metric("binary_f1")
class BinaryF1(F1):
| 64 | 64 | 75 | 16 | 48 | lilyli2004/mmf | mmf/modules/metrics.py | Python | BinaryF1 | BinaryF1 | 766 | 775 | 766 | 767 | 7173a4091ce997c45fb5fd378d8caa2f887dc851 | bigcode/the-stack | train |
3d8bc321a22f20461e9c899c | train | class | @registry.register_metric("binary_ap")
class BinaryAP(AveragePrecision):
"""Metric for calculating Binary Average Precision.
See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precisi... | @registry.register_metric("binary_ap")
class BinaryAP(AveragePrecision):
| """Metric for calculating Binary Average Precision.
See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ # noqa
**Key:** ``binary_ap``
"""
def __init__(s... | .
Returns:
torch.FloatTensor: AP.
"""
output = torch.nn.functional.softmax(model_output["scores"], dim=-1)
expected = sample_list["targets"]
expected = _convert_to_one_hot(expected, output)
value = average_precision_score(expected.cpu(), output.cpu(), **sel... | 93 | 93 | 312 | 15 | 78 | lilyli2004/mmf | mmf/modules/metrics.py | Python | BinaryAP | BinaryAP | 909 | 945 | 909 | 910 | 884c2f6b69131dcba2346f804a7f511cbbe895a0 | bigcode/the-stack | train |
9047f79049e247c771e763ae | train | class | @registry.register_metric("r@10")
class RecallAt10(RecallAtK):
"""
Calculate Recall@10 which specifies how many time the chosen candidate
was among first 10 ranks.
**Key**: ``r@10``.
"""
def __init__(self):
super().__init__("r@10")
def calculate(self, sample_list, model_output, *a... | @registry.register_metric("r@10")
class RecallAt10(RecallAtK):
| """
Calculate Recall@10 which specifies how many time the chosen candidate
was among first 10 ranks.
**Key**: ``r@10``.
"""
def __init__(self):
super().__init__("r@10")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Recall@10 and return it ba... | Loader for
current iteration
model_output (Dict): Dict returned by model.
Returns:
torch.FloatTensor: Recall@5
"""
return self.calculate(sample_list, model_output, k=5)
@registry.register_metric("r@10")
class RecallAt10(RecallAtK):
| 64 | 64 | 160 | 18 | 46 | lilyli2004/mmf | mmf/modules/metrics.py | Python | RecallAt10 | RecallAt10 | 530 | 554 | 530 | 531 | e8ee190566dfe6cd3844e6ca35d2feb8507842ae | bigcode/the-stack | train |
0b5fe43f2fddac547ab615bd | train | class | @registry.register_metric("r@5")
class RecallAt5(RecallAtK):
"""
Calculate Recall@5 which specifies how many time the chosen candidate
was among first 5 rank.
**Key**: ``r@5``.
"""
def __init__(self):
super().__init__("r@5")
def calculate(self, sample_list, model_output, *args, **... | @registry.register_metric("r@5")
class RecallAt5(RecallAtK):
| """
Calculate Recall@5 which specifies how many time the chosen candidate
was among first 5 rank.
**Key**: ``r@5``.
"""
def __init__(self):
super().__init__("r@5")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Recall@5 and return it back.
... | Loader for
current iteration
model_output (Dict): Dict returned by model.
Returns:
torch.FloatTensor: Recall@1
"""
return self.calculate(sample_list, model_output, k=1)
@registry.register_metric("r@5")
class RecallAt5(RecallAtK):
| 64 | 64 | 160 | 18 | 46 | lilyli2004/mmf | mmf/modules/metrics.py | Python | RecallAt5 | RecallAt5 | 503 | 527 | 503 | 504 | c6fcc1590028c6d2af0af4b3b8c1702b985ae60c | bigcode/the-stack | train |
276be3239c3c6fd43867bf5a | train | function | def _convert_to_one_hot(expected, output):
# This won't get called in case of multilabel, only multiclass or binary
# as multilabel will anyways be multi hot vector
if output.squeeze().dim() != expected.squeeze().dim() and expected.dim() == 1:
expected = torch.nn.functional.one_hot(
expe... | def _convert_to_one_hot(expected, output):
# This won't get called in case of multilabel, only multiclass or binary
# as multilabel will anyways be multi hot vector
| if output.squeeze().dim() != expected.squeeze().dim() and expected.dim() == 1:
expected = torch.nn.functional.one_hot(
expected.long(), num_classes=output.size(-1)
).float()
return expected
| ,
)
from mmf.common.registry import registry
from mmf.datasets.processors.processors import EvalAIAnswerProcessor
def _convert_to_one_hot(expected, output):
# This won't get called in case of multilabel, only multiclass or binary
# as multilabel will anyways be multi hot vector
| 64 | 64 | 90 | 40 | 23 | lilyli2004/mmf | mmf/modules/metrics.py | Python | _convert_to_one_hot | _convert_to_one_hot | 61 | 68 | 61 | 63 | db27b6880b91163d0516c3814ccc79935005b1e8 | bigcode/the-stack | train |
7b9ac5ca9da33be34ab1f7d5 | train | class | @registry.register_metric("accuracy")
class Accuracy(BaseMetric):
"""Metric for calculating accuracy.
**Key:** ``accuracy``
"""
def __init__(self):
super().__init__("accuracy")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate accuracy and return it bac... | @registry.register_metric("accuracy")
class Accuracy(BaseMetric):
| """Metric for calculating accuracy.
**Key:** ``accuracy``
"""
def __init__(self):
super().__init__("accuracy")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate accuracy and return it back.
Args:
sample_list (SampleList): SampleList... | Override in your child class
raise NotImplementedError("'calculate' must be implemented in the child class")
def __call__(self, *args, **kwargs):
return self.calculate(*args, **kwargs)
def _calculate_with_checks(self, *args, **kwargs):
value = self.calculate(*args, **kwargs)
r... | 86 | 86 | 287 | 12 | 73 | lilyli2004/mmf | mmf/modules/metrics.py | Python | Accuracy | Accuracy | 212 | 256 | 212 | 213 | e767bb79c4a83dc3dea23d1191875fec06f3c19d | bigcode/the-stack | train |
3720614fda345693d10d235c | train | class | @registry.register_metric("vqa_evalai_accuracy")
class VQAEvalAIAccuracy(BaseMetric):
"""
Calculate Eval AI VQAAccuracy. Find more information here_
This is more accurate and similar comparision to Eval AI
but is slower compared to vqa_accuracy.
**Key**: ``vqa_evalai_accuracy``.
.. _here: http... | @registry.register_metric("vqa_evalai_accuracy")
class VQAEvalAIAccuracy(BaseMetric):
| """
Calculate Eval AI VQAAccuracy. Find more information here_
This is more accurate and similar comparision to Eval AI
but is slower compared to vqa_accuracy.
**Key**: ``vqa_evalai_accuracy``.
.. _here: https://visualqa.org/evaluation.html
"""
def __init__(self):
super().__in... | returned by model.
Returns:
torch.FloatTensor: VQA Accuracy
"""
output = model_output["scores"]
# for three branch movie+mcan model
if output.dim() == 3:
output = output[:, 0]
expected = sample_list["targets"]
output = self._masked_unk_... | 172 | 172 | 576 | 21 | 150 | lilyli2004/mmf | mmf/modules/metrics.py | Python | VQAEvalAIAccuracy | VQAEvalAIAccuracy | 363 | 432 | 363 | 364 | ef8c167958cf90a5bfb895e684a77565bc29b900 | bigcode/the-stack | train |
53460a586b6c1f05f33b9ce1 | train | class | @registry.register_metric("macro_roc_auc")
class MacroROC_AUC(ROC_AUC):
"""Metric for calculating Macro ROC_AUC.
**Key:** ``macro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_roc_auc"
| @registry.register_metric("macro_roc_auc")
class MacroROC_AUC(ROC_AUC):
| """Metric for calculating Macro ROC_AUC.
**Key:** ``macro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_roc_auc"
| ``micro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_roc_auc"
@registry.register_metric("macro_roc_auc")
class MacroROC_AUC(ROC_AUC):
| 64 | 64 | 78 | 20 | 44 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MacroROC_AUC | MacroROC_AUC | 863 | 872 | 863 | 864 | 33fd7b93e04e0bccb97f9a9abf61eb79789c79f2 | bigcode/the-stack | train |
d9b3d4e0a02a5a7a205cc9b0 | train | class | @registry.register_metric("vqa_accuracy")
class VQAAccuracy(BaseMetric):
"""
Calculate VQAAccuracy. Find more information here_
**Key**: ``vqa_accuracy``.
.. _here: https://visualqa.org/evaluation.html
"""
def __init__(self):
super().__init__("vqa_accuracy")
def _masked_unk_softm... | @registry.register_metric("vqa_accuracy")
class VQAAccuracy(BaseMetric):
| """
Calculate VQAAccuracy. Find more information here_
**Key**: ``vqa_accuracy``.
.. _here: https://visualqa.org/evaluation.html
"""
def __init__(self):
super().__init__("vqa_accuracy")
def _masked_unk_softmax(self, x, dim, mask_idx):
x1 = torch.nn.functional.softmax(x, d... | ]
scores = scores.tolist()
predictions = []
for j, _ in enumerate(scores):
caption = self.caption_processor(scores[j])["tokens"]
predictions.append(caption)
hypotheses.extend(predictions)
assert len(references) == len(hypotheses)
bleu4 = self._bl... | 105 | 105 | 353 | 16 | 89 | lilyli2004/mmf | mmf/modules/metrics.py | Python | VQAAccuracy | VQAAccuracy | 314 | 360 | 314 | 315 | a9e8cc031dbafa9f3c2c398800994e087fc956bb | bigcode/the-stack | train |
b003189146f37c9a883399e3 | train | class | class RecallAtK(BaseMetric):
def __init__(self, name="recall@k"):
super().__init__(name)
def score_to_ranks(self, scores):
# sort in descending order - largest score gets highest rank
sorted_ranks, ranked_idx = scores.sort(1, descending=True)
# convert from ranked_idx to ranks
... | class RecallAtK(BaseMetric):
| def __init__(self, name="recall@k"):
super().__init__(name)
def score_to_ranks(self, scores):
# sort in descending order - largest score gets highest rank
sorted_ranks, ranked_idx = scores.sort(1, descending=True)
# convert from ranked_idx to ranks
ranks = ranked_idx.cl... | gt_answer]
matching_answers = [item for item in other_answers if item[1] == answer]
acc = min(1, float(len(matching_answers)) / 3)
gt_acc.append(acc)
avgGTAcc = float(sum(gt_acc)) / len(gt_acc)
accuracy.append(avgGTAcc)
accuracy = float(s... | 103 | 103 | 346 | 7 | 96 | lilyli2004/mmf | mmf/modules/metrics.py | Python | RecallAtK | RecallAtK | 435 | 473 | 435 | 435 | e828169df55db9095f34ddf807d12230f20004dd | bigcode/the-stack | train |
974e3feec4fe1c3019011ca1 | train | class | @registry.register_metric("ap")
class AveragePrecision(BaseMetric):
"""Metric for calculating Average Precision.
See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ ... | @registry.register_metric("ap")
class AveragePrecision(BaseMetric):
| """Metric for calculating Average Precision.
See more details at `sklearn.metrics.average_precision_score <http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html#sklearn.metrics.average_precision_score>`_ # noqa
If you are looking for binary case, please take a look at... | macro_roc_auc")
class MacroROC_AUC(ROC_AUC):
"""Metric for calculating Macro ROC_AUC.
**Key:** ``macro_roc_auc``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "macro_roc_auc"
@registry.register_metric("ap")
class AveragePrecision(BaseM... | 86 | 86 | 288 | 13 | 73 | lilyli2004/mmf | mmf/modules/metrics.py | Python | AveragePrecision | AveragePrecision | 875 | 906 | 875 | 876 | b5f75efaa418175435a5519d9e2212bcc8ba125b | bigcode/the-stack | train |
cb28970d011df269f9fef5ef | train | class | class Metrics:
"""Internally used by MMF, Metrics acts as wrapper for handling
calculation of metrics over various metrics specified by the model in
the config. It initializes all of the metrics and when called it runs
calculate on each of them one by one and returns back a dict with proper
naming b... | class Metrics:
| """Internally used by MMF, Metrics acts as wrapper for handling
calculation of metrics over various metrics specified by the model in
the config. It initializes all of the metrics and when called it runs
calculate on each of them one by one and returns back a dict with proper
naming back. For e.g. a... | , model_output):
metric = torch.tensor(2, dtype=torch.float)
return metric
Example config for above metric::
model_config:
pythia:
metrics:
- type: some
params:
some_param: a
"""
import collections
import torch
from sklearn.me... | 202 | 202 | 675 | 3 | 198 | lilyli2004/mmf | mmf/modules/metrics.py | Python | Metrics | Metrics | 71 | 161 | 71 | 71 | a4b5e39794af214ae0553fd4f7424802c647862a | bigcode/the-stack | train |
2481830a3274cf50c5fe2aef | train | class | @registry.register_metric("textcaps_bleu4")
class TextCapsBleu4(TextVQAAccuracy):
def __init__(self):
super().__init__()
self.name = "textcaps_bleu4"
self.required_params = ["scores", "ref_strs", "context_tokens"]
self.gt_key = "ref_strs"
import mmf.utils.m4c_evaluators as ev... | @registry.register_metric("textcaps_bleu4")
class TextCapsBleu4(TextVQAAccuracy):
| def __init__(self):
super().__init__()
self.name = "textcaps_bleu4"
self.required_params = ["scores", "ref_strs", "context_tokens"]
self.gt_key = "ref_strs"
import mmf.utils.m4c_evaluators as evaluators
self.evaluator = evaluators.TextCapsBleu4Evaluator()
| QAAccuracy(STVQAAccuracy):
def __init__(self):
super().__init__()
# same as STVQAAccuracy except for the name
self.name = "ocrvqa_accuracy"
@registry.register_metric("textcaps_bleu4")
class TextCapsBleu4(TextVQAAccuracy):
| 64 | 64 | 101 | 22 | 42 | lilyli2004/mmf | mmf/modules/metrics.py | Python | TextCapsBleu4 | TextCapsBleu4 | 687 | 696 | 687 | 688 | 91afca8733f93b4308decd40e1702fcf7722522e | bigcode/the-stack | train |
c12ebba82ea211206b9cabea | train | class | @registry.register_metric("mean_rr")
class MeanReciprocalRank(RecallAtK):
"""
Calculate reciprocal of mean rank..
**Key**: ``mean_rr``.
"""
def __init__(self):
super().__init__("mean_rr")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Mean Recipr... | @registry.register_metric("mean_rr")
class MeanReciprocalRank(RecallAtK):
| """
Calculate reciprocal of mean rank..
**Key**: ``mean_rr``.
"""
def __init__(self):
super().__init__("mean_rr")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Mean Reciprocal Rank and return it back.
Args:
sample_list (Samp... |
model_output (Dict): Dict returned by model.
Returns:
torch.FloatTensor: mean rank
"""
ranks = self.get_ranks(sample_list, model_output)
return torch.mean(ranks)
@registry.register_metric("mean_rr")
class MeanReciprocalRank(RecallAtK):
| 64 | 64 | 156 | 19 | 45 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MeanReciprocalRank | MeanReciprocalRank | 585 | 609 | 585 | 586 | 4a6a97425380b148cf0780c0c8f61c4b0a08e427 | bigcode/the-stack | train |
548aae9c29ae2cb5a383c02e | train | class | @registry.register_metric("multilabel_macro_f1")
class MultiLabelMacroF1(F1):
"""Metric for calculating Multilabel Macro F1.
**Key:** ``multilabel_macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "multilabel_macro_f1"
| @registry.register_metric("multilabel_macro_f1")
class MultiLabelMacroF1(F1):
| """Metric for calculating Multilabel Macro F1.
**Key:** ``multilabel_macro_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="macro", **kwargs)
self.name = "multilabel_macro_f1"
| _f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "multilabel_micro_f1"
@registry.register_metric("multilabel_macro_f1")
class MultiLabelMacroF1(F1):
| 64 | 64 | 85 | 21 | 43 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MultiLabelMacroF1 | MultiLabelMacroF1 | 802 | 811 | 802 | 803 | c8cbb632b74a97123febe869a3519908c778509b | bigcode/the-stack | train |
2a473599e5e6b62645b7573d | train | class | @registry.register_metric("micro_ap")
class MicroAP(AveragePrecision):
"""Metric for calculating Micro Average Precision.
**Key:** ``micro_ap``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_ap"
| @registry.register_metric("micro_ap")
class MicroAP(AveragePrecision):
| """Metric for calculating Micro Average Precision.
**Key:** ``micro_ap``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_ap"
| Labels
if expected.dim() == 2:
expected = expected.argmax(dim=1)
value = average_precision_score(expected.cpu(), output.cpu(), **self._sk_kwargs)
return expected.new_tensor(value, dtype=torch.float)
@registry.register_metric("micro_ap")
class MicroAP(AveragePrecision):
| 64 | 64 | 68 | 15 | 49 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MicroAP | MicroAP | 948 | 957 | 948 | 949 | bc133b8c25dc5b84babde521f421637e16008fa6 | bigcode/the-stack | train |
0b8c8715bcbe896ca5cc79fd | train | class | class BaseMetric:
"""Base class to be inherited by all metrics registered to MMF. See
the description on top of the file for more information. Child class must
implement ``calculate`` function.
Args:
name (str): Name of the metric.
"""
def __init__(self, name, *args, **kwargs):
... | class BaseMetric:
| """Base class to be inherited by all metrics registered to MMF. See
the description on top of the file for more information. Child class must
implement ``calculate`` function.
Args:
name (str): Name of the metric.
"""
def __init__(self, name, *args, **kwargs):
self.name = name... | kwargs
)
if not isinstance(values[key], torch.Tensor):
values[key] = torch.tensor(values[key], dtype=torch.float)
else:
values[key] = values[key].float()
if values[key].dim() == 0:
values[key] =... | 97 | 97 | 326 | 4 | 92 | lilyli2004/mmf | mmf/modules/metrics.py | Python | BaseMetric | BaseMetric | 164 | 209 | 164 | 164 | fd5adf7542334c7f4070622053029d3d0ab47676 | bigcode/the-stack | train |
44ae33fef7c3ad2398e11378 | train | class | @registry.register_metric("multilabel_f1")
class MultiLabelF1(F1):
"""Metric for calculating Multilabel F1.
**Key:** ``multilabel_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(multilabel=True, **kwargs)
self.name = "multilabel_f1"
| @registry.register_metric("multilabel_f1")
class MultiLabelF1(F1):
| """Metric for calculating Multilabel F1.
**Key:** ``multilabel_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(multilabel=True, **kwargs)
self.name = "multilabel_f1"
| binary_f1``
"""
def __init__(self, *args, **kwargs):
super().__init__(average="micro", labels=[1], **kwargs)
self.name = "binary_f1"
@registry.register_metric("multilabel_f1")
class MultiLabelF1(F1):
| 64 | 64 | 81 | 19 | 45 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MultiLabelF1 | MultiLabelF1 | 778 | 787 | 778 | 779 | 4b39822a4e2b1debfa6aaa8d479d1a2795516b90 | bigcode/the-stack | train |
17910bc5d56ece7997f6e2f5 | train | class | @registry.register_metric("caption_bleu4")
class CaptionBleu4Metric(BaseMetric):
"""Metric for calculating caption accuracy using BLEU4 Score.
**Key:** ``caption_bleu4``
"""
def __init__(self):
import nltk.translate.bleu_score as bleu_score
self._bleu_score = bleu_score
super(... | @registry.register_metric("caption_bleu4")
class CaptionBleu4Metric(BaseMetric):
| """Metric for calculating caption accuracy using BLEU4 Score.
**Key:** ``caption_bleu4``
"""
def __init__(self):
import nltk.translate.bleu_score as bleu_score
self._bleu_score = bleu_score
super().__init__("caption_bleu4")
self.caption_processor = registry.get("coco_c... | , 1)[1]
# If more than 1
# If last dim is 1, we directly have class indices
if expected.dim() == 2 and expected.size(-1) != 1:
expected = torch.max(expected, 1)[1]
correct = (expected == output.squeeze()).sum().float()
total = len(expected)
value = correct ... | 108 | 108 | 361 | 19 | 88 | lilyli2004/mmf | mmf/modules/metrics.py | Python | CaptionBleu4Metric | CaptionBleu4Metric | 259 | 311 | 259 | 260 | 493ba230bdacf1ba8c4fcd9015a00be161fe246f | bigcode/the-stack | train |
8d23307818f10238c8249ab2 | train | class | @registry.register_metric("r@pk")
class RecallAtPrecisionK(BaseMetric):
"""Metric for calculating recall when precision is above a
particular threshold. Use `p_threshold` param to specify the
precision threshold i.e. k. Accepts precision in both 0-1
and 1-100 format.
**Key:** ``r@pk``
"""
... | @registry.register_metric("r@pk")
class RecallAtPrecisionK(BaseMetric):
| """Metric for calculating recall when precision is above a
particular threshold. Use `p_threshold` param to specify the
precision threshold i.e. k. Accepts precision in both 0-1
and 1-100 format.
**Key:** ``r@pk``
"""
def __init__(self, p_threshold, *args, **kwargs):
"""Initializat... | """
def __init__(self, *args, **kwargs):
super().__init__(average="micro", **kwargs)
self.name = "micro_ap"
@registry.register_metric("macro_ap")
class MacroAP(AveragePrecision):
"""Metric for calculating Macro Average Precision.
**Key:** ``macro_ap``
"""
def __init__(self, *ar... | 119 | 119 | 399 | 17 | 102 | lilyli2004/mmf | mmf/modules/metrics.py | Python | RecallAtPrecisionK | RecallAtPrecisionK | 972 | 1,022 | 972 | 973 | 8638cdc12680e5e54fff179f3af6aecc26cbaed7 | bigcode/the-stack | train |
208cb79187b97ca92c9fb7b8 | train | class | @registry.register_metric("mean_r")
class MeanRank(RecallAtK):
"""
Calculate MeanRank which specifies what was the average rank of the chosen
candidate.
**Key**: ``mean_r``.
"""
def __init__(self):
super().__init__("mean_r")
def calculate(self, sample_list, model_output, *args, **... | @registry.register_metric("mean_r")
class MeanRank(RecallAtK):
| """
Calculate MeanRank which specifies what was the average rank of the chosen
candidate.
**Key**: ``mean_r``.
"""
def __init__(self):
super().__init__("mean_r")
def calculate(self, sample_list, model_output, *args, **kwargs):
"""Calculate Mean Rank and return it back.
... | by DataLoader for
current iteration
model_output (Dict): Dict returned by model.
Returns:
torch.FloatTensor: Recall@10
"""
return self.calculate(sample_list, model_output, k=10)
@registry.register_metric("mean_r")
class MeanRank(RecallAt... | 64 | 64 | 156 | 16 | 48 | lilyli2004/mmf | mmf/modules/metrics.py | Python | MeanRank | MeanRank | 557 | 582 | 557 | 558 | 4cdaae7ec1e0ef29cfee6ea64548274115b8f8da | bigcode/the-stack | train |
feab92fba39a57d108e667dc | train | class | class KeyTransformFactory:
def __init__(self, key_name):
self.key_name = key_name
def __call__(self, *args, **kwargs):
return KeyTransform(self.key_name, *args, **kwargs)
| class KeyTransformFactory:
| def __init__(self, key_name):
self.key_name = key_name
def __call__(self, *args, **kwargs):
return KeyTransform(self.key_name, *args, **kwargs)
| ):
super().__init__(*args, **kwargs)
self.key_name = key_name
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "(%s -> '%s')" % (lhs, self.key_name), params
class KeyTransformFactory:
| 64 | 64 | 50 | 5 | 58 | aitoehigie/django | django/contrib/postgres/fields/hstore.py | Python | KeyTransformFactory | KeyTransformFactory | 92 | 98 | 92 | 93 | eacdea6a982aae0b0deec2e481be4c795c667edc | bigcode/the-stack | train |
bb6ca25f896cc7e5b73cd886 | train | class | @HStoreField.register_lookup
class ValuesTransform(Transform):
lookup_name = 'values'
function = 'avals'
output_field = ArrayField(TextField())
| @HStoreField.register_lookup
class ValuesTransform(Transform):
| lookup_name = 'values'
function = 'avals'
output_field = ArrayField(TextField())
| ):
return KeyTransform(self.key_name, *args, **kwargs)
@HStoreField.register_lookup
class KeysTransform(Transform):
lookup_name = 'keys'
function = 'akeys'
output_field = ArrayField(TextField())
@HStoreField.register_lookup
class ValuesTransform(Transform):
| 64 | 64 | 36 | 13 | 51 | aitoehigie/django | django/contrib/postgres/fields/hstore.py | Python | ValuesTransform | ValuesTransform | 108 | 112 | 108 | 109 | 702ddc4b29531fa643a0d59cb12f17089a0dcd2a | bigcode/the-stack | train |
96a3dd2c7df40f879372a96b | train | class | @HStoreField.register_lookup
class KeysTransform(Transform):
lookup_name = 'keys'
function = 'akeys'
output_field = ArrayField(TextField())
| @HStoreField.register_lookup
class KeysTransform(Transform):
| lookup_name = 'keys'
function = 'akeys'
output_field = ArrayField(TextField())
|
class KeyTransformFactory:
def __init__(self, key_name):
self.key_name = key_name
def __call__(self, *args, **kwargs):
return KeyTransform(self.key_name, *args, **kwargs)
@HStoreField.register_lookup
class KeysTransform(Transform):
| 64 | 64 | 36 | 13 | 51 | aitoehigie/django | django/contrib/postgres/fields/hstore.py | Python | KeysTransform | KeysTransform | 101 | 105 | 101 | 102 | 763b680ed222b8d2ef568b806fe4e7331c909d8d | bigcode/the-stack | train |
23f8dff60fd45069b876df25 | train | class | class HStoreField(CheckFieldDefaultMixin, Field):
empty_strings_allowed = False
description = _('Map of strings to strings/nulls')
default_error_messages = {
'not_a_string': _('The value of “%(key)s” is not a string or null.'),
}
_default_hint = ('dict', '{}')
def db_type(self, connecti... | class HStoreField(CheckFieldDefaultMixin, Field):
| empty_strings_allowed = False
description = _('Map of strings to strings/nulls')
default_error_messages = {
'not_a_string': _('The value of “%(key)s” is not a string or null.'),
}
_default_hint = ('dict', '{}')
def db_type(self, connection):
return 'hstore'
def get_transfor... | import json
from django.contrib.postgres import forms, lookups
from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, TextField, Transform
from django.utils.translation import gettext_lazy as _
from .mixins import CheckFieldDefaultMixin
__al... | 83 | 109 | 366 | 11 | 72 | aitoehigie/django | django/contrib/postgres/fields/hstore.py | Python | HStoreField | HStoreField | 14 | 70 | 14 | 14 | 8c737b5d7db839f4221061d9689012234761cf39 | bigcode/the-stack | train |
48b0a956fc33fa643a01986f | train | class | class KeyTransform(Transform):
output_field = TextField()
def __init__(self, key_name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.key_name = key_name
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "(%s -> '%s')" % (lhs,... | class KeyTransform(Transform):
| output_field = TextField()
def __init__(self, key_name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.key_name = key_name
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "(%s -> '%s')" % (lhs, self.key_name), params
|
HStoreField.register_lookup(lookups.DataContains)
HStoreField.register_lookup(lookups.ContainedBy)
HStoreField.register_lookup(lookups.HasKey)
HStoreField.register_lookup(lookups.HasKeys)
HStoreField.register_lookup(lookups.HasAnyKeys)
class KeyTransform(Transform):
| 64 | 64 | 87 | 6 | 58 | aitoehigie/django | django/contrib/postgres/fields/hstore.py | Python | KeyTransform | KeyTransform | 80 | 89 | 80 | 80 | 30dc062617e25403b344b988a04fa143607843ce | bigcode/the-stack | train |
a9f9b1fa53be278061c0252e | train | function | def doc2pdf(input_path, output_path):
w = Dispatch("Word.Application")
try:
doc = w.Documents.Open(input_path, ReadOnly=1)
doc.ExportAsFixedFormat(output_path, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
... | def doc2pdf(input_path, output_path):
| w = Dispatch("Word.Application")
try:
doc = w.Documents.Open(input_path, ReadOnly=1)
doc.ExportAsFixedFormat(output_path, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCre... | 8 -*-
# @Time : 2018/3/21 16:07
# @Author : Jedrek
# -*- coding:utf-8 -*-
import sys
import os
from win32com.client import Dispatch, constants, gencache
def doc2pdf(input_path, output_path):
| 64 | 64 | 103 | 10 | 53 | JedrekWang/graduation | src/main/java/com/jedrek/graduation/utils/word_to_pdf.py | Python | doc2pdf | doc2pdf | 13 | 25 | 13 | 13 | f498a20ff6da3961f8392d01ca088a8a9035d7ee | bigcode/the-stack | train |
ffb3a418385699e77db9f82c | train | function | def generate_support():
# enable python COM support for Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
| def generate_support():
# enable python COM support for Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
| gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
| 0
except Exception:
return 1
finally:
w.Quit(constants.wdDoNotSaveChanges)
def generate_support():
# enable python COM support for Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
| 64 | 64 | 72 | 38 | 26 | JedrekWang/graduation | src/main/java/com/jedrek/graduation/utils/word_to_pdf.py | Python | generate_support | generate_support | 28 | 31 | 28 | 30 | fc81a3307c6a58e922692b283b2d63c152262f61 | bigcode/the-stack | train |
6b9149f46ef8b87f98d8b4a8 | train | function | def main():
if len(sys.argv) == 2:
input_path = sys.argv[1]
output_path = os.path.splitext(input_path)[0] + '.pdf'
elif len(sys.argv) == 3:
input_path = sys.argv[1]
output_path = sys.argv[2]
else:
input_path = u'C:\\Users\\wangjie22438\\Desktop\\testdoc.doc' # word文档... | def main():
| if len(sys.argv) == 2:
input_path = sys.argv[1]
output_path = os.path.splitext(input_path)[0] + '.pdf'
elif len(sys.argv) == 3:
input_path = sys.argv[1]
output_path = sys.argv[2]
else:
input_path = u'C:\\Users\\wangjie22438\\Desktop\\testdoc.doc' # word文档的名称
... | Word 2007
# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
def main():
| 64 | 64 | 198 | 3 | 61 | JedrekWang/graduation | src/main/java/com/jedrek/graduation/utils/word_to_pdf.py | Python | main | main | 34 | 53 | 34 | 34 | 596c3f3ed6239a15a6a121a1e9dbbf018bf9f45a | bigcode/the-stack | train |
a41ade259827640d676aea82 | train | class | class TestAddressContextFilter(unittest.TestCase):
def test_url_context(self):
context = 'url'
addr = '192.168.1.1'
self.assertEqual(put_address_in_context(addr, context),
addr)
addr = 'www.example.com'
self.assertEqual(put_address_in_context(addr, c... | class TestAddressContextFilter(unittest.TestCase):
| def test_url_context(self):
context = 'url'
addr = '192.168.1.1'
self.assertEqual(put_address_in_context(addr, context),
addr)
addr = 'www.example.com'
self.assertEqual(put_address_in_context(addr, context),
addr)
addr... | language governing permissions and
# limitations under the License.
import unittest
import jinja2
from kolla_ansible.exception import FilterError
from kolla_ansible.kolla_address import kolla_address
from kolla_ansible.put_address_in_context import put_address_in_context
class TestAddressContextFilter(unittest.Test... | 66 | 66 | 223 | 9 | 56 | me450722457/kolla-ansible | kolla_ansible/tests/unit/test_address_filters.py | Python | TestAddressContextFilter | TestAddressContextFilter | 26 | 53 | 26 | 27 | e7d9cd251c1c933d6b33654f1e357ca2e0dc7df8 | bigcode/the-stack | train |
50ace2916c36b4678fff948f | train | class | class TestKollaAddressFilter(unittest.TestCase):
def setUp(self):
# Bandit complains about Jinja2 autoescaping without nosec.
self.env = jinja2.Environment() # nosec
def _make_context(self, parent):
return self.env.context_class(
self.env, parent=parent, name='dummy', bloc... | class TestKollaAddressFilter(unittest.TestCase):
| def setUp(self):
# Bandit complains about Jinja2 autoescaping without nosec.
self.env = jinja2.Environment() # nosec
def _make_context(self, parent):
return self.env.context_class(
self.env, parent=parent, name='dummy', blocks={})
def test_missing_config(self):
... | _in_context
class TestAddressContextFilter(unittest.TestCase):
def test_url_context(self):
context = 'url'
addr = '192.168.1.1'
self.assertEqual(put_address_in_context(addr, context),
addr)
addr = 'www.example.com'
self.assertEqual(put_address_in_c... | 236 | 236 | 789 | 10 | 226 | me450722457/kolla-ansible | kolla_ansible/tests/unit/test_address_filters.py | Python | TestKollaAddressFilter | TestKollaAddressFilter | 56 | 187 | 56 | 57 | ba782de484086e66dd56d9cbe0884c7c5ad9b285 | bigcode/the-stack | train |
44dbd121cf6085760d201668 | train | function | def get_driver():
options = webdriver.ChromeOptions()
options.add_argument('disable-infobars')
options.add_argument('start-maximized')
options.add_argument('disable-dev-shm-usage') #mainly for linux
options.add_argument('no-sandbox')
options.add_experimental_option('excludeSwitches', ['enable-au... | def get_driver():
| options = webdriver.ChromeOptions()
options.add_argument('disable-infobars')
options.add_argument('start-maximized')
options.add_argument('disable-dev-shm-usage') #mainly for linux
options.add_argument('no-sandbox')
options.add_experimental_option('excludeSwitches', ['enable-automation'])
op... | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 8 19:05:59 2022
@author: scyth
"""
from selenium import webdriver
def get_driver():
| 41 | 64 | 122 | 4 | 36 | aniketnaikdesai/anik-lib | selenium/simple_text_scraping/main.py | Python | get_driver | get_driver | 10 | 20 | 10 | 10 | 5b44a5e164fcb86d0a683f237c8ed53710fbb04a | bigcode/the-stack | train |
14d9de842558d4894a3e4e68 | train | function | def main():
driver = get_driver()
element = driver.find_element(by='xpath',value='/html/body/div[1]/div/h1[1]')
return element.text
| def main():
| driver = get_driver()
element = driver.find_element(by='xpath',value='/html/body/div[1]/div/h1[1]')
return element.text
| perimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('disable-blink-features=AutomationControlled')
driver = webdriver.Chrome('C:/webdriver/chromedriver.exe',options=options)
driver.get('http://automated.pythonanywhere.com')
return driver
def main():
| 64 | 64 | 38 | 3 | 60 | aniketnaikdesai/anik-lib | selenium/simple_text_scraping/main.py | Python | main | main | 23 | 26 | 23 | 23 | 5c994d89b2895a60b024ca8d167fb5736a494aaa | bigcode/the-stack | train |
7d01ac004b7494355ccfe580 | train | class | class Debug(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.error = '<:xmark:674359427830382603>'
self.check = '<:check:674359197378281472>'
self.admin_cmds = ['plonk', 'unplonk', 'guilds']
self.common_perms = [
'attach_files',
'read_messag... | class Debug(commands.Cog):
| def __init__(self, bot):
self.bot = bot
self.error = '<:xmark:674359427830382603>'
self.check = '<:check:674359197378281472>'
self.admin_cmds = ['plonk', 'unplonk', 'guilds']
self.common_perms = [
'attach_files',
'read_message_history',
'ex... | without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice sh... | 185 | 185 | 617 | 6 | 178 | TAG-Epic/bot | commands/debug.py | Python | Debug | Debug | 25 | 89 | 25 | 25 | 4b9afaa4668343563743aed00db46e1e495ac2d2 | bigcode/the-stack | train |
fdfd0b99e5d6b612c35c159e | train | function | def setup(bot):
try:
bot.add_cog(Debug(bot))
bot.logger.info(f'$GREENLoaded $CYAN"debug" $GREENcommand!')
except Exception as e:
# errortb = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
bot.logger.error(f'$REDError while adding command $CYAN"debug"', exc_info=... | def setup(bot):
| try:
bot.add_cog(Debug(bot))
bot.logger.info(f'$GREENLoaded $CYAN"debug" $GREENcommand!')
except Exception as e:
# errortb = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
bot.logger.error(f'$REDError while adding command $CYAN"debug"', exc_info=e)
| .utcnow(),
description='\n'.join(detail)
)
if ctx.me.permissions_in(ctx.channel).embed_links:
return await ctx.send(embed=embed)
else:
detail.append(f'{self.error} Fire cannot send embeds')
return await ctx.send('\n'.join(detail))
def setup(bot):
| 64 | 64 | 83 | 4 | 60 | TAG-Epic/bot | commands/debug.py | Python | setup | setup | 92 | 98 | 92 | 92 | 9393f80164e692256999f9765c540877da6e5946 | bigcode/the-stack | train |
785931a9e6e8e570fe16fce9 | train | class | class TestCase(TestBase):
def setup(self):
case_name = "test_auto_invert_001"
case_path = os.getcwd()
self.params_init(case_name, case_path)
self.caseresult = True
self._log.info("============= {0} Setup case============".format(self.casename))
self.testarg = [
... | class TestCase(TestBase):
| def setup(self):
case_name = "test_auto_invert_001"
case_path = os.getcwd()
self.params_init(case_name, case_path)
self.caseresult = True
self._log.info("============= {0} Setup case============".format(self.casename))
self.testarg = [
#caseflag,testfuncna... | permissions and
# limitations under the License.
"""
################################################
Testcase_PrepareCondition:
Testcase_TestSteps:
Testcase_ExpectedResult:
"""
import datetime
import os
import pytest
from base import TestBase
from nose.plugins.attrib import attr
from test_run.invert_run import i... | 85 | 85 | 286 | 6 | 78 | laekov/akg | tests/operators/vector/test_invert_001.py | Python | TestCase | TestCase | 37 | 63 | 37 | 38 | 67a6daa782e728c5bc876d81c2102bb5f9811602 | bigcode/the-stack | train |
ba3acd067aef6f1876870987 | train | class | class Migration(migrations.Migration):
dependencies = [
('smarttm_web', '0012_auto_20190502_1604'),
]
operations = [
migrations.AddField(
model_name='member',
name='status',
field=models.BooleanField(default=True),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('smarttm_web', '0012_auto_20190502_1604'),
]
operations = [
migrations.AddField(
model_name='member',
name='status',
field=models.BooleanField(default=True),
),
]
| # Generated by Django 2.2 on 2019-05-02 12:20
from django.db import migrations, models
class Migration(migrations.Migration):
| 36 | 64 | 63 | 7 | 28 | mseemab/smarttm | smarttm_web/migrations/0013_member_status.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | 548745086d0d941af398edbc8fe16549e1700d79 | bigcode/the-stack | train |
bf513eda8a3d3853051386c3 | train | function | def deconstruct(value):
stack_name, output_name = value.split("::")
return Output(stack_name, output_name)
| def deconstruct(value):
| stack_name, output_name = value.split("::")
return Output(stack_name, output_name)
| Error('Context is required')
d = deconstruct(value)
stack_fqn = d.stack_name
if not fqn:
stack_fqn = context.get_fqn(d.stack_name)
output = provider.get_output(stack_fqn, d.output_name)
return output
def deconstruct(value):
| 64 | 64 | 26 | 5 | 58 | GoodRx/stacker | stacker/lookups/handlers/output.py | Python | deconstruct | deconstruct | 39 | 41 | 39 | 39 | 6b391b97a3b5a625ecfd21d0021bdbcd5941adb2 | bigcode/the-stack | train |
39cdbb1c941430d48f141b73 | train | function | def handler(value, provider=None, context=None, fqn=False, **kwargs):
"""Fetch an output from the designated stack.
Args:
value (str): string with the following format:
<stack_name>::<output_name>, ie. some-stack::SomeOutput
provider (:class:`stacker.provider.base.BaseProvider`): su... | def handler(value, provider=None, context=None, fqn=False, **kwargs):
| """Fetch an output from the designated stack.
Args:
value (str): string with the following format:
<stack_name>::<output_name>, ie. some-stack::SomeOutput
provider (:class:`stacker.provider.base.BaseProvider`): subclass of the
base provider
context (:class:`stack... | from collections import namedtuple
TYPE_NAME = "output"
Output = namedtuple("Output", ("stack_name", "output_name"))
def handler(value, provider=None, context=None, fqn=False, **kwargs):
| 44 | 67 | 226 | 17 | 27 | GoodRx/stacker | stacker/lookups/handlers/output.py | Python | handler | handler | 8 | 36 | 8 | 8 | 93a01268797d2f86032f6eb999f0121d15f3ab14 | bigcode/the-stack | train |
f074023817e1bc61b6d3c783 | train | class | class Part(ABC):
def __init__(self, name: str = "Unknown Part"):
self.name = name
self.logger = logging.getLogger(name)
def run_threaded(self, should_continue):
"""This method will be run in parallel"""
while True:
self.run_step()
if should_continue() is ... | class Part(ABC):
| def __init__(self, name: str = "Unknown Part"):
self.name = name
self.logger = logging.getLogger(name)
def run_threaded(self, should_continue):
"""This method will be run in parallel"""
while True:
self.run_step()
if should_continue() is False:
... | from abc import ABC, abstractmethod
import logging
class Part(ABC):
| 16 | 64 | 122 | 5 | 10 | fedepal450/ROAR-RL_FullControl | ROAR_Jetson/part.py | Python | Part | Part | 5 | 25 | 5 | 5 | ee5b166e9051e77456c3e18fb3a221ea19761177 | bigcode/the-stack | train |
ff0661f323ace0036706b412 | train | function | def t_CPP_WS(t):
r'\s+'
t.lexer.lineno += t.value.count("\n")
return t
| def t_CPP_WS(t):
| r'\s+'
t.lexer.lineno += t.value.count("\n")
return t
| _STRING', 'CPP_CHAR', 'CPP_WS', 'CPP_COMMENT1', 'CPP_COMMENT2', 'CPP_POUND','CPP_DPOUND'
)
literals = "+-*/%|&~^<>=!?()[]{}.,;:\\\'\""
# Whitespace
def t_CPP_WS(t):
| 64 | 64 | 29 | 6 | 57 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_CPP_WS | t_CPP_WS | 61 | 64 | 61 | 61 | 50085c218988fafd303da1a6e67b0a2e3dd4e8a7 | bigcode/the-stack | train |
5bed55c53cc3ed876d1e4ecd | train | class | class Preprocessor(object):
def __init__(self,lexer=None):
if lexer is None:
lexer = lex.lexer
self.lexer = lexer
self.macros = { }
self.path = []
self.temp_path = []
# Probe the lexer for selected tokens
self.lexprobe()
tm = time.localti... | class Preprocessor(object):
| def __init__(self,lexer=None):
if lexer is None:
lexer = lex.lexer
self.lexer = lexer
self.macros = { }
self.path = []
self.temp_path = []
# Probe the lexer for selected tokens
self.lexprobe()
tm = time.localtime()
self.define("__... | igraph(input):
return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input)
# ------------------------------------------------------------------
# Macro object
#
# This object holds information about preprocessor macros
#
# .name - Macro name (string)
# .value - Macro value (a list of toke... | 256 | 256 | 5,585 | 5 | 251 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | Preprocessor | Preprocessor | 187 | 927 | 187 | 187 | 1c46ddcd83dc4e97276a9d870a9dac8073b3bcc4 | bigcode/the-stack | train |
3ee5d75e3aeb320638078688 | train | function | def CPP_INTEGER(t):
r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)'
return t
| def CPP_INTEGER(t):
| r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)'
return t
| .lexer.lineno += t.value.count("\n")
return t
t_CPP_POUND = r'\#'
t_CPP_DPOUND = r'\#\#'
# Identifier
t_CPP_ID = r'[A-Za-z_][\w_]*'
# Integer literal
def CPP_INTEGER(t):
| 64 | 64 | 57 | 5 | 58 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | CPP_INTEGER | CPP_INTEGER | 73 | 75 | 73 | 73 | 0648a69a941e331f49dc90074bece7daeabd8a0c | bigcode/the-stack | train |
2b0d905b8e102bcca745285b | train | function | def t_error(t):
t.type = t.value[0]
t.value = t.value[0]
t.lexer.skip(1)
return t
| def t_error(t):
| t.type = t.value[0]
t.value = t.value[0]
t.lexer.skip(1)
return t
| cr if ncr else ' '
return t
# Line comment
def t_CPP_COMMENT2(t):
r'(//.*?(\n|$))'
# replace with '/n'
t.type = 'CPP_WS'; t.value = '\n'
return t
def t_error(t):
| 64 | 64 | 35 | 5 | 58 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_error | t_error | 110 | 114 | 110 | 110 | 5ec07519e5d6cf2a39ad3cf70e198d7e9965c5ee | bigcode/the-stack | train |
deaa29c55acc9b7478162de5 | train | function | def t_CPP_COMMENT2(t):
r'(//.*?(\n|$))'
# replace with '/n'
t.type = 'CPP_WS'; t.value = '\n'
return t
| def t_CPP_COMMENT2(t):
| r'(//.*?(\n|$))'
# replace with '/n'
t.type = 'CPP_WS'; t.value = '\n'
return t
| ("\n")
t.lexer.lineno += ncr
# replace with one space or a number of '\n'
t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
return t
# Line comment
def t_CPP_COMMENT2(t):
| 64 | 64 | 44 | 7 | 56 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_CPP_COMMENT2 | t_CPP_COMMENT2 | 104 | 108 | 104 | 104 | 04ea24b127138c78992b5ccd490a40cd4323b38f | bigcode/the-stack | train |
6c47d1636a30bbd7b2327e49 | train | class | class Macro(object):
def __init__(self,name,value,arglist=None,variadic=False):
self.name = name
self.value = value
self.arglist = arglist
self.variadic = variadic
if variadic:
self.vararg = arglist[-1]
self.source = None
| class Macro(object):
| def __init__(self,name,value,arglist=None,variadic=False):
self.name = name
self.value = value
self.arglist = arglist
self.variadic = variadic
if variadic:
self.vararg = arglist[-1]
self.source = None
| indicating whether or not variadic macro
# .vararg - Name of the variadic parameter
#
# When a macro is created, the macro replacement token sequence is
# pre-scanned and used to create patch lists that are later used
# during macro expansion
# ------------------------------------------------------------------
c... | 64 | 64 | 70 | 4 | 60 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | Macro | Macro | 170 | 178 | 170 | 170 | b9d47b6511b393fbb74a3c8c1d836519b99dd6d6 | bigcode/the-stack | train |
c9f15c0096e3f4bb861da52a | train | function | def t_CPP_CHAR(t):
r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
t.lexer.lineno += t.value.count("\n")
return t
| def t_CPP_CHAR(t):
| r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
t.lexer.lineno += t.value.count("\n")
return t
| '
# String literal
def t_CPP_STRING(t):
r'\"([^\\\n]|(\\(.|\n)))*?\"'
t.lexer.lineno += t.value.count("\n")
return t
# Character constant 'c' or L'c'
def t_CPP_CHAR(t):
| 64 | 64 | 44 | 6 | 58 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_CPP_CHAR | t_CPP_CHAR | 89 | 92 | 89 | 89 | 19ccafcdd5a800d05afea02e2f17712c2ea59829 | bigcode/the-stack | train |
9dda0ae19ac197b2b820d947 | train | function | def trigraph(input):
return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input)
| def trigraph(input):
| return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input)
| (\)\!<>\-]''')
_trigraph_rep = {
'=':'#',
'/':'\\',
"'":'^',
'(':'[',
')':']',
'!':'|',
'<':'{',
'>':'}',
'-':'~'
}
def trigraph(input):
| 64 | 64 | 27 | 5 | 59 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | trigraph | trigraph | 151 | 152 | 151 | 151 | 96f0e7f660acc046411ab69a6f070d2231eb0dc8 | bigcode/the-stack | train |
f844697117524bc211c080f4 | train | function | def t_CPP_COMMENT1(t):
r'(/\*(.|\n)*?\*/)'
ncr = t.value.count("\n")
t.lexer.lineno += ncr
# replace with one space or a number of '\n'
t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
return t
| def t_CPP_COMMENT1(t):
| r'(/\*(.|\n)*?\*/)'
ncr = t.value.count("\n")
t.lexer.lineno += ncr
# replace with one space or a number of '\n'
t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' '
return t
| Character constant 'c' or L'c'
def t_CPP_CHAR(t):
r'(L)?\'([^\\\n]|(\\(.|\n)))*?\''
t.lexer.lineno += t.value.count("\n")
return t
# Comment
def t_CPP_COMMENT1(t):
| 64 | 64 | 79 | 7 | 56 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_CPP_COMMENT1 | t_CPP_COMMENT1 | 95 | 101 | 95 | 95 | 9cd3b47d341263cd9cdba817b43d051b6a208122 | bigcode/the-stack | train |
83cbeddb09e53d7d2e9536b5 | train | function | def t_CPP_STRING(t):
r'\"([^\\\n]|(\\(.|\n)))*?\"'
t.lexer.lineno += t.value.count("\n")
return t
| def t_CPP_STRING(t):
| r'\"([^\\\n]|(\\(.|\n)))*?\"'
t.lexer.lineno += t.value.count("\n")
return t
|
# Floating literal
t_CPP_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?'
# String literal
def t_CPP_STRING(t):
| 64 | 64 | 42 | 6 | 57 | tianhao13/ngkchain | libraries/ngk-vm/external/outcome/include/outcome/quickcpplib/pcpp/pcpp/ply/ply/cpp.py | Python | t_CPP_STRING | t_CPP_STRING | 83 | 86 | 83 | 83 | 4dd705fab7e7044b2dd15641004821858ba832ab | bigcode/the-stack | train |
5d14057ed877e529ba4938e9 | train | function | def test_unpack_from():
b = bytebuffer(19)
sz = struct.calcsize("ii")
b[2:2+sz] = struct.pack("ii", 17, 42)
assert struct.unpack_from("ii", b, 2) == (17, 42)
b[:sz] = struct.pack("ii", 18, 43)
assert struct.unpack_from("ii", b) == (18, 43) | def test_unpack_from():
| b = bytebuffer(19)
sz = struct.calcsize("ii")
b[2:2+sz] = struct.pack("ii", 17, 42)
assert struct.unpack_from("ii", b, 2) == (17, 42)
b[:sz] = struct.pack("ii", 18, 43)
assert struct.unpack_from("ii", b) == (18, 43) | x00' * 2 +
struct.pack("ii", 17, 42) +
b'\x00' * (19-sz-2))
m = memoryview(b)
struct.pack_into("ii", m, 2, 17, 42)
def test_unpack_from():
| 64 | 64 | 97 | 5 | 59 | olliemath/pypy | pypy/module/struct/test/apptest_structbuffer.py | Python | test_unpack_from | test_unpack_from | 19 | 25 | 19 | 19 | 8d8ad9a1b618c2aa8eff6d534337602a82e43f5d | bigcode/the-stack | train |
60b339f55e629823398c809a | train | function | def test_pack_into():
b = bytebuffer(19)
sz = struct.calcsize("ii")
struct.pack_into("ii", b, 2, 17, 42)
assert b[:] == (b'\x00' * 2 +
struct.pack("ii", 17, 42) +
b'\x00' * (19-sz-2))
m = memoryview(b)
struct.pack_into("ii", m, 2, 17, 42)
| def test_pack_into():
| b = bytebuffer(19)
sz = struct.calcsize("ii")
struct.pack_into("ii", b, 2, 17, 42)
assert b[:] == (b'\x00' * 2 +
struct.pack("ii", 17, 42) +
b'\x00' * (19-sz-2))
m = memoryview(b)
struct.pack_into("ii", m, 2, 17, 42)
| """
Tests for the struct module implemented at interp-level in pypy/module/struct.
"""
# spaceconfig = {"usemodules": ["struct", "__pypy__"]}
import struct
from __pypy__ import bytebuffer
def test_pack_into():
| 51 | 64 | 107 | 5 | 45 | olliemath/pypy | pypy/module/struct/test/apptest_structbuffer.py | Python | test_pack_into | test_pack_into | 9 | 17 | 9 | 9 | bd708fbe0fdb1b8c7547962e8003200b6561ae96 | bigcode/the-stack | train |
7526325b966b12e6daa81132 | train | function | def progressbar(iterable, prefix="", size=50, file=sys.stdout):
"""
Show a progress bar for loop calculations
Keywords:
iterable --> iterable for which the bar has to be displayed
prefix --> any text you wish to write before the bar
size --> bar width
file --> file objects for standard outp... | def progressbar(iterable, prefix="", size=50, file=sys.stdout):
| """
Show a progress bar for loop calculations
Keywords:
iterable --> iterable for which the bar has to be displayed
prefix --> any text you wish to write before the bar
size --> bar width
file --> file objects for standard output
"""
count = len(iterable)
def show(j):
x ... | import sys
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def progressbar(iterable, prefix="", size=50, file=sys.stdout):
| 38 | 64 | 167 | 16 | 21 | viventriglia/Cov19_DeepLearning_forecast | helper_func.py | Python | progressbar | progressbar | 7 | 27 | 7 | 7 | bf15d206e184797fa982a65a617c8fa5725cc04e | bigcode/the-stack | train |
0ccf730133ede29bde00c814 | train | function | def data_by_region(region_name):
"""
Return a DataFrame with up-to-date figures from Protezione Civile's GitHub
Keyword:
region_name --> str, name of the region
"""
# Feed web-data into pandas, down-selecting a region and formatting the date
ts = pd.read_csv(
'https://raw.githubuser... | def data_by_region(region_name):
| """
Return a DataFrame with up-to-date figures from Protezione Civile's GitHub
Keyword:
region_name --> str, name of the region
"""
# Feed web-data into pandas, down-selecting a region and formatting the date
ts = pd.read_csv(
'https://raw.githubusercontent.com/pcm-dpc/COVID-19/mast... | def show(j):
x = int(size*j/count)
file.write("%s[%s%s] %i%%\r" % (prefix, "#"*x, "."*(size-x), int(100*j/count)))
file.flush()
show(0)
for i, item in enumerate(iterable):
yield item
show(i+1)
file.write("\n")
file.flush()
def data_by_region(region_name):... | 93 | 93 | 313 | 7 | 86 | viventriglia/Cov19_DeepLearning_forecast | helper_func.py | Python | data_by_region | data_by_region | 29 | 49 | 29 | 29 | 0b49ed21775656f37fbb6bdacbcb12bb2109cab7 | bigcode/the-stack | train |
9ea03f55f18817963e74072c | train | function | def plot_smooth(region, type=None, time_window=21, smooth_window=7, save=False):
"""
Plot different kind of data (daily infections, deaths or ICU admissions), together with a forward-backward EMA to filter fluctuations out
Keywords:
region --> DataFrame, output from data_by_region()
type --> str; '... | def plot_smooth(region, type=None, time_window=21, smooth_window=7, save=False):
| """
Plot different kind of data (daily infections, deaths or ICU admissions), together with a forward-backward EMA to filter fluctuations out
Keywords:
region --> DataFrame, output from data_by_region()
type --> str; 'positivi' (new infections), 'deceduti' (deaths), 'TI' (ICU admissions) or 'positi... | pc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv')
regione = ts[ts['denominazione_regione'] == region_name.title()].drop(columns=['stato', 'codice_regione', 'lat', 'long'])
regione['data'] = pd.to_datetime(regione.data).dt.strftime('%d-%m-%y')
# Add columns for daily fatalities, swabs and positi... | 256 | 256 | 884 | 22 | 233 | viventriglia/Cov19_DeepLearning_forecast | helper_func.py | Python | plot_smooth | plot_smooth | 51 | 105 | 51 | 51 | 2e9aaa5ccd778a55e793c66dc18f9ae36906c79b | bigcode/the-stack | train |
31a6e3b2f9aaa9f205cc1cc8 | train | function | def mad(arr):
"""Median Absolute Deviation: a robust version of standard deviation"""
arr = np.ma.array(arr).compressed() # a (compressed) masked array is a quick way to avoid NaNs
med = np.median(arr)
return np.median(np.abs(arr - med)) | def mad(arr):
| """Median Absolute Deviation: a robust version of standard deviation"""
arr = np.ma.array(arr).compressed() # a (compressed) masked array is a quick way to avoid NaNs
med = np.median(arr)
return np.median(np.abs(arr - med)) | {time_window} giorni)')
if save:
plt.savefig(f'{type}_{region.denominazione_regione.iloc[0]}_tw={time_window}_sw={smooth_window}.png',
dpi=300, bbox_inches='tight', facecolor='white')
plt.show()
def mad(arr):
| 64 | 64 | 64 | 4 | 60 | viventriglia/Cov19_DeepLearning_forecast | helper_func.py | Python | mad | mad | 107 | 111 | 107 | 107 | ab40bae7e67428e380fe362d98940ff6f6e28531 | bigcode/the-stack | train |
c305528677fb79cd34143b6d | train | function | def _xmesh(T, scheme, iter=None):
"""
Creates the subdivision matrix of the given topology tensor w.r.t. the input scheme.
Parameters
----------
T : LongTensor
the topology tensor
scheme : (numpy.ndarray, int)
the subdivision scheme with the resulting polygons sides
iter : i... | def _xmesh(T, scheme, iter=None):
| """
Creates the subdivision matrix of the given topology tensor w.r.t. the input scheme.
Parameters
----------
T : LongTensor
the topology tensor
scheme : (numpy.ndarray, int)
the subdivision scheme with the resulting polygons sides
iter : int (optional)
the number o... | import numpy
from ..utility.col import *
from ..utility.flatten import *
from ..utility.transpose import *
from ..utility.repelem import *
from ..utility.torch2numpy import *
from .ispoly import *
def _xmesh(T, scheme, iter=None):
| 59 | 114 | 381 | 11 | 48 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | _xmesh | _xmesh | 10 | 52 | 10 | 10 | 9b3502d8a9d3d31ac3880329956499d2a2697fca | bigcode/the-stack | train |
42c3cf6d2bba8e2c989f3230 | train | function | def xtri2quad(T, *args, **kwargs):
"""
Creates the subdivision matrix for transforming a triangle topology into a quad one
Parameters
----------
T : LongTensor
the (3,N,) topology tensor
Returns
-------
(Tensor,LongTensor)
the subdivision matrix and the new (4,M,) topol... | def xtri2quad(T, *args, **kwargs):
| """
Creates the subdivision matrix for transforming a triangle topology into a quad one
Parameters
----------
T : LongTensor
the (3,N,) topology tensor
Returns
-------
(Tensor,LongTensor)
the subdivision matrix and the new (4,M,) topology tensor
Raises
------
... | [k, k, l, l], [i, j, k, l], [k, k, j, j],
[l, l, l, l], [l, l, i, i], [i, j, k, l], [l, l, k, k]]), 4)
return _xmesh(T, scheme, iter=iter)
def xtri2quad(T, *args, **kwargs):
| 94 | 94 | 316 | 13 | 81 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xtri2quad | xtri2quad | 155 | 184 | 155 | 155 | c31963b548be634374b93e5be9c3eb265c639cdf | bigcode/the-stack | train |
396d6d3c198685e26b646c19 | train | function | def xtri(T, iter=None):
"""
Creates the naive subdivision matrix for a triangle topology.
Parameters
----------
T : LongTensor
the (3,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
... | def xtri(T, iter=None):
| """
Creates the naive subdivision matrix for a triangle topology.
Parameters
----------
T : LongTensor
the (3,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(Tensor,LongTensor)
... | be an edge topology'
i = 0
j = 1
scheme = (numpy.array([[i, i], [i, j],
[j, i], [j, j],]), 2)
return _xmesh(T, scheme, iter=iter)
def xtri(T, iter=None):
| 69 | 69 | 232 | 8 | 61 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xtri | xtri | 86 | 117 | 86 | 86 | 6a1765c42713f598dbd1ffe9d38e6e079f22b528 | bigcode/the-stack | train |
390ac97ef3f87633e4d25eeb | train | function | def xtet(T, iter=None):
"""
Creates the naive subdivision matrix for a tetrahedra topology.
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
... | def xtet(T, iter=None):
| """
Creates the naive subdivision matrix for a tetrahedra topology.
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(Tensor,LongTensor)
... | i, j, j, k, k], [j, j, j, i, i, i],
[k, k, k, k, k, k], [k, k, k, i, i, i], [i, i, j, j, k, k], [k, k, k, j, j, j]]), 4)
iter = 1
return _xmesh(T, scheme, iter)
def xtet(T, iter=None):
| 105 | 105 | 352 | 8 | 97 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xtet | xtet | 187 | 225 | 187 | 187 | a037a5fad36a4604ccc011c368122f8fa406f02d | bigcode/the-stack | train |
6aa6b001f90e8dd6ae2bd7a8 | train | function | def xedge(T, iter=None):
"""
Creates the naive subdivision matrix for a triangle topology.
Parameters
----------
T : LongTensor
the (2,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
... | def xedge(T, iter=None):
| """
Creates the naive subdivision matrix for a triangle topology.
Parameters
----------
T : LongTensor
the (2,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(Tensor,LongTensor)
... | t = transpose(numpy.reshape(idx(0, row(M)), (row(M) // scheme[1], scheme[1])))
return numpy2torch(M, dtype=torch.float, device=T.device), \
numpy2torch(t, dtype=torch.long, device=T.device)
def xedge(T, iter=None):
| 64 | 64 | 184 | 8 | 56 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xedge | xedge | 55 | 83 | 55 | 55 | fe9f2eb94f000550d15fc6be0f605ed0f00c2bee | bigcode/the-stack | train |
edddc8908c779e2ca91e1c92 | train | function | def xhex(T, iter=None):
"""
Creates the naive subdivision matrix for a hexaedra topology.
Parameters
----------
T : LongTensor
the (8,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
... | def xhex(T, iter=None):
| """
Creates the naive subdivision matrix for a hexaedra topology.
Parameters
----------
T : LongTensor
the (8,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(Tensor,LongTensor)
... | if topology is not a valid tetrahedra topology
"""
assert istet(T), 'Input topology must be a tetrahedra topology'
i = 0
j = 1
k = 2
l = 3
scheme = (numpy.array([[i, i], [i, j], [i, k], [i, l],
[j, j], [j, l], [j, k], [j, i],
[k, k], [... | 256 | 256 | 1,327 | 8 | 248 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xhex | xhex | 228 | 302 | 228 | 228 | e06b3d0fbc28bd4e3557dee4d12536daf8b63929 | bigcode/the-stack | train |
5079966c09da24116c3a6021 | train | function | def xquad(T, iter=None):
"""
Creates the naive subdivision matrix for a quad topology.
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(T... | def xquad(T, iter=None):
| """
Creates the naive subdivision matrix for a quad topology.
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
iter : int (optional)
the number of iteration to perform. No iteration if None (default is None)
Returns
-------
(Tensor,LongTensor)
... | 2
scheme = (numpy.array([[i, i], [i, j], [i, k],
[j, j], [j, k], [j, i],
[k, k], [k, i], [k, j],
[i, j], [j, k], [k, i]]), 3)
return _xmesh(T, scheme, iter=iter)
def xquad(T, iter=None):
| 96 | 96 | 322 | 8 | 88 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xquad | xquad | 120 | 152 | 120 | 120 | 7eccc1c60f3a0ec2c01c1d2333b851a9391cfedc | bigcode/the-stack | train |
543db2a91c468fef9928f7f9 | train | function | def xtet2hex(T, *args, **kwargs):
"""
Creates the subdivision matrix for transforming a tetrahedra topology into a hexaedra one
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
Returns
-------
(Tensor,LongTensor)
the subdivision matrix and the new (8,M,) ... | def xtet2hex(T, *args, **kwargs):
| """
Creates the subdivision matrix for transforming a tetrahedra topology into a hexaedra one
Parameters
----------
T : LongTensor
the (4,N,) topology tensor
Returns
-------
(Tensor,LongTensor)
the subdivision matrix and the new (8,M,) topology tensor
Raises
--... | , c, c, k, k, k, k],
[c, c, c, c, b, b, b, b], [a, a, b, b, c, c, d, d],
[i, j, k, l, a, b, c, d], [j, j, k, k, b, b, c, c],
[d, d, d, d, d, d, d, d], [d, d, d, d, l, l, l, l],
[k, k, l, l, c, c, d, d], [d, d, d... | 256 | 256 | 988 | 13 | 243 | mauriziokovacic/ACME | ACME/topology/subdivision.py | Python | xtet2hex | xtet2hex | 305 | 351 | 305 | 305 | a27f6f258ba3ff89dd1406219b05a3118b4510fa | bigcode/the-stack | train |
89775716cefbe523a2edd8b5 | train | class | class SettingsDialog(QDialog):
def __init__(self, parent):
super().__init__(parent)
self.server_restart_needed = False
self.time_format_validator = TimeFormatValidator(self)
self.setupUi()
def setupUi(self):
self.ui = loadUi(CONFIG.get_ui_qfile("settings_dialog.ui"), bas... | class SettingsDialog(QDialog):
| def __init__(self, parent):
super().__init__(parent)
self.server_restart_needed = False
self.time_format_validator = TimeFormatValidator(self)
self.setupUi()
def setupUi(self):
self.ui = loadUi(CONFIG.get_ui_qfile("settings_dialog.ui"), baseinstance=self)
self.ap... | from datetime import datetime
from qtpy.QtGui import QDoubleValidator, QFont, QIntValidator, QValidator
from qtpy.QtWidgets import QDialog, QDialogButtonBox, QMessageBox
from .config import CONFIG, MSGPACK_SUPPORT, CBOR_SUPPORT
from .utils import loadUi, show_info_dialog
class SettingsDialog(QDialog):
| 73 | 256 | 1,431 | 6 | 66 | yangrq1018/cutelog | cutelog/settings_dialog.py | Python | SettingsDialog | SettingsDialog | 10 | 157 | 10 | 10 | 723f8443f03a62474025702c6db673cbc0e754ad | bigcode/the-stack | train |
ae4f4e5c177d75efa9067308 | train | class | class TimeFormatValidator(QValidator):
def __init__(self, parent):
super().__init__(parent)
def validate(self, fmt_string, pos):
try:
datetime.now().strftime(fmt_string)
return self.Acceptable, fmt_string, pos
except Exception:
return self.Intermediat... | class TimeFormatValidator(QValidator):
| def __init__(self, parent):
super().__init__(parent)
def validate(self, fmt_string, pos):
try:
datetime.now().strftime(fmt_string)
return self.Acceptable, fmt_string, pos
except Exception:
return self.Intermediate, fmt_string, pos
| (self, fmt):
if self.timeFormatLine.hasAcceptableInput():
self.timeFormatLine.setStyleSheet("QLineEdit {}")
return True
else:
self.timeFormatLine.setStyleSheet("QLineEdit {color: red}")
return False
class TimeFormatValidator(QValidator):
| 64 | 64 | 70 | 7 | 56 | yangrq1018/cutelog | cutelog/settings_dialog.py | Python | TimeFormatValidator | TimeFormatValidator | 160 | 169 | 160 | 160 | 1b48dbeac70417400537b2b486085e29ce2d8c63 | bigcode/the-stack | train |
bbc6eb8ee7e1df9f3688d859 | train | class | class TestHouseBill(unittest.TestCase):
pass
| class TestHouseBill(unittest.TestCase):
| pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2021, Raj Tailot and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestHouseBill(unittest.TestCase):
| 51 | 64 | 10 | 8 | 42 | ShahzadNaser/logistic_management | logistic_management/logistic_management/doctype/house_bill/test_house_bill.py | Python | TestHouseBill | TestHouseBill | 9 | 10 | 9 | 9 | 499a413f0329e8c7a86f4d2df6442bbbf6ee0658 | bigcode/the-stack | train |
d861a47cb9a3c41a215ba68d | train | class | class TestSecondaryPdnConnWithDedBearerLooped(unittest.TestCase):
def setUp(self):
self._s1ap_wrapper = s1ap_wrapper.TestWrapper()
self._spgw_util = SpgwUtil()
def tearDown(self):
self._s1ap_wrapper.cleanup()
def test_seconday_pdn_conn_ded_bearer_looped(self):
""" Attach a ... | class TestSecondaryPdnConnWithDedBearerLooped(unittest.TestCase):
| def setUp(self):
self._s1ap_wrapper = s1ap_wrapper.TestWrapper()
self._spgw_util = SpgwUtil()
def tearDown(self):
self._s1ap_wrapper.cleanup()
def test_seconday_pdn_conn_ded_bearer_looped(self):
""" Attach a single UE and send standalone PDN Connectivity
Request + a... | """
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import unittest
import time... | 113 | 256 | 989 | 15 | 97 | gianpietro-ws/magma | lte/gateway/python/integ_tests/s1aptests/test_attach_detach_secondary_pdn_with_dedicated_bearer_looped.py | Python | TestSecondaryPdnConnWithDedBearerLooped | TestSecondaryPdnConnWithDedBearerLooped | 18 | 134 | 18 | 18 | 50c687acab59aa1bff8a128ceec44cdd334f18cb | bigcode/the-stack | train |
98bfb06b339fb125baeda1c4 | train | class | class Ball:
def __init__(self,world,cx,cy,r,vx,vy):
self.world = world # 球所在的边框(世界)
self.cx=cx # 球心x坐标
self.cy=cy # 球心y坐标
self.r = r # 球心半径
self.vx=vx # 速度x分量
self.vy=vy # 速度y分量
def move(self):
"""
球移动一帧
:return:
"""
if sel... | class Ball:
| def __init__(self,world,cx,cy,r,vx,vy):
self.world = world # 球所在的边框(世界)
self.cx=cx # 球心x坐标
self.cy=cy # 球心y坐标
self.r = r # 球心半径
self.vx=vx # 速度x分量
self.vy=vy # 速度y分量
def move(self):
"""
球移动一帧
:return:
"""
if self.v_collide(... | from dataclasses import dataclass
@dataclass()
class World:
left: float # 左上角x坐标
top: float # 左上角y坐标
right: float # 右下角x坐标
bottom: float # 右下角坐标
#注意Ball有自己的方法,不是dataclass
class Ball:
| 80 | 80 | 267 | 3 | 76 | royqh1979/programming_with_python | Chap04Functions/2-1.ball.py | Python | Ball | Ball | 14 | 49 | 14 | 14 | 058371f5bdfb16d97a489a2174fa302339e75859 | bigcode/the-stack | train |
a48944a98a967d30d41d8272 | train | class | @dataclass()
class World:
left: float # 左上角x坐标
top: float # 左上角y坐标
right: float # 右下角x坐标
bottom: float # 右下角坐标
| @dataclass()
class World:
| left: float # 左上角x坐标
top: float # 左上角y坐标
right: float # 右下角x坐标
bottom: float # 右下角坐标
| from easygraphics import *
import random
from dataclasses import dataclass
@dataclass()
class World:
| 21 | 64 | 59 | 6 | 14 | royqh1979/programming_with_python | Chap04Functions/2-1.ball.py | Python | World | World | 5 | 10 | 5 | 6 | 39a3e3e3e4d2f06e31d1162b34a79982dc2af195 | bigcode/the-stack | train |
f3575f0757cbc0f975652064 | train | function | def main():
init_graph(400,400)
set_render_mode(RenderMode.RENDER_MANUAL)
random.seed()
world = World(20,20,380,380)
cx = random.randrange(20,380)
cy = random.randrange(20,200)
r=5
vx = 0
# 确保随机出来的vx(x方向速度)不会是0
while vx == 0:
vx = random.randint(-3,3)
vy = 0
whil... | def main():
| init_graph(400,400)
set_render_mode(RenderMode.RENDER_MANUAL)
random.seed()
world = World(20,20,380,380)
cx = random.randrange(20,380)
cy = random.randrange(20,200)
r=5
vx = 0
# 确保随机出来的vx(x方向速度)不会是0
while vx == 0:
vx = random.randint(-3,3)
vy = 0
while vy == 0:
... | return self.cy < self.world.top + self.r \
or self.cy > self.world.bottom - self.r
def h_collide(self):
"""
判断X方向上是否撞墙
:return:
"""
return self.cx < self.world.left + self.r \
or self.cx > self.world.right - self.r
def main():
| 74 | 74 | 247 | 3 | 70 | royqh1979/programming_with_python | Chap04Functions/2-1.ball.py | Python | main | main | 52 | 82 | 52 | 52 | 2abe1899cb5d3ff38916548c4b9e9002db8e346d | bigcode/the-stack | train |
c52fc8192051c233284ef7fa | train | class | class Migration(migrations.Migration):
dependencies = [
('materials', '0101_auto_20190905_1702'),
]
operations = [
migrations.AddField(
model_name='dataset',
name='doi',
field=models.CharField(blank=True, max_length=50),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('materials', '0101_auto_20190905_1702'),
]
operations = [
migrations.AddField(
model_name='dataset',
name='doi',
field=models.CharField(blank=True, max_length=50),
),
]
| # Generated by Django 2.2.5 on 2019-11-15 16:40
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 66 | 7 | 30 | HybriD3-database/MatD3 | materials/migrations/0102_dataset_doi.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | fd46a0db42e15d8c431e61cf03ae462abf0df331 | bigcode/the-stack | train |
3dfef2ff4b48122dc328b487 | train | class | class CourseReporter(Reporter):
def report(self, entities: List[CourseEntity], msg: str, is_mute=False) -> None:
total = len(entities)
id_items = [item_entity.id for item_entity in entities]
logger_msg = Template(msg).substitute(total=total, id_items=id_items)
logger.info(logger_msg)... | class CourseReporter(Reporter):
| def report(self, entities: List[CourseEntity], msg: str, is_mute=False) -> None:
total = len(entities)
id_items = [item_entity.id for item_entity in entities]
logger_msg = Template(msg).substitute(total=total, id_items=id_items)
logger.info(logger_msg)
wss.publish(logger_msg,... | ", CourseEntity, LevelEntity, WordEntity, contravariant=True)
class Reporter(ABC, BaseModel):
@abstractmethod
def report(self, entities: List[EntityT], msg: str, is_mute=False) -> None:
raise NotImplementedError
class CourseReporter(Reporter):
| 64 | 64 | 89 | 6 | 57 | kolesnikov-bn/django-memrise-scraper | memrise/core/modules/actions/action_reporter.py | Python | CourseReporter | CourseReporter | 21 | 27 | 21 | 21 | ef6abccd204cb56e1c02992952de860e2bd3c692 | bigcode/the-stack | train |
00c13c32cf8132168223aa0a | train | class | class Reporter(ABC, BaseModel):
@abstractmethod
def report(self, entities: List[EntityT], msg: str, is_mute=False) -> None:
raise NotImplementedError
| class Reporter(ABC, BaseModel):
@abstractmethod
| def report(self, entities: List[EntityT], msg: str, is_mute=False) -> None:
raise NotImplementedError
| memrise.core.domains.entities import CourseEntity, LevelEntity, WordEntity
from memrise.core.modules.web_socket_client import wss
EntityT = TypeVar("EntityT", CourseEntity, LevelEntity, WordEntity, contravariant=True)
class Reporter(ABC, BaseModel):
@abstractmethod
| 64 | 64 | 43 | 13 | 51 | kolesnikov-bn/django-memrise-scraper | memrise/core/modules/actions/action_reporter.py | Python | Reporter | Reporter | 15 | 18 | 15 | 16 | e8d9ede7add9184201d033324613ea1ded02a354 | bigcode/the-stack | train |
770c1ab3c8407978c19e0872 | train | class | class WordReporter(Reporter):
def report(self, entities: List[WordEntity], msg: str, is_mute=False) -> None:
container = defaultdict(list)
[container[entity.level_id].append(entity) for entity in entities]
for level_id, items in container.items():
total = len(items)
... | class WordReporter(Reporter):
| def report(self, entities: List[WordEntity], msg: str, is_mute=False) -> None:
container = defaultdict(list)
[container[entity.level_id].append(entity) for entity in entities]
for level_id, items in container.items():
total = len(items)
id_items = [item_entity.id for... | [item_entity.id for item_entity in items]
logger_msg = Template(msg).substitute(
course_id=course_id, total=total, id_items=id_items
)
logger.info(logger_msg)
wss.publish(logger_msg, is_mute=is_mute)
class WordReporter(Reporter):
| 64 | 64 | 130 | 6 | 58 | kolesnikov-bn/django-memrise-scraper | memrise/core/modules/actions/action_reporter.py | Python | WordReporter | WordReporter | 45 | 57 | 45 | 45 | 7cf30a600b92750123bdf1484908a4d70b2d47e1 | bigcode/the-stack | train |
c6ea9ebbf82e6aad76ff1e81 | train | class | class LevelReporter(Reporter):
def report(self, entities: List[LevelEntity], msg: str, is_mute=False) -> None:
container = defaultdict(list)
[container[entity.course_id].append(entity) for entity in entities]
for course_id, items in container.items():
total = len(items)
... | class LevelReporter(Reporter):
| def report(self, entities: List[LevelEntity], msg: str, is_mute=False) -> None:
container = defaultdict(list)
[container[entity.course_id].append(entity) for entity in entities]
for course_id, items in container.items():
total = len(items)
id_items = [item_entity.id ... | total = len(entities)
id_items = [item_entity.id for item_entity in entities]
logger_msg = Template(msg).substitute(total=total, id_items=id_items)
logger.info(logger_msg)
wss.publish(logger_msg, is_mute=is_mute)
class LevelReporter(Reporter):
| 64 | 64 | 130 | 6 | 58 | kolesnikov-bn/django-memrise-scraper | memrise/core/modules/actions/action_reporter.py | Python | LevelReporter | LevelReporter | 30 | 42 | 30 | 30 | 9a9e6908bb77c663f55a4aedb6bc4f0ae0198280 | bigcode/the-stack | train |
30561f8b1e1e74a3986a2dc8 | train | class | class SaveERP:
def __init__(self, resultsName, resultsPath, results, markers2hide,
preFrame):
# Create output folder if it doesn't exist
if not exists(resultsPath):
makedirs(resultsPath)
# Go through all the markers
for i, m in enumerate(results.unique... | class SaveERP:
| def __init__(self, resultsName, resultsPath, results, markers2hide,
preFrame):
# Create output folder if it doesn't exist
if not exists(resultsPath):
makedirs(resultsPath)
# Go through all the markers
for i, m in enumerate(results.uniqueMarkers):
... | - postcut])
for e in data.Datasets]
tvaMarker = [
1 if 'ok_' in m else 0 for m in data.Results.matrixSelected]
# Go through the files and save TVA for each
counter = 0
for i, n in enumerate(data.Filenames):
filename = join(data.DirPath, n + '.linevie... | 150 | 150 | 502 | 4 | 145 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | SaveERP | SaveERP | 241 | 290 | 241 | 242 | 029ba30a2bf4d373afb7f466d26951c8b9817f2e | bigcode/the-stack | train |
d6be748ffa3ac1dc36e252ed | train | class | class SaveEpochs:
def __init__(self, resultsPath, results, preFrame):
# Create output folder if it doesn't exist
if not exists(resultsPath):
makedirs(resultsPath)
# Go through all epochs
for i, epoch in enumerate(results.epochs):
# Only save epochs that we... | class SaveEpochs:
| def __init__(self, resultsPath, results, preFrame):
# Create output folder if it doesn't exist
if not exists(resultsPath):
makedirs(resultsPath)
# Go through all epochs
for i, epoch in enumerate(results.epochs):
# Only save epochs that were OK
i... | n'
f.writelines(
formatString.format(*np.round(tValues, 7).tolist()))
# Write ERP marker file
filename += '.mrk'
with open(join(resultsPath, filename), 'w') as f:
f.writelines(
'TL02\n{:>12}\t{:>12}\t"Or... | 91 | 91 | 304 | 5 | 86 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | SaveEpochs | SaveEpochs | 293 | 326 | 293 | 294 | 437885aa9fdfcf58d02906e7ac4623d821904480 | bigcode/the-stack | train |
d39c806748469f1227e59724 | train | class | class ReadXYZ:
def __init__(self, filename):
# Read XYZ File
with open(filename) as f:
content = f.readlines()
self.coord = []
self.labels = []
for i, e in enumerate(content):
if i != 0:
coord = e.split()
... | class ReadXYZ:
| def __init__(self, filename):
# Read XYZ File
with open(filename) as f:
content = f.readlines()
self.coord = []
self.labels = []
for i, e in enumerate(content):
if i != 0:
coord = e.split()
self.... |
def excludeChannels(self, channels2exclude):
keepID = [i for i, e in enumerate(self.labelsChannel)
if e not in channels2exclude]
self.labelsChannel = self.labelsChannel[keepID]
self.rawdata = self.rawdata[keepID]
class ReadXYZ:
| 64 | 64 | 158 | 4 | 60 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | ReadXYZ | ReadXYZ | 190 | 211 | 190 | 191 | 6bb89da547d535e74e632532c7f1fa1d3401cc11 | bigcode/the-stack | train |
77501993e80fc74e92396761 | train | class | class SaveVerbose:
def __init__(self, resultsName, resultsPath, data):
# abbreviation to shorten variable name
res = data.Results
# Write Verbose File
with open(join(resultsPath, '%s.vrb' % resultsName), 'w') as f:
f.writelines('Verbose File\n============\n\n')
... | class SaveVerbose:
| def __init__(self, resultsName, resultsPath, data):
# abbreviation to shorten variable name
res = data.Results
# Write Verbose File
with open(join(resultsPath, '%s.vrb' % resultsName), 'w') as f:
f.writelines('Verbose File\n============\n\n')
f.writelines('L... | formatString[:-1] + '\n'
f.writelines(
formatString.format(*np.round(tValues, 7).tolist()))
# Write Epoch marker file
filename += '.mrk'
with open(join(resultsPath, filename), 'w') as f:
f.writelines(
'... | 256 | 256 | 2,318 | 4 | 252 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | SaveVerbose | SaveVerbose | 348 | 523 | 348 | 349 | a9a1404a2e300c52618841f71b2898ef4af8d0a5 | bigcode/the-stack | train |
0d24fb543610086c9d8bd537 | train | class | class SaveTVA:
def __init__(self, data, precut, postcut):
dataSize = [
len([m for m in e.markerTime
if m > precut and m < e.rawdata.shape[1] - postcut])
for e in data.Datasets]
tvaMarker = [
1 if 'ok_' in m else 0 for m in data.Results.matrixSel... | class SaveTVA:
| def __init__(self, data, precut, postcut):
dataSize = [
len([m for m in e.markerTime
if m > precut and m < e.rawdata.shape[1] - postcut])
for e in data.Datasets]
tvaMarker = [
1 if 'ok_' in m else 0 for m in data.Results.matrixSelected]
... | = np.array(self.coord)
self.labels = np.array(self.labels)
# Get ID of 10% most frontal channels
xValue = self.coord[:, 0]
self.frontalID = np.where(xValue >= np.percentile(xValue, 90))[0]
class SaveTVA:
| 64 | 64 | 198 | 5 | 59 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | SaveTVA | SaveTVA | 214 | 238 | 214 | 215 | 627f7f893745d36915148d3338d1945d99d405ad | bigcode/the-stack | train |
8a532f298701fc4cd521d74a | train | class | class ReadEEG:
def __init__(self, filename, newSampleRate=0, channels2exclude=[]):
self.filename = filename
if filename[-3:] == 'bdf':
self.readBDF()
elif filename[-3:] == 'eeg':
self.readBrainVision()
# Exclude Channels if necessary
if channels2ex... | class ReadEEG:
| def __init__(self, filename, newSampleRate=0, channels2exclude=[]):
self.filename = filename
if filename[-3:] == 'bdf':
self.readBDF()
elif filename[-3:] == 'eeg':
self.readBrainVision()
# Exclude Channels if necessary
if channels2exclude != []:
... | import time
import numpy as np
from os import makedirs
from os.path import exists, join, basename
class ReadEEG:
| 30 | 256 | 1,561 | 5 | 24 | miykael/LINEViewer | lineviewer/FileHandler.py | Python | ReadEEG | ReadEEG | 7 | 187 | 7 | 8 | 8d8f15ed7c913af0d6dc8a908d0fd3d2eb379ef7 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.