code
stringlengths
101
5.91M
def _generate_results_unreliable(input_stream, input_queue, worker_output_queue, output_queue, num_workers, max_outstanding_unused): next_in_item = next(input_stream, EndSentinel) inputs_remain = (next_in_item is not EndSentinel) received_messages = deque() pack_cookie = struct.pack input_fd = input...
class _BrokenModel(_PseudoTrainableQuadratic): def optimize(self, dataset: Dataset) -> NoReturn: raise _Whoops
class SumoVehSignal(object): BLINKER_RIGHT = (1 << 0) BLINKER_LEFT = (1 << 1) BLINKER_EMERGENCY = (1 << 2) BRAKELIGHT = (1 << 3) FRONTLIGHT = (1 << 4) FOGLIGHT = (1 << 5) HIGHBEAM = (1 << 6) BACKDRIVE = (1 << 7) WIPER = (1 << 8) DOOR_OPEN_LEFT = (1 << 9) DOOR_OPEN_RIGHT = (1 ...
def find_input_arraynode(graph, edge): result = graph.memlet_path(edge)[0] if (not isinstance(result.src, nd.AccessNode)): raise RuntimeError(('Input array node not found for memlet ' + str(edge.data))) return result.src
class YosoConfig(PretrainedConfig): model_type = 'yoso' def __init__(self, vocab_size=50265, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=4096, type_vocab_size=1, initi...
_function_from_c_func_and_dispatcher(_multiarray_umath.dot) def dot(a, b, out=None): return (a, b, out)
class SwagProcessor(DataProcessor): def get_train_examples(self, data_dir): logger.info('LOOKING AT {} train'.format(data_dir)) return self._create_examples(self._read_csv(os.path.join(data_dir, 'train.csv')), 'train') def get_dev_examples(self, data_dir): logger.info('LOOKING AT {} dev'...
class CityscapesData(Dataset): def __init__(self, folder_path): self.folder_path = folder_path self.all_imgs = sorted(list(Path(folder_path).glob('**/*.png'))) def __len__(self): return len(self.all_imgs) def __getitem__(self, index): image_path = self.all_imgs[index] ...
class MemoizedClass(object): def __init__(self): self.calls = 0 _with_key_fxn((lambda self, a, b: b)) def fxn_to_memoize(self, a, b): self.calls += 1 return (a + b)
def _preserve_environment(names): log.debug(('_preserve_environment(%r)' % names)) env = {name: os.environ.get(name) for name in names} return env
def get_label_from_logits(logits, label_ids, input_ids, subword, input_mask, tokenizer, label_map, k=1, mode='IO', print_topk=0): pred_ids_topk = torch.topk(logits, k=k, dim=2).indices if (print_topk > 0): (pred_value_top5, pred_ids_top5) = torch.topk(logits, k=print_topk, dim=2) pred_labels = [] ...
_model def identityformer_s12(pretrained=False, **kwargs): model = MetaFormer(depths=[2, 2, 6, 2], dims=[64, 128, 320, 512], token_mixers=nn.Identity, norm_layers=partial(LayerNormGeneral, normalized_dim=(1, 2, 3), eps=1e-06, bias=False), **kwargs) model.default_cfg = default_cfgs['identityformer_s12'] if p...
def write_sensor_data_as_document(cas): localpath = '/Users/moy/work/git_public/word2vec-data/sensor' with open((localpath + '/sensor_data.txt'), 'w') as f: f.write(' '.join(cas.sensor_seq))
def generate_sample(embeddings, this_spk, other_spks, label): this_spk_embs = embeddings[this_spk] other_spk_embs = list(chain(*[embeddings[spk] for spk in other_spks])) samples = [] for this_spk_emb in this_spk_embs: for other_spk_emb in other_spk_embs: cosine_similarity = get_cosin...
class ResultSet(six.Iterator): def __init__(self): self._generator = None def __iter__(self): return self def _gen(self): fetch_size = 128 while True: rows = (self._fetch(fetch_size) or []) for r in rows: (yield r) if (len(r...
def expand_args(params): sweep_args = {k: v for (k, v) in params.items() if isinstance(v, list)} sweep = [dict(zip(sweep_args.keys(), vs)) for vs in itertools.product(*sweep_args.values())] expanded = [] for swargs in sweep: new_args = {**params, **swargs} expanded.append(new_args) r...
def add_assert_range_checked(ctx: LeanGenContext, lhs: Expression, rhs: Expression, assert_rw: str): if (ctx.rc_steps is not None): ctx.concat_final(ctx.rc_steps.add_assert_range_checked(lhs, rhs, assert_rw))
def test_indexed(): assert ak.almost_equal(ak.contents.ListOffsetArray(ak.index.Index64([0, 2, 4, 8]), ak.contents.IndexedArray(ak.index.Index64([0, 1, 2, 3, 2, 1, 0, 5]), ak.contents.NumpyArray(np.arange(6, dtype=np.int64)))), ak.contents.ListOffsetArray(ak.index.Index64([0, 2, 4, 8]), ak.contents.NumpyArray(np.ar...
class SolveMaxMatching(): def __init__(self, nworkers, ntasks, k, value=10000, pairwise_lamb=0.1): self.nworkers = nworkers self.ntasks = ntasks self.value = value self.k = k self.source = 0 self.sink = ((self.nworkers + self.ntasks) + 1) self.pairwise_cost = ...
def get_impute_knn_score(X_missing, y_missing): imputer = KNNImputer(missing_values=np.nan, add_indicator=True) knn_impute_scores = get_scores_for_imputer(imputer, X_missing, y_missing) return (knn_impute_scores.mean(), knn_impute_scores.std())
class ParameterList(rf.Module): def __init__(self, *parameters: Union[(rf.Parameter, Iterable[rf.Parameter], Dict[(str, rf.Parameter)], ParameterList)]): super().__init__() if ((len(parameters) == 1) and isinstance(parameters[0], dict)): for (i, (key, parameter)) in enumerate(parameters[...
class BatchSampler(BaseSampler): def start_worker(self): if (singleton_pool.n_parallel > 1): singleton_pool.run_each(worker_init_tf) parallel_sampler.populate_task(self.algo.env, self.algo.policy) if (singleton_pool.n_parallel > 1): singleton_pool.run_each(worker_init...
class adjust_light(): def __call__(self, image): seed = random.random() if (seed > 0.5): gamma = ((random.random() * 3) + 0.5) invGamma = (1.0 / gamma) table = np.array([(((i / 255.0) ** invGamma) * 255) for i in np.arange(0, 256)]).astype(np.uint8) im...
def resnet18(pretrained=False, progress=True, modal='vision', **kwargs): return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, modal, **kwargs)
def pil_loader(data_path, label_path): data = Image.open(data_path) label = Image.open(label_path) return (data, label)
class LinearOperator(object): def __new__(cls, *args, **kwargs): if (cls is LinearOperator): return super(LinearOperator, cls).__new__(_CustomLinearOperator) else: obj = super(LinearOperator, cls).__new__(cls) if ((type(obj)._matvec == LinearOperator._matvec) and ...
def recover_formula(prefix_tree): formula = '' if (not isinstance(prefix_tree, list)): raise TypeError('the input must be a parse tree as a list') formula = apply_func(prefix_tree, recover_formula_internal) if ((prefix_tree[0] == '~') or (len(prefix_tree) == 1)): return formula retur...
def map_starred_assignment(lhs_targets, starred_assignments, lhs_args, rhs_args): for (i, (targets, expr)) in enumerate(zip(lhs_targets, lhs_args)): if expr.is_starred: starred = i lhs_remaining = ((len(lhs_args) - i) - 1) break targets.append(expr) else: ...
class Critic(nn.Module): def __init__(self, repr_dim, action_shape, feature_dim, hidden_dim): super().__init__() self.Q1 = nn.Sequential(nn.Linear((feature_dim + (action_shape[0] * 100)), hidden_dim), nn.ReLU(inplace=True), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True), nn.Linear(hidden_d...
(datatype[(N, N)], datatype[N], datatype[N]) def trisolv(L, x, b): for i in range(0, N, 1): def init_x(): (in_b << b[i]) (out >> x[i]) out = in_b def set_x(j: _[0:i]): (in_L << L[(i, j)]) (in_x << x[j]) (out >> x(1, (lambda x, y...
def register_Ns3Dot11sPeerLinkConfirmStartPlinkConfirmStartFields_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::dot11s::PeerLinkConfirmStart::PlinkConfirmStartFields const &', 'arg0')]) cls.add_instance_attribute('aid', 'uint16_t', is_const=False) cls.add_instance_a...
def install_mpi_excepthook(): import sys from mpi4py import MPI old_hook = sys.excepthook def new_hook(a, b, c): old_hook(a, b, c) sys.stdout.flush() sys.stderr.flush() MPI.COMM_WORLD.Abort() sys.excepthook = new_hook
class TFMobileViTMobileNetLayer(tf.keras.layers.Layer): def __init__(self, config: MobileViTConfig, in_channels: int, out_channels: int, stride: int=1, num_stages: int=1, **kwargs) -> None: super().__init__(**kwargs) self.layers = [] for i in range(num_stages): layer = TFMobileVi...
def test_replace_ImageToTensor(): pipelines = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize'), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img...
def test_readxml_public_api(): assert (dir(pyhf.readxml) == ['clear_filecache', 'dedupe_parameters', 'extract_error', 'import_root_histogram', 'parse', 'process_channel', 'process_data', 'process_measurements', 'process_sample'])
class Bucket(object): def __init__(self, environment, key, checksum): self.environment = environment self.key = key self.checksum = checksum self.reset() def reset(self): self.code = None def load_bytecode(self, f): magic = f.read(len(bc_magic)) if (ma...
def format_stat(stat): if isinstance(stat, Number): stat = '{:g}'.format(stat) elif isinstance(stat, AverageMeter): stat = '{:.3f}'.format(stat.avg) elif isinstance(stat, TimeMeter): stat = '{:g}'.format(round(stat.avg)) elif isinstance(stat, StopwatchMeter): stat = '{:g}...
def read_sentences_from_conllu(filename): sents = [] cache = [] with open(filename, encoding='utf-8') as infile: for line in infile: line = line.strip() if (len(line) == 0): if (len(cache) > 0): sents.append(cache) cache...
def _match_hostname(cert, asserted_hostname): try: match_hostname(cert, asserted_hostname) except CertificateError as e: log.warning('Certificate did not match expected hostname: %s. Certificate: %s', asserted_hostname, cert) e._peer_cert = cert raise
def get_console(**kwargs) -> Console: interactive = is_interactive() from rich.theme import Theme theme = Theme(STYLES) return Console(force_jupyter=interactive, log_path=False, theme=theme, soft_wrap=True, **kwargs)
class BaseLearner(Layer): def __init__(self, module: Layer) -> None: super().__init__() self.module = module def adapt(self, loss: Tensor) -> None: raise NotImplementedError def clone(self: Type[Learner]) -> Learner: raise NotImplementedError def forward(self, *args, **kw...
('grammar', 'spider') class SpiderLanguage(): root_type = 'sql' def __init__(self, output_from=False, use_table_pointer=False, include_literals=True, include_columns=True, end_with_from=False, clause_order=None, infer_from_conditions=False, factorize_sketch=0): custom_primitive_type_checkers = {} ...
def assert_approx_equal(actual, desired, significant=7, err_msg='', verbose=True): __tracebackhide__ = True import numpy as np (actual, desired) = map(float, (actual, desired)) if (desired == actual): return with np.errstate(invalid='ignore'): scale = (0.5 * (np.abs(desired) + np.abs...
class MagmaFunction(ExpectFunction): def __call__(self, *args, **kwds): nvals = 1 if (len(kwds) > 0): if ('nvals' in kwds): nvals = kwds['nvals'] del kwds['nvals'] M = self._parent return M.function_call(self._name, list(args), params=kwds,...
def inside(): return (lambda bbox1, bbox2: ((bbox2['x1'] >= bbox1['x1']) and (bbox2['x2'] <= bbox1['x2']) and (bbox2['y1'] >= bbox1['y1']) and (bbox2['y2'] <= bbox1['y2'])))
def test_dtype(target, mix, dtype): output = wiener(target.to(dtype=dtype), mix.to(dtype=dtype), iterations=1) assert (output.dtype == dtype)
def _where_connected_to_curr_pose(start, traversible, seed, visited): non_traversible = (1 - (traversible * 1)) if (traversible[((start[0] + 1), (start[1] + 1))] == 0): count = 0 while ((traversible[((start[0] + 1), (start[1] + 1))] == 0) and (count < 100)): np.random.seed((seed + co...
def res2net50_v1b_26w_4s(pretrained=False, **kwargs): model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth=26, scale=4, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['res2net50_v1b_26w_4s'])) return model
def add_reranking_args(parser): group = parser.add_argument_group('Reranking') group.add_argument('--score-model1', '-s1', type=str, metavar='FILE', required=True, help='path to first model or ensemble of models for rescoring') group.add_argument('--score-model2', '-s2', type=str, metavar='FILE', required=F...
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): to_dir = os.path.abspath(to_dir) was_imported = (('pkg_resources' in sys.modules) or ('setuptools' in sys.modules)) try: try: import pkg_resources try: ...
def get_fixtures(func: Callable, request: FixtureRequest, given_kwargs: dict[(str, Any)]) -> dict[(str, Any)]: sig = signature(func) return {name: request.getfixturevalue(name) for name in sig.parameters if ((name != 'case') and (name not in given_kwargs))}
def zeropadding2d_args_preprocessor(args, kwargs): converted = [] if (('padding' in kwargs) and isinstance(kwargs['padding'], dict)): if (set(kwargs['padding'].keys()) <= {'top_pad', 'bottom_pad', 'left_pad', 'right_pad'}): top_pad = kwargs['padding'].get('top_pad', 0) bottom_pad...
def commodity_gen(mat, with_val=True, skip_zero=True): for x in range(mat.shape[0]): for y in range(mat.shape[(- 1)]): if (x == y): continue if (skip_zero and (mat[(x, y)] == 0)): continue if with_val: (yield (x, y, mat[(x, ...
def test_zero_der_nz_dp(): dx = (np.finfo(float).eps ** 0.33) p0 = ((200.0 - dx) / (2.0 + dx)) with suppress_warnings() as sup: sup.filter(RuntimeWarning, 'RMS of') x = zeros.newton((lambda y: ((y - 100.0) ** 2)), x0=([p0] * 10)) assert_allclose(x, ([100] * 10)) p0 = ((2.0 - 0.0001) ...
class SpikeSlab(base.Prior): def __init__(self, prob, mean, var): self.prob = prob self.mean = mean self.var = var self.rho = (prob * (var + (mean ** 2))) def __var_x(self, a, b): m_g = (((b * self.var) + self.mean) / (1.0 + (a * self.var))) v_g = (self.var / (1 +...
def tf_efficientnet_b1_ns(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet('tf_efficientnet_b1_ns', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs) return model
(version_base='1.3', config_path='../configs', config_name='enjoy') def main(cfg: EnjoyConfig): assert (cfg.infer == True) train_main(cfg)
.parametrize('axis', (0, 1, 2)) .parametrize('family', ('chebyshev',)) def test_biharmonic3D(family, axis): la = cla N = (16, 16, 16) SD = FunctionSpace(N[allaxes3D[axis][0]], family=family, bc=(0, 0, 0, 0)) K1 = FunctionSpace(N[allaxes3D[axis][1]], family='F', dtype='D') K2 = FunctionSpace(N[allaxe...
def disassemble(pdf, pars): return {k: pars[pdf.config.par_slice(k)] for k in pdf.config.par_map}
def current_actor_handle() -> ray.actor.ActorHandle: return ray.runtime_context.get_runtime_context().current_actor
_dispatch def idct(x, type=2, n=None, axis=(- 1), norm=None, overwrite_x=False, workers=None): return (Dispatchable(x, np.ndarray),)
def sa_tti(u, v, model): (A, B, C) = thomsen_mat(model) R = R_mat(model) PI = (R.T * (((A * R) * grads(u, so_fact=2)) + ((B * R) * grads(v, so_fact=2)))) MI = (R.T * (((B * R) * grads(u, so_fact=2)) + ((C * R) * grads(v, so_fact=2)))) return (divs(PI, so_fact=2), divs(MI, so_fact=2))
def adjust_learning_rate(optimizer, epoch, args): if (args.lradj == 'type1'): lr_adjust = {epoch: (args.learning_rate * (0.5 ** ((epoch - 1) // 1)))} elif (args.lradj == 'type2'): lr_adjust = {2: 5e-05, 4: 1e-05, 6: 5e-06, 8: 1e-06, 10: 5e-07, 15: 1e-07, 20: 5e-08} if (epoch in lr_adjust.key...
class TransformerDecoderLayerImproved(Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu'): super(TransformerDecoderLayerImproved, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout, use_alibi=False) self.multihea...
class DataProcessor(object): def get_train_examples(self, data_dir): raise NotImplementedError() def get_dev_examples(self, data_dir): raise NotImplementedError() def get_labels(self): raise NotImplementedError() def _read_tsv(cls, input_file, quotechar=None): with open(i...
_utils.test() def test_argument_redefinition(): def foo(a: ti.i32): a = 1 with pytest.raises(ti.TaichiSyntaxError, match='Kernel argument "a" is immutable in the kernel') as e: foo(5)
def register_Ns3EpcS11SapSgwCreateSessionRequestMessage_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::EpcS11SapSgw::CreateSessionRequestMessage const &', 'arg0')]) cls.add_instance_attribute('bearerContextsToBeCreated', 'std::list< ns3::EpcS11SapSgw::BearerContextToBeCr...
class _GlfwRenderer(imgui.integrations.glfw.GlfwRenderer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.mouse_wheel_multiplier = 1 def scroll_callback(self, window, x_offset, y_offset): self.io.mouse_wheel += (y_offset * self.mouse_wheel_multiplier)
class InputRequired(object): field_flags = ('required',) def __init__(self, message=None): self.message = message def __call__(self, form, field): if ((not field.raw_data) or (not field.raw_data[0])): if (self.message is None): message = field.gettext('This field ...
class JoinedMonitorDescription(schema_utils.Model): joiner_id = types.StringType() monitor_names = types.ListType(optplan.ReferenceType(optplan.Monitor)) monitor_type = types.StringType(choices=('scalar', 'planar', 'volume')) scalar_operation = types.StringType(choices=('magnitude_squared', 'magnitude',...
class GPipeLastPartition(GPipePartition): RECOMP_PARTITION_CLS = Partition NO_RECOMP_PARTITION_CLS = LastPartition _CLONE_INPUTS = True def __init__(self, *args, **kw): super().__init__(*args, **kw) def forward(self, x: TensorOrTensors, micro_batch_idx): x = super().forward(x, micro_...
(name='learners_data') def fixture_learners_data(breast_cancer_data, california_housing_data, california_housing_survival_data): models_data = [] (X_class_train, _, Y_class_train, _) = breast_cancer_data ngb = NGBClassifier(verbose=False, n_estimators=10) ngb.fit(X_class_train, Y_class_train) models...
class NodeNotExpandedError(InvalidSDFGNodeError): def __init__(self, sdfg: 'SDFG', state_id: int, node_id: int): super().__init__('Library node not expanded', sdfg, state_id, node_id)
def hardtanh(input, min_val=(- 1.0), max_val=1.0, inplace=False): if inplace: return torch._C._nn.hardtanh_(input, min_val, max_val) return torch._C._nn.hardtanh(input, min_val, max_val)
def generate_pt_gradient_test(configs, pt_bench_op): _register_test(configs, pt_bench_op, create_pytorch_op_test_case, True)
def arg_parse(): parser = argparse.ArgumentParser(description='Script for testing RoutedFusion') parser.add_argument('--config', required=True) args = parser.parse_args() return vars(args)
class StereoDataset(data.Dataset): def __init__(self, root='./datasets', data_file='test.list', phase='test', img_transform=None, joint_transform=None, depth_transform=None): self.root = root self.data_file = data_file self.files = [] self.phase = phase self.img_transform = i...
class PretrainedVocab(BaseVocab): def __init__(self, embedding_name, *args, **kwargs): self.type = 'pretrained' if (embedding_name not in vocab.pretrained_aliases): raise RuntimeError(f'Unknown embedding type: {embedding_name}') vector_cache = get_mmf_cache_dir() if is_ma...
class ProbingTest(absltest.TestCase): def test_array(self): A_pos = np.array([1, 2, 0, 4, 3]) expected = np.array([2, 1, 1, 4, 0]) out = probing.array(A_pos) np.testing.assert_array_equal(expected, out) def test_array_cat(self): A = np.array([2, 1, 0, 1, 1]) expec...
def get_model_modules(): _ignore_modules = ['modeling_auto', 'modeling_encoder_decoder', 'modeling_marian', 'modeling_mmbt', 'modeling_outputs', 'modeling_retribert', 'modeling_utils', 'modeling_flax_auto', 'modeling_flax_encoder_decoder', 'modeling_flax_utils', 'modeling_speech_encoder_decoder', 'modeling_flax_spe...
def log1p(g, self): return log(g, add(g, sym_help._if_scalar_type_as(g, torch.ones(1), self), self))
def set_checkpoint(config): if (config.checkpoint.filepath is not ''): config.checkpoint.monitor = os.path.join('{}-{}'.format(prepare_dataset_prefix(config.datasets.validation, config.checkpoint.monitor_index), config.checkpoint.monitor)) config.checkpoint.filepath = os.path.join(config.checkpoint....
def test_fit_predict(): lcpn = LocalClassifierPerNode(local_classifier=LogisticRegression()) x = np.array([[1, 2], [3, 4]]) y = np.array([['a', 'b'], ['b', 'c']]) lcpn.fit(x, y) predictions = lcpn.predict(x) assert_array_equal(y, predictions)
class UniversalCondition(QuantifiedCondition): def _untyped(self, parts): type_literals = [par.get_atom().negate() for par in self.parameters] return UniversalCondition(self.parameters, [Disjunction((type_literals + parts))]) def negate(self): return ExistentialCondition(self.parameters,...
class BSMNode(Node): def __init__(self, name: str, timeline: 'Timeline', other_nodes: List[str], seed=None, component_templates=None) -> None: super().__init__(name, timeline, seed) if (not component_templates): component_templates = {} bsm_name = (name + '.BSM') bsm_args...
_metric def pr50k3(opts): opts.dataset_kwargs.update(max_size=None) (precision, recall) = precision_recall.compute_pr(opts, max_real=50000, num_gen=50000, nhood_size=3, row_batch_size=10000, col_batch_size=10000) return dict(pr50k3_precision=precision, pr50k3_recall=recall)
def adaptive_clip_grad(parameters, gradients, clip_factor=0.01, eps=0.001): new_grads = [] for (params, grads) in zip(parameters, gradients): p_norm = unitwise_norm(params) max_norm = (tf.math.maximum(p_norm, eps) * clip_factor) grad_norm = unitwise_norm(grads) clipped_grad = (gr...
def proxyless_base(net_config=None, n_classes=None, bn_param=None, dropout_rate=None, local_path='~/.torch/proxylessnas/'): assert (net_config is not None), 'Please input a network config' if (' in net_config): net_config_path = download_url(net_config, local_path) else: net_config_path = ne...
def splantider(tck, n=1): if isinstance(tck, BSpline): return tck.antiderivative(n) else: return _impl.splantider(tck, n)
_method('Intracomm', 'Recv') def _intracomm_Recv(pv: 'ProgramVisitor', sdfg: SDFG, state: SDFGState, icomm: 'Intracomm', buffer: str, src: Union[(str, sp.Expr, Number)], tag: Union[(str, sp.Expr, Number)]): from mpi4py import MPI (icomm_name, icomm_obj) = icomm if (icomm_obj != MPI.COMM_WORLD): rais...
def AddEdges(depG, deps, vtoi): for tup in deps: (src, tgt) = (vtoi[tup[0]], vtoi[tup[1]]) depG.add_edge(src, tgt, label=tup[2])
def _validate_int(n, bound, name): msg = f'{name} must be an integer not less than {bound}, but got {n!r}' try: n = operator.index(n) except TypeError: raise TypeError(msg) from None if (n < bound): raise ValueError(msg) return n
def get_dataloaders(args): train_dataset = torchvision.datasets.__dict__[args.task.upper()](root=args.data, train=True, download=True) test_dataset = torchvision.datasets.__dict__[args.task.upper()](root=args.data, train=False, download=True) dataloaders = [] datasets = {} for split in ['train', 'te...
class WeightedEuclidean(Module): def __init__(self, inputSize, outputSize): super(WeightedEuclidean, self).__init__() self.weight = torch.Tensor(inputSize, outputSize) self.gradWeight = torch.Tensor(inputSize, outputSize) self.diagCov = torch.Tensor(inputSize, outputSize) sel...
def gettypeval(typename): if ('int' in typename): typeval = 123 elif ('bool' in typename): typeval = True elif (('double' in typename) or ('float' in typename)): typeval = 123.0 else: raise ValueError('Unknown type encountered') return typeval
class LinearDecayLR(_LRScheduler): def __init__(self, optimizer, args, last_epoch=(- 1), verbose=False): if args.finetune: self.lrs = ([args.lr] * (args.epochs + 1)) else: warmup_lr = [(args.warmup_min_lr + (((args.lr - args.warmup_min_lr) * i) / args.warmup_epochs)) for i in...
class NTMLayer(Layer): def __init__(self, incoming, memory, controller, heads, only_return_final=False, **kwargs): super(NTMLayer, self).__init__(incoming, **kwargs) self.memory = memory self.controller = controller self.heads = heads self.write_heads = WriteHeadCollection(he...
def test__get_pipeline_hyperparameter_dataset(): hyperparameters = {'dataset1': {'pipeline1': 'pipeline1.json', 'pipeline2': 'pipeline2.json'}} dataset = 'dataset1' expected_return = {'pipeline1': 'pipeline1.json', 'pipeline2': 'pipeline2.json'} returned = benchmark._get_pipeline_hyperparameter(hyperpar...
def test_numpytype_datetime64(): t = NumpyType('datetime64') assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t))
def range_deserialize(iodata: 'IOData') -> range: arguments = iodata.as_kwargs() return range(arguments['start'], arguments['stop'], arguments['step'])