code
stringlengths
101
5.91M
class GenericExperiment(): def __init__(self, name, description, run_method): self.name = name self.description = description self.run_method = run_method run_args = ['num_samples', 'seed', 'parallelize', 'show_progress'] self.params = extract_params(run_method, run_args) ...
class TokenClassificationFields(Preprocessing): tokens: str = 'tokens' labels: str = 'labels'
class BasicBlock(nn.Module): def __init__(self, inplanes, planes, stride, downsample, residual=True): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(pla...
class ScenarioConfig(): name: str = 'intersection' kwargs: Dict[(str, Any)] = field(default_factory=(lambda : {})) tasks: List[str] = field(default_factory=(lambda : [])) net_path: str = '' route_path: str = '' add_path: str = '' seed_offset: int = 0 seeding_mode: str = 'train' num_m...
.parametrize('backend', ['pydub']) .parametrize('channel_first', [False, True]) .parametrize('audio', audios) .parametrize('source_type', ['string', 'binaryFileHandler', 'BytesIO', 'StringIO', 'strFileHandler']) def test_ausave_and_auread(tmpdir, backend, channel_first, audio, source_type): _change_backend(backend)...
.pure def test_reshape_add(): def add_reshape(inp: dace.float64[9], bias: dace.float64[3], target_shape: dace.int64[2]): reshaped = dace.define_local([3, 3], dace.float64) donnx.ONNXReshape(data=inp, shape=target_shape, reshaped=reshaped) return (reshaped + bias) sdfg: dace.SDFG = add_re...
def mlp_actor_critic(x, a, hidden_sizes=(400, 300), activation=tf.nn.relu, output_activation=tf.tanh, action_space=None): act_dim = a.shape.as_list()[(- 1)] act_limit = action_space.high[0] with tf.variable_scope('pi'): pi = (act_limit * mlp(x, (list(hidden_sizes) + [act_dim]), activation, output_ac...
class RedirectOut(): def __init__(self, out): super().__init__() self.out = out self.original = sys.stdout def __enter__(self): self.__fd = open(self.out, 'w') sys.stdout = self.__fd def __exit__(self, type, value, traceback): sys.stdout = self.original ...
class AugustSmartLockGenerateTemporaryAccessCode(VirtualFunctionTool): name = 'AugustSmartLockGenerateTemporaryAccessCode' summary = 'Generates a temporary access code that can be used to unlock the door for a specified period of time.' parameters: List[ArgParameter] = [{'name': 'start_time', 'type': 'strin...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, OurTrainingArguments, RetrieverArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args, bertscore_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) ...
class GaussianStrategy(ExplorationStrategy): def __init__(self, env_spec, max_sigma=1.0, min_sigma=0.1, decay_period=1000000): assert isinstance(env_spec.action_space, gym.spaces.Box) assert (len(env_spec.action_space.shape) == 1) self._max_sigma = max_sigma self._min_sigma = min_sig...
def nes_op_ray_amplitude(ray, nes_op, velocity='interpolation'): assert (velocity in velocities_list), ("Two options are supported for velocity evaluation: 'interpolation' and " + "'learned velocity'.") dims = np.shape(ray)[(- 1)] ray_times = np.squeeze(nes_op.Traveltime(ray)) laplacians = np.squeeze(ne...
def tile_images(img_nhwc): img_nhwc = np.asarray(img_nhwc) (N, h, w, c) = img_nhwc.shape H = int(np.ceil(np.sqrt(N))) W = int(np.ceil((float(N) / H))) img_nhwc = np.array((list(img_nhwc) + [(img_nhwc[0] * 0) for _ in range(N, (H * W))])) img_HWhwc = img_nhwc.reshape(H, W, h, w, c) img_HhWwc ...
class Loader(yaml.Loader, metaclass=LoaderMeta): def __init__(self, stream): try: self._root = os.path.split(stream.name)[0] except AttributeError: self._root = os.path.curdir super().__init__(stream) def construct_include(self, node): filename = os.path.a...
def prepare_data_seq(task, batch_size=100): file_train = 'data/KVR/train_graph.txt' file_dev = 'data/KVR/dev_graph.txt' file_test = 'data/KVR/test_graph.txt' (pair_train, train_max_len) = read_langs(file_train, max_line=None) (pair_dev, dev_max_len) = read_langs(file_dev, max_line=None) (pair_te...
class IInt8MinMaxCalibrator(CalibratorBase, trt.IInt8MinMaxCalibrator): def __init__(self, *args, **kwargs): CalibratorBase.__init__(self, *args, **kwargs) trt.IInt8MinMaxCalibrator.__init__(self)
class PerformanceTable(): def __init__(self, percentiles, unit, reverse_percentiles=False): self.percentiles = percentiles self.data = collections.defaultdict(dict) self.unit = unit self.reverse_percentiles = reverse_percentiles def add(self, key, value): (math, value) = ...
def classifier_layers(x, input_shape, trainable=False): if (K.backend() == 'tensorflow'): x = conv_block_td(x, 3, [512, 512, 2048], stage=5, block='a', input_shape=input_shape, strides=(2, 2), trainable=trainable) elif (K.backend() == 'theano'): x = conv_block_td(x, 3, [512, 512, 2048], stage=5,...
def rf_importance(models): return np.array([m.feature_importances_ for m in models]).mean(axis=0)
class Iter_LR_Scheduler(object): def __init__(self, args, max_iteration, iters_per_epoch): self.mode = args.mode print('Using {} LR Scheduler!'.format(self.mode)) self.lr = args.base_lr self.lr_step = args.lr_step self.iters_per_epoch = iters_per_epoch self.max_iterat...
def hash_loop(data): param = np.vstack(data['param']) cmd = np.hstack(data['cmd']) hash_str = ((sha256(np.ascontiguousarray(param).flatten()).hexdigest() + '_') + sha256(np.ascontiguousarray(cmd).flatten()).hexdigest()) uid = data['tmp_uid'] return (hash_str, uid)
def test_missing_contrib_extra(caplog): with mock.patch.dict(sys.modules): sys.modules['requests'] = None if ('pyhf.contrib.utils' in sys.modules): reload(sys.modules['pyhf.contrib.utils']) else: import_module('pyhf.contrib.utils') with caplog.at_level(logging.ERR...
def unwrap_node(node): while isinstance(node, UtilNodes.ResultRefNode): node = node.expression return node
class DistillKL(nn.Module): def __init__(self, T): super(DistillKL, self).__init__() self.T = T def forward(self, y_s, y_t): p_s = F.log_softmax((y_s / self.T), dim=1) p_t = F.softmax((y_t / self.T), dim=1) loss = ((F.kl_div(p_s, p_t, size_average=False) * (self.T ** 2)) ...
class RecoveryLikelihood(tf.keras.Model): def __init__(self, hps): super(RecoveryLikelihood, self).__init__() self.hps = hps self.num_timesteps = FLAGS.num_diffusion_timesteps (self.sigmas, self.a_s) = get_sigma_schedule(beta_start=0.0001, beta_end=0.02, num_diffusion_timesteps=self....
class DoubleType(FloatType): __slots__ = () exp = 11 frac = 53 def __str__(self): return 'double'
class TestDiverseSiblingsSearch(TestDiverseBeamSearch): def assertHypoScore(self, hypo, pos_probs, sibling_rank, diversity_rate, normalized=True, lenpen=1.0): pos_scores = torch.FloatTensor(pos_probs).log() pos_scores.sub_((torch.Tensor(sibling_rank) * diversity_rate)) self.assertAlmostEqual...
.skipif((not _ti_core.GGUI_AVAILABLE), reason='GGUI Not Available') _utils.test(arch=supported_archs) def test_draw_part_of_particles_per_vertex_rad_and_col_old(): N = 10 particles_pos = ti.Vector.field(3, dtype=ti.f32, shape=N) particles_col = ti.Vector.field(3, dtype=ti.f32, shape=N) particles_radii =...
class DomainRegistrarService(Service): def __init__(self): super().__init__() self.addDependency('Base', False, False) def getName(self) -> str: return 'DomainRegistrarService' def _createServer(self) -> DomainRegistrarServer: return DomainRegistrarServer() def _doConfigu...
class ProteinOneHotAbstractModel(ProteinModel): config_class = ProteinOneHotConfig pretrained_model_archive_map: typing.Dict[(str, str)] = {} base_model_prefix = 'onehot' def _init_weights(self, module): if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mea...
class RecordLookup(ContentLookup): LENGTH = 0 CONTENTS = 1 def tolookup(cls, layout, positions): pos = len(positions) positions.append(len(layout)) positions.extend(([None] * len(layout.contents))) for (i, content) in enumerate(layout.contents): positions[((pos + ...
class _VocabParallelCrossEntropy(torch.autograd.Function): def forward(ctx, vocab_parallel_logits, target): logits = vocab_parallel_logits.clone() logits_max = torch.max(logits, dim=(- 1))[0] torch.distributed.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=get_model_parallel...
def configure_ws_ovpn_container(): base_path = 'ws-ovpn/' env_file = (base_path + 'ovpn_env.sh') change_line(env_file, 24, (('declare -x OVPN_SERVER_URL=udp://' + str(os.getenv('GW_NETWORK_HEAD'))) + '.0.10'))
def gather(outputs, target_device, dim=0): error_msg = 'outputs must contain tensors, numbers, dicts or lists; found {}' def gather_map(outputs): out = outputs[0] elem_type = type(out) if isinstance(out, Variable): return Gather.apply(target_device, dim, *outputs) if ...
def test_parse_path(): assert (parse_path('/') == ('local', '/', '/')) assert (parse_path('/tmp') == ('local', '/tmp', '/tmp')) assert (parse_path('does-not-exist-0000000/file') == ('local', 'does-not-exist-0000000/file', 'does-not-exist-0000000/file')) assert (parse_path('s3://bucket') == ('aws', 'buck...
def detections_to_tracks(detections): tracks = defaultdict(list) for det in detections: tracks[det.track_id].append(det) for track_id in tracks: tracks[track_id] = sorted(tracks[track_id], key=(lambda d: d.frame_id)) return list(tracks.values())
class MultiDecoder(object): def __init__(self, modes): self._decoders = [_get_decoder(m.strip()) for m in modes.split(',')] def flush(self): return self._decoders[0].flush() def decompress(self, data): for d in reversed(self._decoders): data = d.decompress(data) r...
def test_pbmc_cite(save_path): file_path = os.path.join(save_path, '10X/pbmc_10k_protein_v3/filtered_feature_bc_matrix.tar.gz') sp = os.path.join(save_path, '10X/pbmc_10k_protein_v3/') tar = tarfile.open(file_path, 'r:gz') tar.extractall(path=sp) tar.close() dataset = sc.read_10x_mtx(os.path.joi...
def test_se_layer(): with pytest.raises(AssertionError): SELayer(channels=32, act_cfg=(dict(type='ReLU'),)) with pytest.raises(AssertionError): SELayer(channels=32, act_cfg=[dict(type='ReLU'), dict(type='ReLU')]) layer = SELayer(channels=32) layer.init_weights() layer.train() x =...
class MockDDPWrapper(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, x): return self.module(x)
class C(FairseqDataclass): data: str = field(default='test', metadata={'help': 'root level data input'}) encoder: D = field(default=D()) decoder: A = field(default=A()) lr: int = field(default=0, metadata={'help': 'learning rate'})
class TextDecoder(): def __init__(self, vocab): self._vocab = vocab self._vocab_size = vocab.get_size() self._complete_seqs = [] self._complete_seqs_scores = [] def init_batch(self, sample_list): img_size = sample_list.image_feature_0.size() (self._batch_size, fea...
def search_limbs(data_source: str, mask: Optional[Union[(np.ndarray, tuple, list)]]=None, keypoints_factory: dict=KEYPOINTS_FACTORY) -> Tuple[(dict, dict)]: limbs_source = HUMAN_DATA_LIMBS_INDEX limbs_palette = HUMAN_DATA_PALETTE keypoints_source = keypoints_factory['human_data'] keypoints_target = keyp...
def test_WatchYourStep_save_load(tmpdir, barbell): generator = AdjacencyPowerGenerator(barbell, num_powers=5) wys = WatchYourStep(generator) test_utils.model_save_load(tmpdir, wys)
def annotations_to_instances(annos, image_size, sample_points=0): target = base_annotations_to_instances(annos, image_size) assert ('point_coords' in annos[0]) assert ('point_labels' in annos[0]) assert ('segmentation' not in annos[0]), 'Please remove mask annotation' if (len(annos) and ('point_labe...
def get_model(data_path='/tmp'): model_name = 'zoo:sensitive_topics_classifier/model' model_file = modelzoo_path(data_path, model_name) optfile = (model_file + '.opt') opt = Opt.load(optfile) TCA.upgrade_opt(opt) opt['model_file'] = model_file opt['dict_file'] = (model_file + '.dict') mo...
def convert_secs2time(epoch_time, return_str=False): need_hour = int((epoch_time / 3600)) need_mins = int(((epoch_time - (3600 * need_hour)) / 60)) need_secs = int(((epoch_time - (3600 * need_hour)) - (60 * need_mins))) if return_str: str = '[{:02d}:{:02d}:{:02d}]'.format(need_hour, need_mins, n...
def randmat(shape, name, mu=0.0, type_init='he2', type_dist='normal', trainable=True, extra_scale=1.0): if (len(shape) == 1): (dim_in, dim_out) = (shape[0], 0) elif (len(shape) == 2): (dim_in, dim_out) = shape else: (dim_in, dim_out) = (np.prod(shape[1:]), shape[0]) if (type_init...
class ExplicitEnum(Enum): def _missing_(cls, value): raise ValueError(('%r is not a valid %s, please select one of %s' % (value, cls.__name__, str(list(cls._value2member_map_.keys())))))
def main(): parser = argparse.ArgumentParser(description='Training') parser.add_argument('--model', type=str, default='unets', metavar='model', help='training model name, uit (integral transformer), ut (with traditional softmax normalization), hut (hybrid ut with linear attention), xut (cross-attention with had...
def test_recordarray_1(): def func_recordarray_1(x): return ((2 * x.y[2][0][1]) + 10) (value_jvp, jvp_grad) = jax.jvp(func_recordarray_1, (test_recordarray,), (test_recordarray_tangent,)) (value_vjp, vjp_func) = jax.vjp(func_recordarray_1, test_recordarray) assert (ak.to_list(value_jvp) == 14.0)...
def get_ava_eval_data(scores, boxes, metadata, class_whitelist, verbose=False, video_idx_to_name=None): out_scores = defaultdict(list) out_labels = defaultdict(list) out_boxes = defaultdict(list) count = 0 for i in range(scores.shape[0]): video_idx = int(np.round(metadata[i][0])) sec...
def _sympysage_polynomial(self): base_ring = self.domain._sage_() variables = ','.join(map(str, self.gens)) R = base_ring[variables] return R.sum(((base_ring(coeff) * R.monomial(*exp)) for (exp, coeff) in self.rep.terms(order=None)))
def perspectivex_grid(output_size, ulim=(1, 8), vlim=((((- 0.99) * np.pi) / 2), ((0.99 * np.pi) / 2)), out=None, device=None): (nv, nu) = output_size urange = torch.linspace(ulim[0], ulim[1], nu, device=device) vrange = torch.linspace(vlim[0], vlim[1], (nv // 2), device=device) (vs, us) = torch.meshgrid...
def onnx_verify(onnx_model, inputs, ref_outputs): prepared = caffe2.python.onnx.backend.prepare(onnx_model) onnx_inputs = [] for input in inputs: if isinstance(input, tuple): onnx_inputs.append(input[1]) else: onnx_inputs.append(input) onnx_outputs = prepared.run(...
def test_inner_dereference(testdir): testdir.make_test('\(method="POST")\(max_examples=1)\ndef test_(request, case):\n request.config.HYPOTHESIS_CASES += 1\n assert case.path == "/users"\n assert case.method == "POST"\n assert_int(case.body["id"])\n', paths={'/users': {'post': {'parameters': [{'schema':...
def _save_eval_stats(opt, report): if (not is_primary_worker): return report_fname = opt['report_filename'] if (report_fname == ''): return json_serializable_report = report for (k, v) in report.items(): if isinstance(v, Metric): v = v.value() json_seriali...
.parametrize('flatlist_as_rvec', [False, True]) def test_nested_NumpyArray(flatlist_as_rvec): v2a = ak.contents.ListOffsetArray(ak.index.Index64(np.array([0, 1, 5], dtype=np.int64)), ak.contents.numpyarray.NumpyArray(np.array([999.0, 0.0, 1.1, 2.2, 3.3]), parameters={'some': 'stuff', 'other': [1, 2, 'three']})) ...
def _seed_dataset_transform(transform, seed=None): if isinstance(transform, Compose): for subtransform in transform.transforms: _seed_dataset_transform(subtransform, seed=seed) elif hasattr(transform, 'seed'): transform.seed(seed=seed)
def modification_time(representation_list): return max((r['modified'] for r in representation_list))
class FPN(tf.keras.layers.Layer): def __init__(self, filters=256, min_level=3, max_level=7, backbone_max_level=5, fusion_mode=None, conv_2d_op_params=None, normalization_op_params=None, activation_fn=None, **kwargs): if (activation_fn is None): raise ValueError('`activation_fn` cannot be None') ...
def test_checkpoint_hook_register(tmpdir): from speechbrain.utils.checkpoints import register_checkpoint_hooks from speechbrain.utils.checkpoints import mark_as_saver from speechbrain.utils.checkpoints import mark_as_loader from speechbrain.utils.checkpoints import Checkpointer _checkpoint_hooks ...
def random_topology_func(op_names, max_nodes=4): def random_architecture(): genotypes = [] for i in range(1, max_nodes): xlist = [] for j in range(i): node_str = '{:}<-{:}'.format(i, j) op_name = random.choice(op_names) xlist.ap...
def number_of_arguments(func): if isinstance(func, functools.partial): total_args = len(inspect.signature(func.func).parameters) return ((total_args - len(func.args)) - len(func.keywords)) return len(inspect.signature(func).parameters)
def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): if (pool_type == 'avgmaxc'): x = torch.cat([F.avg_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad), F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding)], di...
def test_set_log_level(caplog): cashocs.set_log_level(cashocs.LogLevel.DEBUG) issue_messages() if (fenics.MPI.rank(fenics.MPI.comm_world) == 0): assert ('abc' in caplog.text) assert ('def' in caplog.text) assert ('ghi' in caplog.text) assert ('jkl' in caplog.text) ass...
class ScliteJob(Job): def __init__(self, name, refs, hyps): self.name = name self.refs = refs self.hyps = hyps self.output_sclite_dir = self.output_path('sclite-out', directory=True) def create_stm(name, source_filename, target_filename): py_txt = eval(generic_open(source...
def from_dr_metadata(d: dr.Metadata) -> Metadata: fields = [from_dr_field(x) for x in d.fields] kernels = [from_dr_kernel(x) for x in d.kernels] required_caps = [] for cap in d.required_caps: if (cap.value == 1): required_caps += [cap.key] else: required_caps += [...
class Compare(Expr): fields = ('expr', 'ops') def as_const(self, eval_ctx=None): eval_ctx = get_eval_context(self, eval_ctx) result = value = self.expr.as_const(eval_ctx) try: for op in self.ops: new_value = op.expr.as_const(eval_ctx) result = ...
def square_matrix(x): assert_tensor(x) shape = x.get_shape() if ((len(shape) != 2) or (shape[0] != shape[1])): return (False, f'expected a square matrix, got shape {shape}') return (True, None)
class Ex2Job(IndependentJob): def __init__(self, aggregator, p, data_source, prob_label, rep, job_func, prob_param): walltime = (60 * 59) memory = (int(((tr_proportion * sample_size) * 0.01)) + 50) IndependentJob.__init__(self, aggregator, walltime=walltime, memory=memory) self.p = p...
class MockCmdLineArgs(): quiet = True MODEL = 'name' path = dataset_path path_labels = None label = 'folder' port = 0
def save_in_word2vec_format(vecs: np.ndarray, words: np.ndarray, fname: str): with open(fname, 'w', encoding='utf-8') as f: f.write((((str(len(vecs)) + ' ') + '300') + '\n')) for (i, (v, w)) in tqdm.tqdm_notebook(enumerate(zip(vecs, words))): vec_as_str = ' '.join([str(x) for x in v]) ...
class PylayersGUI(HasTraits): laynames = ([''] + np.sort(os.listdir((basename + '/struc/lay/'))).tolist()) Lay_Enum = Enum(laynames) av_ant = ['Omni', 'Gauss', 'aperture'] antext = ['vsh3', 'sh3'] for fname in os.listdir((basename + '/ant')): if (fname.split('.')[(- 1)] in antext): ...
def test_all_gemm(operation: 'GemmOperationUniversal', testcase='universal'): passed = True minimum_operand_element_size = min(DataTypeSize[operation.A.element], DataTypeSize[operation.B.element]) opcode_class = operation.tile_description.math_instruction.opcode_class if (opcode_class == cutlass.OpClass...
def _quadratic_observer(x: tf.Tensor) -> Mapping[(Tag, Dataset)]: return {NA: Dataset(x, quadratic(x))}
def test_array(): array = ak.Array(['this', {'x': ['is', 1, 2, None]}]) assert (ak.type(array) == array.type) assert isinstance(array.type, ak.types.ArrayType)
def define_D_pair(opt): opt_net = opt['network_D_pair'] which_model = opt_net['which_model_D'] if (which_model == 'discriminator_vgg_128'): netD = SRGAN_arch.Discriminator_VGG_128(in_nc=opt_net['in_nc'], nf=opt_net['nf']) elif (which_model == 'patchgan'): netD = NLayerDiscriminator(input...
def shingles(text, char_ngram=5): return set((text[head:(head + char_ngram)] for head in range(0, (len(text) - char_ngram))))
def resnetish10(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNetish: return _resnetish('resnetish18', BasicBlock, [1, 1, 1, 1], pretrained, progress, **kwargs)
def slice_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, start=None, stop=None, step=None): dy = grad_inputs[0] x0_shape = input_shapes[0] ctx = nn.get_current_context() df = SliceDataGrad(ctx, start, stop, step) df.xshape = x0_shape dx0 = df(dy) return dx0
def zero_one_loss_calc(TP, POP): try: length = POP return (length - sum(TP.values())) except Exception: return 'None'
def semseg_png(score, dataset=None, img_info=None, output_folder=None, semseg=None, target=None): semseg_pres_dir = os.path.join(output_folder, 'semseg_pres') if (not os.path.exists(semseg_pres_dir)): os.makedirs(semseg_pres_dir) im_name = img_info['file_name'] extra_fields = dataset.extra_field...
class MPNetForTokenClassification(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def _baseset_picker(args): if (args.baseset == 'CIFAR10'): transform_train = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) clean_trainset = torchvision.datasets.CIFAR10(root='~/data', train=True...
def recursive_redirect_lookup(redirects, word): if (word in redirects): try: return recursive_redirect_lookup(redirects, redirects[word]) except RecursionError: return word else: return word
def compare_collocation(word): corp1_collocates = ct.collocator(ct.tokenize(ct.ldcorpus(corpus1)), word, stat='MI') corp2_collocates = ct.collocator(ct.tokenize(ct.ldcorpus(corpus2)), word, stat='MI') print(f''' Collocates for the word `{word}`: {corpus1}''') ct.head(corp1_collocates, hits=20) print...
class cross_GNN(MessagePassing): def __init__(self, dim, hidden_layer): super(cross_GNN, self).__init__(aggr='mean') def forward(self, x, edge_index, edge_weight=None): x = x.squeeze() return self.propagate(edge_index, x=x, edge_weight=edge_weight) def message(self, x_i, x_j, edge_we...
class OneColorSpaceInvadersWorld(SpaceInvadersWorld): shield_class = WhiteShield invader_class = WhiteLeftRightMovingInvader
_utils.test() def test_non_static_in(): with pytest.raises(ti.TaichiCompilationError, match='"In" is only supported inside `ti.static`.'): def foo(a: ti.template()) -> ti.i32: b = 0 if (a in [ti.i32, ti.u32]): b = 1 return b foo(ti.i32)
def test_var_test_case(test_case_mock): ref = vr.VariableReference(test_case_mock, int) assert (ref.test_case == test_case_mock)
(scope='function') def montecarlo_main_loop_config(config_montecarlo_1e5_verysimple): montecarlo_configuration.LEGACY_MODE_ENABLED = True config_montecarlo_1e5_verysimple.montecarlo.last_no_of_packets = 100000.0 config_montecarlo_1e5_verysimple.montecarlo.no_of_virtual_packets = 0 config_montecarlo_1e5_...
def simPushInt32OntoStack(stackHandle, value): ret = lib.simPushInt32OntoStack(stackHandle, value) _check_return(ret)
def hash_sequence(seq, ksize): global hashing_fn, hashing_ksize if ((hashing_fn is None) or (hashing_ksize != ksize)): kh = khmer.Nodetable(ksize, 1, 1) (hashing_fn, hashing_ksize) = (kh.get_kmer_hashes, ksize) return hashing_fn(seq)
def test_context_manager_decorator(): class Ctx(): def __init__(self) -> None: self.did_start = False self.should_pass = False def mgr(self, name: str): self.start(name) (yield) self.stop() def start(self, name: str): if...
def train(args, train_dataset, model, tokenizer): if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSampler(train_dat...
.parametrize('sql', ['select 1 -- foo', 'select 1 # foo']) def test_single_line_comments(sql): p = sqlparse.parse(sql)[0] assert (len(p.tokens) == 5) assert (p.tokens[(- 1)].ttype == T.Comment.Single)
def construct_model(): if args.nf: chain = [] for i in range(args.depth): chain.append(layers.PlanarFlow(2)) return layers.SequentialFlow(chain) else: chain = [] for i in range(args.depth): if args.glow: chain.append(layers.BruteFor...
class ZenodoDownloadError(ZenodoException): def __init__(self): super().__init__('An error occurred while downloading the dataset from Zenodo.')
def append_beams(obj, beams): for b in beams[0]: if ('-' in b): (former, latter) = b.split('-') obj.beams.append(former, latter) else: obj.beams.append(b)