code
stringlengths
101
5.91M
class _infix_wrapper(): function = None def __init__(self, left=None, right=None): self.left = left self.right = right def __call__(self, *args, **kwds): return self.function(*args, **kwds) def _left(self, right): if (self.left is None): if (self.right is None...
def test_select(with_global_metadata): arr = ak.metadata_from_parquet(with_global_metadata, row_groups=[1]) assert (arr['col_counts'] == [2]) with pytest.raises(ValueError): ak.metadata_from_parquet(with_global_metadata, row_groups=[1, 1]) with pytest.raises(ValueError): ak.metadata_from...
def test_feedback_block_heatmap_attention(): x1 = torch.rand(2, 16, 32, 32) heatmap = torch.rand(2, 5, 32, 32) model = FeedbackBlockHeatmapAttention(16, 2, 8, 5, 2) x2 = model(x1, heatmap) assert (x2.shape == x1.shape) x3 = model(x2, heatmap) assert (x3.shape == x2.shape)
def _make_legal_action_mask(state: State, hand, c_p, new_tile): legal_action_mask = jnp.zeros(NUM_ACTION, dtype=jnp.bool_) legal_action_mask = legal_action_mask.at[:34].set((hand[c_p] > 0)) legal_action_mask = legal_action_mask.at[new_tile].set(FALSE) legal_action_mask = legal_action_mask.at[Action.TSUM...
class Unexpectedness(RecOnlyMetric): _scala_udf_name = 'getUnexpectednessMetricValue' def __init__(self, pred: DataFrameLike, use_scala_udf: bool=False): self._use_scala_udf = use_scala_udf self.pred = convert2spark(pred) def _get_metric_value_by_user(k, *args) -> float: pred = args[...
def _length_hint(obj): try: return len(obj) except (AttributeError, TypeError): try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if ...
def validate_json_string(json_string: str, schema_name: str) -> (dict | None): try: json_loaded = json.loads(json_string) if (not validate_json(json_loaded, schema_name)): return None return json_loaded except: return None
class GTResDataset(Dataset): def __init__(self, root_path, gt_dir=None, transform=None, transform_train=None): self.pairs = [] for f in os.listdir(root_path): image_path = os.path.join(root_path, f) gt_path = os.path.join(gt_dir, f) if (f.endswith('.jpg') or f.end...
def load_checkpoint(filename, gpu=True): if os.path.exists(filename): checkpoint = torch.load(filename, map_location=(lambda storage, loc: storage)) else: print('No model found at {}'.format(filename)) return checkpoint
class dlaplace_gen(rv_discrete): def _pmf(self, k, a): return (tanh((a / 2.0)) * exp(((- a) * abs(k)))) def _cdf(self, x, a): k = floor(x) f = (lambda k, a: (1.0 - (exp(((- a) * k)) / (exp(a) + 1)))) f2 = (lambda k, a: (exp((a * (k + 1))) / (exp(a) + 1))) return _lazywher...
def is_tensor_method_or_property(func: Callable) -> bool: return ((func in _get_tensor_methods()) or (func.__name__ == '__get__'))
def load_model(model_path='', mode='all', **kwds): model = get_2lvl_model(mode=mode, **kwds) return model
def evaluate_one_shot(model, xloader, api, cal_mode, seed=111): print('This is an old version of codes to use NAS-Bench-API, and should be modified to align with the new version. Please contact me for more details if you use this function.') weights = deepcopy(model.state_dict()) model.train(cal_mode) w...
class DenseNet121(nn.Module): def __init__(self, n_inputs=12, numCls=17): super().__init__() densenet = models.densenet121(pretrained=False) self.encoder = nn.Sequential(nn.Conv2d(n_inputs, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False), *densenet.features[1:]) se...
class TestImbalance(unittest.TestCase): def test(self): feature_names = ['Age', 'Workclass', 'fnlwgt', 'Education', 'Education-Num', 'Marital Status', 'Occupation', 'Relationship', 'Race', 'Sex', 'Capital Gain', 'Capital Loss', 'Hours per week', 'Country', 'label'] data_dir = os.path.join(os.path.di...
def _key_complex_for_display(a): ar = a.real() ai = a.imag() if (not ai): return (0, ar) epsilon = ar.parent()(1e-10) if (ar.abs() < epsilon): ar_truncated = 0 elif (ar.prec() < 34): ar_truncated = ar else: ar_truncated = ar.n(digits=9) return (1, ar_trunc...
def convLayer(batchNorm, in_planes, out_planes, kernel_size=3, stride=1, dilation=1, bias=False): if batchNorm: return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=((((kernel_size - 1) // 2) + dilation) - 1), dilation=dilation, bias=bias), nn.BatchNorm2d(out...
_module() class Collect(object): def __init__(self, keys, meta_keys=('filename', 'ori_filename', 'ori_shape', 'img_shape', 'flip', 'flip_direction', 'img_norm_cfg')): self.keys = keys self.meta_keys = meta_keys def __call__(self, results): data = {} img_meta = {} for key ...
def get_metrics(): try: return tf.compat.v1.metrics except AttributeError: return tf.metrics
class TargetFilter(Wrapper, Dataset): def __init__(self, dataset, keep): super().__init__(dataset) self.ds = dataset self.keep = set(keep) self.slugs = self.load_slugs() def load_slugs(self): slugs = [] for (i, data) in enumerate(self.ds): (target, aux...
def obj_from_dict(info, parent=None, default_args=None): assert (isinstance(info, dict) and ('type' in info)) assert (isinstance(default_args, dict) or (default_args is None)) args = copy.deepcopy(info) obj_type = args.pop('type') if torchie.is_str(obj_type): if (parent is not None): ...
_torch _torchaudio class ClapFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): feature_extraction_class = ClapFeatureExtractor def setUp(self): self.feat_extract_tester = ClapFeatureExtractionTester(self) def test_call(self): feature_extractor = self.feature_extra...
def _reverse_seq(input_seq, lengths): if (lengths is None): return list(reversed(input_seq)) input_shape = tensor_shape.matrix(None, None) for input_ in input_seq: input_shape.merge_with(input_.get_shape()) input_.set_shape(input_shape) s_joined = array_ops.pack(input_seq) if...
def test_nlc2nchw2nlc(): shape_nchw = (4, 2, 5, 5) shape_nlc = (4, 25, 2) def test_func(x): assert (x.shape == torch.Size(shape_nchw)) return x x = torch.rand(*shape_nlc) output = nlc2nchw2nlc(test_func, x, shape_nchw[2:]) assert (output.shape == torch.Size(shape_nlc)) def te...
def get_recall(capsule1_path, region1_path, capsule2_path, region2_path): class_coefs = [] capsules = [] regions = [] capsules.append(cv2.imread(capsule1_path)) capsules.append(cv2.imread(capsule2_path)) regions.append(cv2.imread(region1_path)) regions.append(cv2.imread(region2_path)) fo...
def test_statement_coverage_hash(statement_coverage_goal): assert (statement_coverage_goal.__hash__() != 0)
class MaxNorm(Constraint): def __init__(self, max_value=2, axis=0): self.max_value = max_value self.axis = axis def __call__(self, w): norms = K.sqrt(K.sum(K.square(w), axis=self.axis, keepdims=True)) desired = K.clip(norms, 0, self.max_value) w *= (desired / (K.epsilon()...
class Partition5(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/T5Block[20]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[21]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[22]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[23]', 'T5ForConditionalGeneration/T5Stack...
class Form(Meta): def _init(self, *, parameters: (JSONMapping | None), form_key: (str | None)): if ((parameters is not None) and (not isinstance(parameters, dict))): raise TypeError("{} 'parameters' must be of type dict or None, not {}".format(type(self).__name__, repr(parameters))) if (...
def vgg_detectron_weight_mapping(model): mapping_to_detectron = {} for k in model.state_dict(): if ('.weight' in k): mapping_to_detectron.update({k: k.replace('.weight', '_w')}) if ('.bias' in k): mapping_to_detectron.update({k: k.replace('.bias', '_b')}) orphan_in_de...
def main(): paused = False while True: if (not paused): straight() print(key_check()) time.sleep(1) left() print(key_check()) time.sleep(1) right() print(key_check()) time.sleep(1)
def get_dist_from_SVDD(data_set, model, center): z_set = [] model.eval() with torch.no_grad(): for (batch_idx, x) in enumerate(data_set): z = model(x) z_set.append(z) z_set = torch.vstack(z_set) dist = (z_set - center.unsqueeze(0)) dist = dist.square().mean(1) ...
def search_span(span): candidates = [] params = {'action': 'wbsearchentities', 'search': span, 'language': 'en', 'limit': 5, 'format': 'json', 'props': 'description'} response = requests.get(url, params=params) data = response.json() results = data['search'] for result in results: candid...
class BernoulliDistribution(Distribution): def __init__(self, action_dims: int): super(BernoulliDistribution, self).__init__() self.action_dims = action_dims def proba_distribution_net(self, latent_dim: int) -> nn.Module: action_logits = nn.Linear(latent_dim, self.action_dims) re...
def eye(n, M=None, k=0, dtype=float, order='C'): return asmatrix(np.eye(n, M=M, k=k, dtype=dtype, order=order))
def add_chinese_references(dataset, ref_file): with open(ref_file, 'r', encoding='utf-8') as f: refs = [json.loads(line) for line in f.read().splitlines() if ((len(line) > 0) and (not line.isspace()))] assert (len(dataset) == len(refs)) dataset_dict = {c: dataset[c] for c in dataset.column_names} ...
def unlink_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): dy = grad_inputs[0] x0 = inputs[0] raise NotImplementedError('unlink_backward is not implemented.')
def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: def _objective(trial, checkpoint_dir=None): model_path = None if checkpoint_dir: for subdir in os.listdir(checkpoint_dir): if subdir.startswith(PREFIX_CHECKPOINT_DIR): ...
def check_integrity(fpath: str, md5: Optional[str]=None) -> bool: if (not os.path.isfile(fpath)): return False if (md5 is None): return True return check_md5(fpath, md5)
def enable_explicit_format() -> None: handlers = _get_library_root_logger().handlers for handler in handlers: formatter = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s') handler.setFormatter(formatter)
def generate_multimethod(argument_extractor: ArgumentExtractorType, argument_replacer: ArgumentReplacerType, domain: str, default: Optional[Callable]=None): (kw_defaults, arg_defaults, opts) = get_defaults(argument_extractor) ua_func = _Function(argument_extractor, argument_replacer, domain, arg_defaults, kw_de...
def write_sequence(frames, path): with open(path, 'w') as f: for (t, objects) in frames.items(): for obj in objects: print(t, obj.track_id, obj.class_id, obj.mask['size'][0], obj.mask['size'][1], obj.mask['counts'].decode(encoding='UTF-8'), file=f)
class DeVilliersGlasser02(Benchmark): def __init__(self, dimensions=5): Benchmark.__init__(self, dimensions) self._bounds = list(zip(([1.0] * self.N), ([60.0] * self.N))) self.global_optimum = [[53.81, 1.27, 3.012, 2.13, 0.507]] self.fglob = 0.0 def fun(self, x, *args): s...
def fit_predict_selected(model, train_log, inf_log, user_features, users): kwargs = {} if isinstance(model, (HybridRecommender, UserRecommender)): kwargs = {'user_features': user_features} model.fit(train_log, **kwargs) return model.predict(log=inf_log, users=users, k=1, **kwargs)
_LAYERS.register_module() _LAYERS.register_module('deconv') _LAYERS.register_module('deconv', force=True) class ConvTranspose2d(nn.ConvTranspose2d): def forward(self, x: torch.Tensor) -> torch.Tensor: if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 4))): out_shape = [x.shape[0...
class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self)
class FPEM(BaseModule): def __init__(self, in_channels=128, init_cfg=None): super().__init__(init_cfg=init_cfg) self.up_add1 = SeparableConv2d(in_channels, in_channels, 1) self.up_add2 = SeparableConv2d(in_channels, in_channels, 1) self.up_add3 = SeparableConv2d(in_channels, in_chann...
def read_metadata_from_db(datasource, table): with connect_with_data_source(datasource) as conn: with SQLFSReader(conn, table) as r: metadata = _read_metadata(r) return metadata
class Conv2D2BNInfoCollectionTest(BasePytorchTest): def __init__(self, unit_test): super().__init__(unit_test) self.val_batch_size = 1 def create_inputs_shape(self): return [[self.val_batch_size, 3, 32, 32]] def generate_inputs(input_shapes): return to_torch_tensor([torch.ran...
class ConfigurationCommand(Command): name = 'config' usage = '\n %prog [<file-option>] list\n %prog [<file-option>] [--editor <editor-path>] edit\n\n %prog [<file-option>] get name\n %prog [<file-option>] set name value\n %prog [<file-option>] unset name\n ' summary = '...
class SoftSign(Module): def __init__(self): super(SoftSign, self).__init__() self.temp = None self.tempgrad = None def updateOutput(self, input): if (self.temp is None): self.temp = input.new() self.temp.resize_as_(input).copy_(input).abs_().add_(1) se...
class AddPosEmb(nn.Module): def __init__(self, n, c): super(AddPosEmb, self).__init__() self.pos_emb = nn.Parameter(torch.zeros(1, 1, n, c).float().normal_(mean=0, std=0.02), requires_grad=True) self.num_vecs = n def forward(self, x): (b, n, c) = x.size() x = x.view(b, (-...
def build_candidate_set(documents: List[Document], target: str) -> List[Union[(Span, Relation)]]: Xs = [] for doc in documents: xs = [doc.annotations[i][target] for i in doc.annotations if (target in doc.annotations[i])] Xs.extend(itertools.chain.from_iterable(xs)) return Xs
def get_random_port(): old_state = random.getstate() random.seed() port = random.randint(10000, 20000) random.setstate(old_state) return port
_utils.test(require=ti.extension.data64) def test_cast_f64(): z = ti.field(ti.i32, shape=()) def func(): z[None] = ((ti.cast(.0, ti.f64) / ti.cast(.0, ti.f64)) + 0.001) func() assert (z[None] == 1000)
def test_pickling_vectorizer(): instances = [HashingVectorizer(), HashingVectorizer(norm='l1'), HashingVectorizer(binary=True), HashingVectorizer(ngram_range=(1, 2)), CountVectorizer(), CountVectorizer(preprocessor=strip_tags), CountVectorizer(analyzer=lazy_analyze), CountVectorizer(preprocessor=strip_tags).fit(JUN...
def run_python_forward_backward(unit_test_class, test_params): device = test_params.device module = test_params.test_instance.constructor(*test_params.test_instance.constructor_args).to(device) inputs = set_python_tensors_requires_grad(move_python_tensors_to_device([arg_value for (_, arg_value) in test_para...
def GenerateSM61_Simt(manifest, args): layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, LayoutType.RowMajor, LayoutT...
def print_model_param_nums(model=None): if (model == None): model = torchvision.models.alexnet() total = sum([(param.nelement() if param.requires_grad else 0) for param in model.parameters()]) print((' + Number of params: %.4fM' % (total / 1000000.0)))
def register_coco_panoptic(name, metadata, image_root, panoptic_root, panoptic_json, instances_json=None): panoptic_name = name DatasetCatalog.register(panoptic_name, (lambda : load_coco_panoptic_json(panoptic_json, image_root, panoptic_root, metadata))) MetadataCatalog.get(panoptic_name).set(panoptic_root=...
def compute_rhs(up_hat, bh_hat): global uiuj, uiuj_hat bh_hat.fill(0) bi_hat = bh_hat[0] ui_hat = up_hat[0] uip = ui_hat.backward(padding_factor=1.5) uiuj = outer(uip, uip, uiuj) uiuj_hat = uiuj.forward(uiuj_hat) bi_hat = BS.matvec(uiuj_hat, bi_hat) return bh_hat
class EpicFHIRDownloadFiles(VirtualFunctionTool): name = 'EpicFHIRDownloadFiles' summary = 'Download files by their unique identifiers.' parameters: List[ArgParameter] = [{'name': 'file_ids', 'type': 'array', 'description': "The unique identifiers of the files to download. Each should be a valid 'document_i...
def to_tf_space(space): if isinstance(space, TheanoBox): return Box(low=space.low, high=space.high) elif isinstance(space, TheanoDiscrete): return Discrete(space.n) elif isinstance(space, TheanoProduct): return Product(list(map(to_tf_space, space.components))) else: raise...
class PointTarget(): def __init__(self): self.points = Point(cfg.POINT.STRIDE, cfg.TRAIN.OUTPUT_SIZE, (cfg.TRAIN.SEARCH_SIZE // 2)) def __call__(self, target, size, neg=False): cls = ((- 1) * np.ones((size, size), dtype=np.int64)) delta = np.zeros((4, size, size), dtype=np.float32) ...
def stringify_keys(d): for key in d.keys(): if isinstance(d[key], dict): value = stringify_keys(d[key]) else: value = d[key] if (not isinstance(key, str)): try: d[str(key)] = value except Exception: try: ...
def render_pep440_post_branch(pieces): if pieces['closest-tag']: rendered = pieces['closest-tag'] if (pieces['distance'] or pieces['dirty']): rendered += ('.post%d' % pieces['distance']) if (pieces['branch'] != 'master'): rendered += '.dev0' render...
def convolution(_x, k, out_dim, name, stride=1): padding = ((k - 1) // 2) _x = ZeroPadding2D(padding=padding, name=(name + '.pad'))(_x) _x = Conv2D(out_dim, k, strides=stride, use_bias=False, name=(name + '.conv'))(_x) _x = BatchNormalization(epsilon=1e-05, name=(name + '.bn'))(_x) _x = Activation('...
def read_teacher_score(score_files): teacher_score = collections.defaultdict(dict) for file in score_files.split(','): if (not os.path.exists(file)): logging.info(f'There is no score file:{file}, skip reading the score') return None for line in open(file): (qi...
def get_all_examples(): blocklist = {'_np'} allexamples = '' example_file_lines = ['import torch', 'import torch.nn.functional as F', 'import math # type: ignore', 'import numpy # type: ignore', 'import io # type: ignore', 'import itertools # type: ignore', '', 'def preprocess(inp):', ' # type: (torc...
def get_valid_stats(trainer): stats = collections.OrderedDict() stats['valid_loss'] = trainer.get_meter('valid_loss').avg if (trainer.get_meter('valid_nll_loss').count > 0): nll_loss = trainer.get_meter('valid_nll_loss').avg stats['valid_nll_loss'] = nll_loss else: nll_loss = tra...
class RealUser(UserSim): def __init__(self, error_evaluator, bool_undo=True): UserSim.__init__(self, error_evaluator) self.user_type = 'real' self.bool_undo = bool_undo self.undo_semantic_units = [] def get_answer(self, pointer, *args): self.questioned_pointers.append(poi...
class TFCLIPPreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class PerTensorWeightQuantizationTest(BaseKerasFeatureNetworkTest): def __init__(self, unit_test): super().__init__(unit_test, experimental_exporter=True) def get_tpc(self): tp = generate_test_tp_model({'weights_per_channel_threshold': False}) return generate_keras_tpc(name='per_tensor_w...
def weights_init(m): if ((type(m) == nn.Conv2d) or (type(m) == nn.ConvTranspose2d)): nn.init.xavier_normal(m.weight.data) elif (type(m) == nn.BatchNorm2d): m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0)
def main(): parser = argparse.ArgumentParser('preprocess') parser.add_argument('--input_dir', type=str, help='inp directory', default='../data/') parser.add_argument('--output_dir', type=str, help='out directory', default='data/qmsum/preprocessed') args = parser.parse_args() Path(args.output_dir).mk...
def test_pegasus_newline(): pred = ['" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" '] tgt = [' Marseille prosecutor says "so far no videos were used in the c...
class HRModule(BaseModule): def __init__(self, num_branches, blocks, num_blocks, in_channels, num_channels, multiscale_output=True, with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), block_init_cfg=None, init_cfg=None): super(HRModule, self).__init__(init_cfg) self.block_ini...
def _validate_loaded_sparse_tensors(): try: for t in _sparse_tensors_to_validate: torch._validate_sparse_coo_tensor_args(t._indices(), t._values(), t.size()) finally: _sparse_tensors_to_validate.clear()
def save_json(data, json_path, mode='w', encoding='utf-8'): dir = os.path.dirname(os.path.abspath(json_path)) if (not os.path.exists(dir)): print(dir) os.makedirs(dir) with open(json_path, mode=mode, encoding=encoding) as f: f.write(json.dumps(data, ensure_ascii=False))
class ClientNode2(Node): def config(self, **params): super(ClientNode2, self).config(**params) self.cmd('openvpn openvpn-client2.conf &') def terminate(self): super(ClientNode2, self).terminate()
def get_tree_node_with_kinds(tree, kinds): cursor = tree.walk() reached_root = False while (reached_root == False): if (cursor.node.type in kinds): (yield cursor.node) if cursor.goto_first_child(): continue if cursor.goto_next_sibling(): continue ...
class ColumnReductionOp(): Template = '\n${visitor}\n\nusing ${instance_name} = cutlass::epilogue::threadblock::VisitorOpColumnReduction<\n cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,\n ${element_accumulator}, ${element_reduction}, ${element_reduction_accu...
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): while True: chunk = file.read(size) if (not chunk): break (yield chunk)
def unpack_kwargs(kwarg_keys: List[str], flat_args: List[Any]) -> Tuple[(List[Any], Dict[(str, Any)])]: if (len(kwarg_keys) == 0): return (flat_args, {}) args = flat_args[:(- len(kwarg_keys))] kwargs = {k: v for (k, v) in zip(kwarg_keys, flat_args[(- len(kwarg_keys)):])} return (args, kwargs)
def is_dominating(G, dom, focus=None): to_dom = (set(G) if (focus is None) else set(focus)) for v in dom: if (not to_dom): return True to_dom.difference_update(G.neighbor_iterator(v, closed=True)) return (not to_dom)
class AlgebraicGeneratorRelation(SageObject): def __init__(self, child1, child1_poly, child2, child2_poly, parent): self.child1 = child1 self.child1_poly = child1_poly self.child2 = child2 self.child2_poly = child2_poly self.parent = parent
.parametrize('p', [1, 2, np.inf]) .parametrize('size', [50, 100, None]) def test_ensure_spacing_batch_processing(p, size): coord = np.random.randn(100, 2) spacing = np.median(pdist(coord, metric=minkowski, p=p)) expected = ensure_spacing(coord, spacing=spacing, p_norm=p) assert np.array_equal(ensure_spa...
def print_uniques(csv, cols=['alg', 'bs_train', 'model', 'dataset', 'seed', 'step_every']): df = pd.read_csv(csv) var_to_uniques = {var: pd.unique(df[var]) for var in cols} var_to_len_uniques = {i: len(v) for (i, v) in var_to_uniques.items()} print(f'-I- Describing csv: {csv}') print(f'-I- Analyzed ...
def _lfc(content, equality=False): content = list(content) a = ([0] * sum(content)) content[0] -= 1 k = len(content) rng_k = list(range(k)) rng_k.reverse() dll = DoublyLinkedList(rng_k) if (not content[0]): dll.hide(0) (yield from _list_fixed_content(a, content, 2, 1, k, dll,...
_numpy_output(check_dtype=True) def test_ufunc_heaviside_cc(A: dace.complex64[10], B: dace.complex64[10]): return np.heaviside(A, B)
def run_once(func): (func) def wrapper(*args, **kwargs): if (not wrapper.has_run): result = func(*args, **kwargs) wrapper.has_run = True return result wrapper.has_run = False return wrapper
.fast .parametrize('length,max_seq_length,eos_token_id,expected_token_ids,expected_token_type_ids', [(2, 6, (- 1), [0, 1, (- 1), (- 1), (- 1), (- 1)], [0, (- 1), 2, 2, 2, 2]), (0, 6, (- 1), [(- 1), (- 1), (- 1), (- 1), (- 1), (- 1)], ([TokenTypeIds.PADDING] * 6))]) def test_pad(tokenized_line: TokenizedLine, expected_t...
class AbstractAdapter(GaugeAdapter): __test__ = False re_time = re_compile('RESULT-(\\w+):\\s*(\\d+\\.\\d+)') def __init__(self, include_faulty, executor): super(AbstractAdapter, self).__init__(include_faulty, executor) self._other_error_definitions = [re_compile('FAILED')] def _make_mea...
def test_classify_instance_weighting(create_pool_classifiers): n_samples = 3 query = np.ones((n_samples, 2)) pool_classifiers = (create_pool_classifiers + create_pool_classifiers) des_test = BaseDES(pool_classifiers, mode='weighting') des_test.classes_ = np.array([0, 1]) des_test.n_classes_ = 2 ...
def aggregate_passage_embeddings_in_run(run: dict, p_emb_dict: dict, aggregation_mode: str): if ((aggregation_mode == 'vrrf') or (aggregation_mode == 'vranks') or (aggregation_mode == 'vscores')): run_p_embs = aggregate_run_in_p_with_scores(run, p_emb_dict) else: run_p_embs = aggregate_p_in_run(...
def _clean_args(*args): newargs = [] for chk in args: if (chk is None): break newargs.append(chk) return newargs
class ProtobufModel(torch.nn.Module): _ids = count(0) def __init__(self, predict_net, init_net): logger.info(f'Initializing ProtobufModel for: {predict_net.name} ...') super().__init__() assert isinstance(predict_net, caffe2_pb2.NetDef) assert isinstance(init_net, caffe2_pb2.NetD...
def fst_transition(fst_handle, states, inputs): return get_tf_mod().open_fst_transition(handle=fst_handle, states=states, inputs=inputs)
class Mapping(): def __init__(self, short_details=None): self.short_details = short_details def prop(self): return getattr(self, '_prop', None) def prop(self, value): value = validate_type('prop', value, PhysicalProperty, cast=False) value._mapping = self self._prop =...
def score_dependencies(args): if (args['lang'] != 'en'): raise ValueError('Converting and scoring dependencies is currently only supported for English') constituency_package = 'wsj_bert' pipeline_args = {'lang': args['lang'], 'tokenize_pretokenized': True, 'package': {'pos': args['retag_package'], '...