code
stringlengths
101
5.91M
class GLPNImageProcessor(BaseImageProcessor): model_input_names = ['pixel_values'] def __init__(self, do_resize: bool=True, size_divisor: int=32, resample=PILImageResampling.BILINEAR, do_rescale: bool=True, **kwargs) -> None: self.do_resize = do_resize self.do_rescale = do_rescale self.s...
class LSTM(rf.Module): def __init__(self, in_dim: Dim, out_dim: Dim, *, with_bias: bool=True): super().__init__() self.in_dim = in_dim self.out_dim = out_dim self.ff_weight = rf.Parameter(((4 * self.out_dim), self.in_dim)) self.ff_weight.initial = rf.init.Glorot() sel...
def test_zip_and_unzip(): x = ak.Array([[1, 2, 3], [], [4, 5], [6], [7, 8, 9, 10]]) y = ak.Array([1.1, 2.2, 3.3, 4.4, 5.5]) one = ak.operations.zip({'x': x, 'y': y}) two = ak.operations.zip({'x': x, 'y': y}, depth_limit=1) (xx, yy) = ak.operations.unzip(two) assert isinstance(one.layout, ak.cont...
def ratio2weight(targets, ratio): pos_weights = (targets * (1 - ratio)) neg_weights = ((1 - targets) * ratio) weights = torch.exp((neg_weights + pos_weights)) weights[(targets > 1)] = 0.0 return weights
class TFCamembertForSequenceClassification(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class TestExecCommand(object): def setup(self): self.pyexe = get_pythonexe() def check_nt(self, **kws): (s, o) = exec_command.exec_command('cmd /C echo path=%path%') assert_((s == 0)) assert_((o != '')) (s, o) = exec_command.exec_command(('"%s" -c "import sys;sys.stderr.w...
def _format_health_check_suggestion(label: str) -> str: return f"Bypass this health check using {bold(f'`--hypothesis-suppress-health-check={label}`')}."
class BertForTokenClassification(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
class Playlist(): playlists = {} def __init__(self): self.name = input('Playlist Name:') Playlist.playlists[self.name] = self self.init_song_strings = [] self.search_results = [] self.recommended_track_ids = [] self.trax = [] self.df = None self.pl...
def pass_data_iteratively(model, graphs, minibatch_size=64): output = [] idx = np.arange(len(graphs)) for i in range(0, len(graphs), minibatch_size): sampled_idx = idx[i:(i + minibatch_size)] if (len(sampled_idx) == 0): continue output.append(model([graphs[j] for j in sam...
def compare_functions_2v(func, nloop=500, test=True, xs=xs, nmxs=nmxs, ys=ys, nmys=nmys, xl=xl, nmxl=nmxl, yl=yl, nmyl=nmyl): funcname = func.__name__ print(('-' * 50)) print(('%s on small arrays' % funcname)) (module, data) = ('numpy.ma', 'nmxs,nmys') timer(('%(module)s.%(funcname)s(%(data)s)' % lo...
def plot_throughput_reductions(data): plt.figure(figsize=(4.5, 3)) ax = plt.subplot2grid((1, 1), (0, 0), colspan=1) sns.lineplot(x='num_jobs', y='effective_throughput_reductions', style='style', hue='style', data=data, ci=None, markers=True, legend=False) ax.set_xlabel('Number of jobs') ax.set_ylabe...
class TestContinuousMLPBaseline(TfGraphTestCase): .parametrize('obs_dim', [[1], [2], [1, 1], [2, 2]]) def test_fit(self, obs_dim): box_env = GarageEnv(DummyBoxEnv(obs_dim=obs_dim)) with mock.patch('garage.tf.baselines.continuous_mlp_baseline.ContinuousMLPRegressor', new=SimpleMLPRegressor): ...
def mask_rcnn_fcn_head_v1up4convs(dim_in, roi_xform_func, spatial_scale): return mask_rcnn_fcn_head_v1upXconvs(dim_in, roi_xform_func, spatial_scale, 4)
class UnbufferedStream(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr)
def shuffle(*arrays): permutation = None n_samples = None shuffled_arrays = [] for (i, a) in enumerate(arrays): if (a is None): shuffled_arrays.append(a) continue if (permutation is None): n_samples = a.shape[0] permutation = np.random.perm...
class SymEngineMatrixHashTest(TestCase): _only def test_matrix_hash(self) -> None: hash1 = hash(sf.sympy.Matrix([[0, 1], [2, 3]])) hash2 = hash(sf.sympy.Matrix([[0, 1], [2, 4]])) hash3 = hash(sf.sympy.Matrix([[0, 1, 2, 3]])) self.assertNotEqual(hash1, 0) self.assertNotEqu...
class _Parser(): def __init__(self, parse_table, callbacks, debug=False): self.parse_table = parse_table self.callbacks = callbacks self.debug = debug def parse(self, lexer, start, value_stack=None, state_stack=None): parse_conf = ParseConf(self.parse_table, self.callbacks, start...
_REGISTRY.register() class VideoTestDataset(data.Dataset): def __init__(self, opt): super(VideoTestDataset, self).__init__() self.opt = opt self.cache_data = opt['cache_data'] (self.gt_root, self.lq_root) = (opt['dataroot_gt'], opt['dataroot_lq']) self.data_info = {'lq_path':...
def astrange_to_symrange(astrange, arrays, arrname=None): if (arrname is not None): arrdesc = arrays[arrname] if (arrdesc.shape is None): return None if (astrange is None): return [(symbolic.pystr_to_symbolic(0), (symbolic.pystr_to_symbolic(symbolic.symbol_name_or_val...
class SchubertPolynomialRing_xbasis(CombinatorialFreeModule): Element = SchubertPolynomial_class def __init__(self, R): self._name = 'Schubert polynomial ring with X basis' self._repr_option_bracket = False CombinatorialFreeModule.__init__(self, R, Permutations(), category=GradedAlgebras...
def create_save_path(args): model_name = args.model.model_name suffix = ('/{}'.format(model_name) + time.strftime('%Y-%m-%d-%H_%M_%S', time.localtime(time.time()))) from pathlib import Path saved_name = (Path(args.save_dir).stem + suffix) args.save_dir = (args.save_dir + suffix) if os.path.exist...
class InPlaceABNSync(ABN): def __init__(self, num_features, devices=None, eps=1e-05, momentum=0.1, affine=True, activation='leaky_relu', slope=0.01): super(InPlaceABNSync, self).__init__(num_features, eps, momentum, affine, activation, slope) self.devices = (devices if devices else list(range(torch....
class Maze(environment.Environment): def __init__(self, options={}): environment.Environment.__init__(self, options=options) self.configure(options) self.valid_actions = list(maze_action_enum.keys()) self.valid_observations = xrange(0, (self.max_observation() + 1)) self.valid...
def register_Ns3LtePhyTag_methods(root_module, cls): cls.add_constructor([param('ns3::LtePhyTag const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('uint16_t', 'cellId')]) cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) cls.add_method('GetCel...
def test_constructor_mutable_arg_count(test_case_mock, constructor_mock): const = stmt.ConstructorStatement(test_case_mock, constructor_mock, {'test': MagicMock(vr.VariableReference)}) assert (const._mutable_argument_count() == 1)
def resample_folder(input_folder, output_folder, fs, regex): files = glob.glob(os.path.join(input_folder, regex), recursive=True) for f in tqdm.tqdm(files): (audio, fs_read) = torchaudio.load(f) audio = audio[0].numpy() audio = signal.resample_poly(audio, fs, fs_read) peak = np.m...
def update_cfg(base_cfg, update_cfg): res_cfg = copy.deepcopy(base_cfg) res_cfg.update(update_cfg) return res_cfg
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('--triviaqa_file', help='Triviaqa file') parser.add_argument('--squad_file', help='Squad file') parser.add_argument('--wikipedia_dir', help='Wikipedia doc dir') parser.add_argument('--web_dir', help='Web doc dir') parser.add_...
def find_match_ref_at_step(collab_attr_list, all_collborators): collab_names = all_collborators.keys() matched_ref_dict = {} for collborator_name in collab_names: matched_ref_dict[collborator_name] = [] previous_collaborator = '' for attr in collab_attr_list: attr_dict = {attr: []} ...
def load_h5_data_label_normal(h5_filename): f = h5py.File(h5_filename, 'r') data = f['data'][:] label = f['label'][:] normal = f['normal'][:] return (data, label, normal)
def refine(graph: Graph, node_weight_function: NodeWeightFunction, edge_weight_function: EdgeWeightFunction, round_limit=(- 1)): re_assign_partition_indices(graph) refiner = Refiner(graph, node_weight_function, edge_weight_function) rounds = 0 num_moved = 1 total_moves = 0 while ((num_moved > 0)...
class DropoutParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _DROPOUTPARAMETER
def _adam_delta(optimizer, model, grads): deltas = {} for group in optimizer.param_groups: for param in group['params']: grad = grads[param] state = optimizer.state[param] (exp_avg, exp_avg_sq) = (state['exp_avg'], state['exp_avg_sq']) (beta1, beta2) = gro...
def common_parent_scope(sdict: ScopeDictType, scope_a: NodeType, scope_b: NodeType) -> NodeType: if (scope_a is scope_b): return scope_a if scope_contains_scope(sdict, scope_a, scope_b): return scope_a if scope_contains_scope(sdict, scope_b, scope_a): return scope_b spath_a = _sc...
class MolMap(Base): def __init__(self, ftype='descriptor', flist=None, fmap_type='grid', fmap_shape=None, split_channels=True, metric='cosine', var_thr=0.0001): super().__init__() assert (ftype in ['descriptor', 'fingerprint']), 'no such feature type supported!' assert (fmap_type in ['scatte...
def prepare(element): image = element['image'] image = tf.cast(image, tf.float32) return image
class FreeModule_ambient_field(FreeModule_generic_field, FreeModule_ambient_pid): def __init__(self, base_field, dimension, sparse=False, category=None): FreeModule_ambient_pid.__init__(self, base_field, dimension, sparse=sparse, category=category) def _repr_(self): if self.is_sparse(): ...
def __recompute_bwweights(G, M, E, D, T): weightscale = 10000 if (((3 * E) >= T) and ((3 * G) >= T)): casename = 'Case 1 (Wgd=Wmd=Wed)' Wgd = Wed = Wmd = (weightscale / 3) Wee = ((weightscale * ((E + G) + M)) / (3 * E)) Wme = (weightscale - Wee) Wmg = ((weightscale * (((2...
def write_labels(dirpath, dictionary): print(('Writing labels for trees in ' + dirpath)) with open(os.path.join(dirpath, 'labels.txt'), 'w') as labels, open(os.path.join(dirpath, 'dlabels.txt'), 'w') as dlabels: (const_trees, dep_trees, toks) = load_trees(dirpath) for i in xrange(len(const_trees...
def get_activation_distance_stats(activations_0, activations_1, layer_name=''): if (layer_name != ''): print('In layer {}: getting activation distance statistics'.format(layer_name)) M = (cost_matrix(activations_0, activations_1) ** (1 / 2)) mean_dists = torch.mean(M, dim=(- 1)) max_dists = torc...
class GeneralBlock(ControlFlow): elements: List[ControlFlow] gotos_to_ignore: Sequence[Edge[InterstateEdge]] gotos_to_continue: Sequence[Edge[InterstateEdge]] gotos_to_break: Sequence[Edge[InterstateEdge]] assignments_to_ignore: Sequence[Edge[InterstateEdge]] sequential: bool def as_cpp(self...
def gpu_mem_usage(): if (not torch.cuda.is_available()): return 0 _B_IN_GB = ((1024 * 1024) * 1024) mem_usage_bytes = torch.cuda.max_memory_allocated() return (mem_usage_bytes / _B_IN_GB)
class LearnerModelParallel(nn.Module): def __init__(self, module, sections): super(LearnerModelParallel, self).__init__() self.module = module.cuda() self.sections = sections self.num_sections = len(self.sections) self._scatter_sections() def _scatter_sections(self): ...
def main(): import argparse import pickle as pkl parser = argparse.ArgumentParser() parser.add_argument('datafile', type=str, help='sequences to embed') parser.add_argument('model', type=str, help='which model to use') parser.add_argument('--load-from', type=str, default=None, help='file from wh...
class MADGRAD(torch.optim.Optimizer): def __init__(self, params: _params_t, lr: float=0.01, momentum: float=0.9, weight_decay: float=0, eps: float=1e-06, decoupled_decay: bool=False): if ((momentum < 0) or (momentum >= 1)): raise ValueError(f'Momentum {momentum} must be in the range [0,1]') ...
def visualize_predictions(frame_sequence, one_hot_pred, one_hot_gt, many_hot_pred=None, many_hot_gt=None): batch_size = len(frame_sequence) images = [] for i in range(batch_size): scene = frame_sequence[i] scene_labels = one_hot_gt[i] scene_one_hot_pred = one_hot_pred[i] scen...
def main_random(split, logit_file, is_training=False, num_retain=10, force_diff=FORCE_DIFF_CONFIG): import random random.seed(123) candidate_info = load_candidates_file(f'outputs/grail_{split}_candidates-ranking.jsonline') logit_info = torch.load(logit_file) gen_dataset = [] num_spec = 0 top...
def gen_rest_table_index(obj, names=None, sort=True, only_local_functions=True, root=None): if (names is None): names = {} if (inspect.isclass(obj) or inspect.ismodule(obj)): (list_of_entries, names) = list_of_subfunctions(obj, only_local_functions=only_local_functions) else: list_of...
def asy_calc_old(create_loss, nbins): (loss, (Nsig, Nbkg, mean, sigma)) = create_loss(npeak=10, nbins=nbins) mean.floating = False sigma.floating = False return (Nsig, AsymptoticCalculatorOld(loss, Minuit()))
def build_criterion(args): weight = torch.ones(args.num_classes) weight[args.eos_index] = args.eos_loss_coef criterion = nn.CrossEntropyLoss(weight=weight, ignore_index=args.padding_index) device = torch.device('cuda') criterion = criterion.to(device) return criterion
class InspectDialogPhenomena(object): def __init__(self, config): super().__init__() self.config = config self.data_dir = config.data_dir self.save_data_dir = config.save_data_dir self.weather_list = ['rainy', 'sunny', 'daytime', 'day', 'night'] self.difficult_pronoun...
def up_stage(inputs, skip, filters, kernel_size=3, activation='relu', padding='SAME'): up = UpSampling2D()(inputs) up = Conv2D(filters, 2, activation=activation, padding=padding)(up) up = GroupNormalization()(up) merge = concatenate([skip, up]) merge = GroupNormalization()(merge) conv = Conv2D(f...
def reg_component(name, c): global _Id, _Components, _ComponentNames, _Name2Component c.id = _Id _Id = (_Id + 1) _Components.append(c) _ComponentNames.add(name) _Name2Component[name] = c if VERBOSE: print(("New component: '%s'" % name))
.parametrize('alphas', ALPHAS) def test_compute_quantiles_2D_and_3D(alphas: NDArray): vector1 = np.random.rand(1000, 1) vector2 = np.repeat(vector1, len(alphas), axis=1) quantiles1 = compute_quantiles(vector1, alphas) quantiles2 = compute_quantiles(vector2, alphas) assert (quantiles1 == quantiles2)....
def log_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): dy = grad_inputs[0] x0 = inputs[0] dx0 = (dy / x0) return dx0
_model def res2next50(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['res2next50'] res2net_block_args = dict(scale=4) model = ResNet(Bottle2neck, [3, 4, 6, 3], base_width=4, cardinality=8, num_classes=num_classes, in_chans=in_chans, block_args=res2net_block_args, **kwa...
def init_dist(backend='nccl', **kwargs): if (mp.get_start_method(allow_none=True) != 'spawn'): mp.set_start_method('spawn') rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() torch.cuda.set_device((rank % num_gpus)) dist.init_process_group(backend=backend, **kwargs)
def register_Ns3MmWaveMacPduTag_methods(root_module, cls): cls.add_constructor([param('ns3::MmWaveMacPduTag const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::SfnSf', 'sfn')]) cls.add_constructor([param('ns3::SfnSf', 'sfn'), param('uint8_t', 'symStart'), param('uint8_t', 'numSy...
class RandomDataSplit(BaseTransform): def __init__(self, num_nodes_per_class, train_ratio=0.7, test_ratio=0.2): self.num_nodes_per_class = num_nodes_per_class self.train_ratio = train_ratio self.test_ratio = test_ratio def __call__(self, data: Data) -> Data: y = data.y nu...
def norm_point_xyxy(point, *, w, h): (x, y) = point norm_x = max(0.0, min((x / w), 1.0)) norm_y = max(0.0, min((y / h), 1.0)) point = (norm_x, norm_y) return point
def make_install_req_from_link(link, template): assert (not template.editable), 'template is editable' if template.req: line = str(template.req) else: line = link.url ireq = install_req_from_line(line, user_supplied=template.user_supplied, comes_from=template.comes_from, use_pep517=templ...
_criterion('nat_loss') class LabelSmoothedDualImitationCriterion(FairseqCriterion): def __init__(self, task, label_smoothing): super().__init__(task) self.label_smoothing = label_smoothing def add_args(parser): parser.add_argument('--label-smoothing', default=0.0, type=float, metavar='D'...
class SpectralNorm(): _version: int = 1 name: str dim: int n_power_iterations: int eps: float def __init__(self, name: str='weight', n_power_iterations: int=1, dim: int=0, eps: float=1e-12) -> None: self.name = name self.dim = dim if (n_power_iterations <= 0): ...
def thresholding(S: np.ndarray, thresh: Union[(str, float)]) -> np.ndarray: if (thresh == 'auto'): mu = np.median(S) sig = (np.median(np.abs((S - mu))) / 0.675) thresh = norm.ppf((1 - 1e-06), loc=mu, scale=sig) M = (S >= thresh) return M
def load_model(file_name, gpu=False): with open(file_name, 'rb') as f: model = torch.load(f, map_location=(lambda storage, loc: storage)) print('gpu:', gpu) if (not gpu): model.set_device_id(None) else: model.cuda() return model
def _register_pytree_node(typ: Any, flatten_fn: FlattenFunc, unflatten_fn: UnflattenFunc) -> None: SUPPORTED_NODES[typ] = NodeDef(flatten_fn, unflatten_fn)
class Subsets_sk(Subsets_s): def __init__(self, s, k): Subsets_s.__init__(self, s) self._k = Integer(k) if (self._k < 0): raise ValueError('the integer k (={}) should be non-negative'.format(k)) def _repr_(self): return (Subsets_s._repr_(self) + ' of size {}'.format(s...
_model def ig_resnext101_32x32d(pretrained=True, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=32, base_width=32, **kwargs) return _create_resnet('ig_resnext101_32x32d', pretrained, **model_args)
def ndrange(slice_list: Union[(Tuple[slice], slice)]): if (not isinstance(slice_list, (tuple, list))): (yield from slicetoxrange(slice_list)) else: ndxrange = tuple((slicetoxrange(d) for d in slice_list)) for indices in itertools.product(*ndxrange): (yield indices)
def getargvalues(frame): (args, varargs, varkw) = getargs(frame.f_code) return (args, varargs, varkw, frame.f_locals)
class RetinaNetModule(torch.nn.Module): def __init__(self, cfg, in_channels): super(RetinaNetModule, self).__init__() self.cfg = cfg.clone() anchor_generator = make_anchor_generator_retinanet(cfg) head = RetinaNetHead(cfg, in_channels) box_coder = BoxCoder(weights=(10.0, 10.0...
class BiLSTMp(nn.Module): def __init__(self, input_size, hidden_size, proj_size, layers, proj_activ='tanh', dropout=0): super().__init__() self.input_size = input_size self.hidden_size = hidden_size self.proj_size = proj_size self.layers = [int(i) for i in layers.split('_')] ...
class BucketingSampler(Sampler): def __init__(self, data_source, batch_size=1): super(BucketingSampler, self).__init__(data_source) self.data_source = data_source ids = list(range(0, len(data_source))) self.bins = [ids[i:(i + batch_size)] for i in range(0, len(ids), batch_size)] ...
class UnpairedImageTest(UnpairedImageBase): def __init__(self, size=None, random_crop=False, folder1=None, folder2=None, numpy_folder1=None, numpy_folder2=None, wikiart_info1=None, wikiart_key1=None, wikiart_info2=None, wikiart_key2=None): super().__init__() self.data = UnpairedImagePaths(size=size,...
def load_img_future_de_haze_revide(filepath, nFrames, img_id, phase='train'): tt = int((nFrames / 2)) img_id = (img_id + tt) num_dir = filepath.split('/')[3] if (phase == 'train'): targetPath = ('Dataset/REVIDE/Train_GT/' + num_dir) else: targetPath = ('Dataset/REVIDE/Test_GT/' + num...
def load_and_cache_rank_examples(args, tokenizer, evaluate=False): if (args.dataset == 'grail'): return grail_load_and_cache_rank_examples(args, tokenizer, evaluate=evaluate) elif (args.dataset == 'webqsp'): return webqsp_load_and_cache_rank_examples(args, tokenizer, evaluate=evaluate) else:...
class CohereTokenCostEstimator(TokenCostEstimator): def estimate_tokens(self, request: Request, metric_service: MetricService) -> int: return (request.num_completions * request.max_tokens)
def pytest_addoption(parser): group = parser.getgroup('schemathesis') group.addoption('--schemathesis-io-token', action='store', default=DEFAULT_SERVICE_TOKEN, help='A token to access the test Schemathesis.io instance.')
def parse_encoder(parser, arg_str=None): enc_parser = parser.add_argument_group() enc_parser.add_argument('--conv_type', type=str, help='type of convolution') enc_parser.add_argument('--method_type', type=str, help='type of embedding') enc_parser.add_argument('--batch_size', type=int, help='Training bat...
def get_render_func(venv): if hasattr(venv, 'envs'): return venv.envs[0].render elif hasattr(venv, 'venv'): return get_render_func(venv.venv) elif hasattr(venv, 'env'): return get_render_func(venv.env) return None
def binop_node(pos, operator, operand1, operand2, inplace=False, **kwargs): return binop_node_classes[operator](pos, operator=operator, operand1=operand1, operand2=operand2, inplace=inplace, **kwargs)
_if_32bit .parametrize('csr_container', CSR_CONTAINERS) def test_countvectorizer_sort_features_64bit_sparse_indices(csr_container): X = csr_container((5, 5), dtype=np.int64) INDICES_DTYPE = np.int64 X.indices = X.indices.astype(INDICES_DTYPE) X.indptr = X.indptr.astype(INDICES_DTYPE) vocabulary = {'...
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', use_xavier=True, stddev=0.001, weight_decay=None, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: (kernel_h, kernel_w) = kernel_size num_in_...
def parse_args(): parser = argparse.ArgumentParser(description='MMAction2 check datasets') parser.add_argument('config', help='test config file path') parser.add_argument('--options', nargs='+', action=DictAction, default={}, help='custom options for evaluation, the key-value pair in xxx=yyy format will be ...
((not have_sympy), 'SymPy not installed') def test_conv4(): x = Symbol('x') y = Symbol('y') z = Symbol('z') e = (x ** y) assert (e._sympy_() == (sympy.Symbol('x') ** sympy.Symbol('y'))) e = ((x + y) ** z) assert (e._sympy_() == ((sympy.Symbol('x') + sympy.Symbol('y')) ** sympy.Symbol('z')))
class textSpace(gym.spaces.Space): def contains(self, x) -> bool: return isinstance(x, str)
def read_segmentation(filename): assert os.path.isfile(filename) seg_to_verts = {} with open(filename) as f: data = json.load(f) num_verts = len(data['segIndices']) for i in range(num_verts): seg_id = data['segIndices'][i] if (seg_id in seg_to_verts): ...
class GradMixin(): def _resize(preprocess_function, image): assert (image.shape[0] == 1), '`image` can contain one instance only.' if (preprocess_function is None): return image y = image.to_numpy() x = preprocess_function(image) if (not isinstance(x, np.ndarray))...
def modify_notebook(path: Path, config: dict) -> None: notebook = path.read_text(encoding='utf-8') if ('# quickrun' in notebook): logger.warning('Already modified %s for quickrun', path.name) return for repl in config['replace']: repl_from = '^(( *){})$'.format(repl['from']) ...
def add_toctree_functions(app, pagename, templatename, context, doctree): from sphinx.environment.adapters.toctree import TocTree def get_nav_object(maxdepth=None, collapse=True, numbered=False, **kwargs): toctree = TocTree(app.env).get_toctree_for(pagename, app.builder, collapse=collapse, maxdepth=maxd...
class IfScope(ControlFlow): sdfg: SDFG branch_state: SDFGState condition: CodeBlock body: GeneralBlock orelse: Optional[GeneralBlock] = None def as_cpp(self, codegen, symbols) -> str: condition_string = unparse_interstate_edge(self.condition.code[0], self.sdfg, codegen=codegen) e...
def test__detrend_signal_no_trend(): df = pd.DataFrame({'timestamp': range(5), 'value': ([0.0] * 5)}) expected_return = df.copy() returned = benchmark._detrend_signal(df, 'value') pd.testing.assert_frame_equal(returned, expected_return)
class QObserverBenchmark(op_bench.TorchBenchmarkBase): def init(self, C, M, N, dtype, qscheme, op_func, device): self.f_input = torch.rand(C, M, N, device=device) self.op_func = op_func(dtype=dtype, qscheme=qscheme).to(device) def forward(self): self.op_func(self.f_input) self.op...
class DetaModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TrainerSchool(): cfg: T.DictConfig model: T.Module def init_school(self) -> T.Module: return stad.models.School() def load_pretrained_model(self): self.school.load_state_dict(torch.load(self.cfg.model.school.pretrained))
def get_ae(**model_cfg): arch = model_cfg.pop('arch') x_dim = model_cfg.pop('x_dim') z_dim = model_cfg.pop('z_dim') enc_cfg = model_cfg.pop('encoder') dec_cfg = model_cfg.pop('decoder') if (arch == 'ae'): encoder = get_net(in_dim=x_dim, out_dim=z_dim, **enc_cfg) decoder = get_net...
def all_but(train: list[Example], x: Example) -> list[Example]: output = [y for y in train if (not set.intersection(set((x.get('history', []) + [x.question])), set((y.get('history', []) + [y.question]))))] return output
class Dataset_ETT_hour(Dataset): def __init__(self, root_path, flag='train', size=None, features='S', data_path='ETTh1.csv', target='OT', scale=True, timeenc=0, freq='h'): if (size == None): self.seq_len = ((24 * 4) * 4) self.label_len = (24 * 4) self.pred_len = (24 * 4) ...
class AmbientSpace(ambient_space.AmbientSpace): def dimension(self): return self.root_system.cartan_type().rank() def root(self, i, j, p1, p2): if (i != j): return ((((- 1) ** p1) * self.monomial(i)) + (((- 1) ** p2) * self.monomial(j))) return (((- 1) ** p1) * self.monomial(...