code
stringlengths
101
5.91M
def convert_to_num_gpus(module, num_gpus_to_sim): module_output = module if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): new_cls = MODULE_INSTANCES_TO_REPLACE[module.__class__.__name__] module_output = new_cls(module.num_features, module.eps, module.momentum, module.affine, module....
class PerlmutterHvp(object): def __init__(self, num_slices=1): self.target = None self.reg_coeff = None self.opt_fun = None self._num_slices = num_slices def update_opt(self, f, target, inputs, reg_coeff): self.target = target self.reg_coeff = reg_coeff pa...
def process_treebank(treebank, model_type, paths, args): prepare_tokenizer_treebank.copy_conllu_treebank(treebank, model_type, paths, paths['POS_DATA_DIR'])
def main(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', default='./data/', help='path to datasets') parser.add_argument('--data_name', default='precomp', help='{coco,f30k}_precomp') parser.add_argument('--vocab_path', default='./vocab/', help='Path to saved vocabulary json file...
class GNN(torch.nn.Module): def __init__(self, input_dim, hid_dim=None, out_dim=None, gcn_layer_num=2, pool=None, gnn_type='GAT'): super().__init__() if (gnn_type == 'GCN'): GraphConv = GCNConv elif (gnn_type == 'GAT'): GraphConv = GATConv elif (gnn_type == 'T...
def test_method_statement_args(test_case_mock, variable_reference_mock, method_mock): references = {'a': MagicMock(vr.VariableReference), 'b': MagicMock(vr.VariableReference)} statement = stmt.MethodStatement(test_case_mock, method_mock, variable_reference_mock) statement.args = references assert (state...
class BlenderbotSmallTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, merges_...
class Counter(object): def __init__(self): self._countList = {} self._timeList = {} def count(self, prop): assert isinstance(prop, str), 'The property must be a string.' if (prop not in self._countList): self._countList[prop] = 0 self._countList[prop] += 1 ...
def article_tokenizer_for_prompt_sequences(monkeypatch, packing_boundary: BoundaryType, ext_type: FileExtension, keep_prompt_only_sequences: bool) -> ArticleTokenizer: monkeypatch.setattr(TOKENIZER, 'encode', mock_tokenize) article_tokenizer = ArticleTokenizer(TOKENIZER, MAX_SEQ_LEN, ext_type, packing_boundary=...
def validate_fi_veronumero(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(veronumero.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column ...
_module() class DefaultFormatBundleMmdet(): def __init__(self, img_to_float=True, pad_val=dict(img=0, masks=0, seg=255, pan=0)): self.img_to_float = img_to_float self.pad_val = pad_val def __call__(self, results): if ('img' in results): img = results['img'] if ((s...
def test_mapcollapse_tree(): sdfg: dace.SDFG = tocollapse.to_sdfg() sdfg.simplify() sdfg.validate() assert (sdfg.apply_transformations(MapCollapse) == 1) sdfg.validate()
def benchmark(test_acc, target_acc, test_perf, target_perf): def test(achieved, target, name): passed = True if ((target is not None) and (achieved is not None)): logging.info(f'{name} achieved: {achieved:.2f} target: {target:.2f}') if (achieved >= target): lo...
def create_logger(args): logger = logging.getLogger('MaskTCNNTrainLogger') if dist_utils.is_main_process(): logger.setLevel(args.log_level) else: logger.setLevel(args.subprocess_log_level) ch = logging.StreamHandler() formatter = logging.Formatter('[%(proc_id)d] %(asctime)s - %(level...
(scope='session') def join_items(): left = [{'name': 'left', 'key': 'value', 'deep': [{'name': 1}]}, {'name': 'common', 'key': 'left', 'deep': [{'name': 1}]}] right = [{'name': 'right', 'key': 'value', 'deep': [{'name': 2}]}, {'name': 'common', 'key': 'right', 'deep': [{'name': 2}]}] return (left, right)
def human_format(num): num = float('{:.3g}'.format(num)) magnitude = 0 while (abs(num) >= 1000): magnitude += 1 num /= 1000.0 return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
class PPO(flexs.Explorer): def __init__(self, model: flexs.Model, rounds: int, sequences_batch_size: int, model_queries_per_batch: int, starting_sequence: str, alphabet: str, log_file: Optional[str]=None): super().__init__(model, 'PPO_Agent', rounds, sequences_batch_size, model_queries_per_batch, starting_s...
class DataAndLabelsLastPartitionTrainer(LastPartitionTrainer): def backprop_last_partition(self, x, y, *args, **kw): pass def last_partition_step_and_statistics(self, x, y, *args, **kw): pass
def test_comma_separated_exclude_checks(cli, mocker, swagger_20): excluded_checks = 'not_a_server_error,status_code_conformance' mocker.patch('schemathesis.cli.load_schema', return_value=swagger_20) execute = mocker.patch('schemathesis.runner.from_schema', autospec=True) cli.run(SCHEMA_URI, '--checks=al...
def slot_edit_f1_full(hypothesis, groundtruth, **kwargs): return slot_edit_f1(hypothesis, groundtruth, loop_over_all_slot=True, **kwargs)
.timeout(10) def test_update_envs_env_update(): max_path_length = 16 env = GarageEnv(PointEnv()) policy = FixedPolicy(env.spec, scripted_actions=[env.action_space.sample() for _ in range(max_path_length)]) tasks = SetTaskSampler(PointEnv) n_workers = 8 workers = WorkerFactory(seed=100, max_path_...
def summarize_address_range(first, last): if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if (first.version != last.version): raise TypeError(('%s and %s are not of the same version' % (first, las...
class LoggerMonitor(object): def __init__(self, paths): self.loggers = [] for (title, path) in paths.items(): logger = Logger(path, title=title, resume=True) self.loggers.append(logger) def plot(self, names=None): plt.figure() plt.subplot(121) lege...
class MultiMLP(Module): CombType = Literal[('cat', 'sum', 'max', 'mean', 'att')] supported_combinations = get_args(CombType) def __init__(self, *, num_channels: int, output_dim: int, hidden_dim: int=16, base_layers: int=2, head_layers: int=1, combination: CombType='cat', activation_fn: Callable[([Tensor], T...
def test_goal_1(env_0: Warehouse): assert (env_0.request_queue[0] == env_0.shelfs[0]) (_, rewards, _, _) = env_0.step([Action.FORWARD]) assert (env_0.agents[0].x == 4) assert (env_0.agents[0].y == 28) assert (env_0.request_queue[0] != env_0.shelfs[0]) assert (rewards[0] == pytest.approx(1.0))
def test_incomplete_requirements_config(config_sop, F, bcs, J, y, p, geometry): with pytest.raises(ConfigError) as e_info: config_sop.set('Output', 'save_mesh', 'True') cashocs.ShapeOptimizationProblem(F, bcs, J, y, p, geometry.boundaries, config=config_sop) assert ('Key save_mesh in section Out...
_module() class SegHead(nn.Module): def __init__(self, num_classes, in_channels, mlps=None, norm_args={'norm': 'bn1d'}, act_args={'act': 'relu'}, dropout=0.5, global_feat=None, **kwargs): super().__init__() if kwargs: logging.warning(f'kwargs: {kwargs} are not used in {__class__.__name__...
def test_gen_mesh_from_voxels(output_dir): from sfepy.mesh.mesh_generators import gen_mesh_from_voxels voxels = nm.array([[[0, 0, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]], [[0, 0, 0, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 1, 1]], [[1, 0, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]...
class SoftIntroVAEBootstrap(nn.Module): def __init__(self, config): super(SoftIntroVAEBootstrap, self).__init__() self.zdim = config['z_size'] self.encoder = Encoder(config) self.decoder = Decoder(config) self.target_decoder = Decoder(config) def forward(self, x, determin...
def parse_shape(shape, dim): if isinstance(shape, basestr): try: shape = {'scalar': (1,), 'vector': (dim,)}[shape] except KeyError: raise ValueError('unsupported field shape! (%s)', shape) elif isinstance(shape, six.integer_types): shape = (int(shape),) return...
class Splitter(): def __init__(self, data: pd.DataFrame, splitting_ns: SimpleNamespace, random_seed=42): self.random_seed = random_seed self.data = data self.splitting_ns = splitting_ns self.save_on_disk = False self.save_folder = None def process_splitting(self): ...
class EncodeText(DataPipe): text_name: str = 'transcription' output_text_name: str = 'tokenized_text' tokenizer_name: str = 'tokenizer' def encode_text(self, tokenizer: Tokenizer, text: str) -> torch.LongTensor: return torch.LongTensor(tokenizer.encode(text)) def forward(self, dataset: Augme...
def load_params_from_file(model, filename, to_cpu=False): if (not os.path.isfile(filename)): raise FileNotFoundError print(('==> Loading parameters from checkpoint %s to %s' % (filename, ('CPU' if to_cpu else 'GPU')))) loc_type = (torch.device('cpu') if to_cpu else None) checkpoint = torch.load(...
def test(): encoder = BERTEncoder('bert-base-cased') sentences = ['test sentence #1', 'test sentence #2'] encoder.embed_sentences(sentences)
class ExternSprintDatasetSource(): def __init__(self, c2p_fd, p2c_fd, input_dim, output_dim, num_segments): self.pipe_c2p = os.fdopen(c2p_fd, 'wb') self.pipe_p2c = os.fdopen(p2c_fd, 'rb') self._send('init', (input_dim, output_dim, num_segments)) def _send(self, data_type, args=None): ...
class SoftmaxAverage(OptimizationFunction): def __init__(self, objectives: List[OptimizationFunction]): super().__init__(objectives) self.objectives = objectives def eval(self, input_vals: List[np.ndarray]) -> np.ndarray: max_val = np.max(input_vals) weights = np.exp((input_vals ...
class NaiveModel(nn.Module): def __init__(self, input_sequence_length=1, forecasting_step=1): super(NaiveModel, self).__init__() self.input_sequence_length = input_sequence_length self.forecasting_step = forecasting_step def forward(x): return x[(- forecasting_step):]
def _demo_head_inputs(input_shape=(1, 480, 56, 56)): (N, C, H, W) = input_shape rng = np.random.RandomState(0) features = rng.rand(*input_shape) return features
def merge_vocab(pair, v_in): v_out = {} bigram_pattern = re.escape(' '.join(pair)) p = re.compile((('(?<!\\S)' + bigram_pattern) + '(?!\\S)')) for word in v_in: w_out = p.sub(''.join(pair), word) v_out[w_out] = v_in[word] return v_out
def get_parser(desc, default_task='translation'): usr_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) usr_parser.add_argument('--user-dir', default=None) (usr_args, _) = usr_parser.parse_known_args() utils.import_user_module(usr_args) parser = argparse.ArgumentParser(allow_abbre...
class AI21TextGenerationAPI(TextGenerationAPI): config_name = 'ai21' def __init__(self, engine, api_key): super().__init__(engine, api_key=api_key, request_batch_size=1) ai21.api_key = api_key def generate_text(self, prompts, max_tokens, temperature, top_p, stop_sequences, retries=3, **kwarg...
def upload_objects(bucket_name: str='iq-airport-use-case', root_path: str='/scratch/SATE00_MFSR00/DATA_SOURCES/', root_pth_bucket: str='DATA_SOURCES/', upload_num_threads: int=10) -> None: s3_resource = boto3.resource('s3', region_name='eu-west-1') try: my_bucket = s3_resource.Bucket(bucket_name) ...
def charemb(w): chars = ((['#BEGIN#'] + list(w)) + ['#END#']) match = {} for i in [2, 3, 4]: grams = ngrams(chars, i) for g in grams: g = '{}gram-{}'.format(i, ''.join(g)) e = None if (g in kazuma['stoi']): e = kazuma['vectors'][kazuma['sto...
def load_audio_pydub(path, shape=None, normalize=False): if shape: return auresize(auread(path), shape) return auread(path)
def trainModel(model, trainData, validData, dataset, optim): print(model) sys.stdout.flush() model.train() crit1 = NLLLoss(dataset['dicts']['tgt'].size()) crit2 = BCELoss() start_time = time.time() def trainEpoch(epoch): if (opt.extra_shuffle and (epoch > opt.curriculum)): ...
(3, 4, FOptsDir.DOWNLINK, fOptsDownlink) class LinkADRReq(FOpt): _MASK_DATARATE = 240 _MASK_TXPOWER = 15 _MASK_NBTRANS = 15 _MASK_CHMASKCNTL = 112 def __init__(self, dataRate=None, txPower=None, chMask=set(), chMaskCntl=None, nbTrans=1, **kwargs): super().__init__(**kwargs) if (dataR...
class ProjectionHead(nn.Module): def __init__(self, in_dim, hidden_dim, out_dim, dropout): super(ProjectionHead, self).__init__() self.l1 = nn.Linear(in_dim, hidden_dim, bias=False) self.l2 = nn.Linear(hidden_dim, out_dim, bias=False) self.dropout = dropout def forward(self, x): ...
class CompoundType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, refid=None, name=None, member=None): self.kind = kind self.refid = refid self.name = name if (member is None): self.member = [] else: self.memb...
def register_Ns3EpcS1apSapErabSetupItem_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::EpcS1apSap::ErabSetupItem const &', 'arg0')]) cls.add_instance_attribute('enbTeid', 'uint32_t', is_const=False) cls.add_instance_attribute('enbTransportLayerAddress', 'ns3::Ipv4Add...
def test_extract_boundary(): result = {} with pytest.raises(AssertionError): mask_utils.extract_boundary(result) result = {'boundary_result': [0, 1]} with pytest.raises(AssertionError): mask_utils.extract_boundary(result) result = {'boundary_result': [[0, 0, 1, 0, 1, 1, 0, 1, 1]]} ...
def _get_walk_files_to_hash(dir: str, filter: Optional[str]=None): files_to_hash = [] for (foldername, _, filenames) in os.walk(dir): if ((filter is not None) and (filter in foldername.split('/'))): continue relative_foldername = os.path.relpath(foldername, dir) if (relative_...
class FastViterbiOp(NativeOpGenBase): in_info = ({'name': 'am_scores', 'ndim': 3, 'shape': (None, None, None), 'need_contiguous': True, 'gradient': 'disconnected'}, {'name': 'am_seq_len', 'ndim': 1, 'shape': ((0, 0),), 'dtype': 'int32', 'need_contiguous': True, 'gradient': 'disconnected'}, {'name': 'edges', 'ndim':...
def get_solution_dicts(output_file_contents, input_ring, get_failures=True): output_list = output_file_contents.splitlines() solution_dicts = [] for solution_line in range((len(output_list) - 1), (- 1), (- 1)): if (output_list[solution_line].find('THE SOLUTIONS') == 0): break try: ...
def losses(real_images): z = tf.truncated_normal([FLAGS.batch_size, FLAGS.z_size], stddev=1) d_template = discriminator_template() g_template = generator_template() (gen_images, z_prediction) = pt.construct_all(g_template, input=z) tf.image_summary('generated_images', gen_images, max_images=FLAGS.ba...
_testing def test_random_simplicial_complex(level=1, trials=1, verbose=False): deprecation(33777, 'the CHomP interface is deprecated; hence so is this function') for i in range(trials): X = random_simplicial_complex(level=level) chomp = X.homology(verbose=verbose) no_chomp = X.homology(a...
def get_module_constant(module, symbol, default=(- 1), paths=None): try: (f, path, (suffix, mode, kind)) = find_module(module, paths) except ImportError: return None try: if (kind == PY_COMPILED): f.read(8) code = marshal.load(f) elif (kind == PY_FROZE...
class Base3DFusionModel(BaseModule, metaclass=ABCMeta): def __init__(self, init_cfg=None): super().__init__(init_cfg) self.fp16_enabled = False def _parse_losses(self, losses): log_vars = OrderedDict() for (loss_name, loss_value) in losses.items(): if isinstance(loss_...
def register_Ns3Ipv6PrefixValue_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual...
def try_get_nn_module_compiled_mod_and_inputs(*args, **kwargs): name = get_nn_module_name_from_kwargs(**kwargs) if (('desc' in kwargs) and ('eval' in kwargs['desc'])): return test_name = name if ('desc' in kwargs): test_name = '{}_{}'.format(test_name, kwargs['desc']) test_name = get...
def get_embedder(multires, input_dims=3): embed_kwargs = {'include_input': True, 'input_dims': input_dims, 'max_freq_log2': (multires - 1), 'num_freqs': multires, 'log_sampling': True, 'periodic_fns': [torch.sin, torch.cos]} embedder_obj = Embedder(**embed_kwargs) embed = (lambda x, eo=embedder_obj: eo.embe...
def basic_bn_shortcut(model, prefix, blob_in, dim_in, dim_out, stride): if (dim_in == dim_out): return blob_in c = model.Conv(blob_in, (prefix + '_branch1'), dim_in, dim_out, kernel=1, stride=stride, no_bias=1) return model.AffineChannel(c, (prefix + '_branch1_bn'), dim=dim_out)
def set_cycles_renderer(scene: bpy.types.Scene, camera_object: bpy.types.Object, num_samples: int, use_denoising: bool=True, use_motion_blur: bool=False, use_transparent_bg: bool=False) -> None: scene.camera = camera_object scene.render.image_settings.file_format = 'PNG' scene.render.engine = 'CYCLES' s...
def setup_dataset(args, dataset_clazz, data_config, main_gpu, is_training_data): if (not isinstance(data_config, dict)): data_config = literal_eval(data_config) if (('batch_size' not in data_config) or (data_config['batch_size'] is None)): data_config['batch_size'] = args['batch_size'] if ((...
class BasicRFB(nn.Module): def __init__(self, in_planes, out_planes, stride=1, scale=0.1, map_reduce=8, vision=1, groups=1): super(BasicRFB, self).__init__() self.scale = scale self.out_channels = out_planes inter_planes = (in_planes // map_reduce) self.branch0 = nn.Sequentia...
def _lemmas_to_words(tokens): lemma_to_word = {} for (word, unit) in tokens.items(): lemma = unit.token if (lemma in lemma_to_word): lemma_to_word[lemma].append(word) else: lemma_to_word[lemma] = [word] return lemma_to_word
class MultiPage(): def __init__(self): self.pages = [] def add_page(self, title, function): self.pages.append({'title': title, 'function': function}) def run(self, database): page = st.sidebar.selectbox('App Navigation', self.pages, format_func=(lambda page: page['title'])) p...
class CnnC3_3(Convolution2DArchitectureBase, NeuralNetworkTrainingDefault): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.use_gpu = False def build_model(self, x_shape, y_shape): self.assert_shapes(x_shape, y_shape) assert (x_shape[1:] == (101, 6, 1)...
class NezhaForMultipleChoice(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class Trainer(DefaultTrainer): def build_evaluator(cls, cfg, dataset_name, output_folder=None): if (output_folder is None): output_folder = os.path.join(cfg.OUTPUT_DIR, 'inference') evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type if (...
def vgg11(pretrained=False, **kwargs): if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['A']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) return model
class Chunking(TaggingTask): def __init__(self, config, tokenizer): super(Chunking, self).__init__(config, 'chunk', tokenizer, False)
def inspecs_params(): inspecs = [] inspecs.append([Inspec((64, 64, 224, 224))]) inspecs.append([Inspec((64, 128, 112, 112))]) inspecs.append([Inspec((64, 512, 14, 14))]) return inspecs
class TestBasisUtilFunctions(unittest.TestCase): def test_basis_size(self): for n in range(1, (MAX_PHOTONS + 1)): for m in range(1, (MAX_MODES + 1)): n1 = len(b.fock.basis(n, m)) n2 = b.fock.basis_size(n, m) self.assertEqual(n1, n2) def test_lo...
def test_mmi(data_with_redundancy): random.seed(SEED) from ndd.nsb import interaction_information h0 = ndd.from_data(data_with_redundancy[0], ks=[3]) h1 = ndd.from_data(data_with_redundancy[1], ks=[3]) h2 = ndd.from_data(data_with_redundancy[2], ks=[3]) h01 = ndd.from_data(data_with_redundancy[[...
def mean_absolute_scaled_error(y_true, y_pred): (y_true, y_pred) = (np.array(y_true).flatten(), np.array(y_pred).flatten()) n = y_true.shape[0] d = (np.abs(np.diff(y_true, axis=(- 1))).sum() / (n - 1)) errors = np.abs((y_true - y_pred)) return (errors.mean() / d)
class ModelBuilder(): def weights_init(self, m): classname = m.__class__.__name__ if (classname.find('Conv') != (- 1)): nn.init.kaiming_normal_(m.weight.data) elif (classname.find('BatchNorm') != (- 1)): m.weight.data.fill_(1.0) m.bias.data.fill_(0.0001) ...
def cinc_elbow2(coors, mode): if (mode == 0): centre = nm.array([0.0, (- 1e-05), 0.0], nm.float64) else: centre = nm.array([0.2, (- 1e-05), 0.0], nm.float64) axis = nm.array([0, 1, 0], nm.float64) radius = 0.029 length = 2e-05 return get_coors_in_tube(coors, centre, axis, (- 1.0)...
def bilerp_impl(vf: ti.template(), p): (u, v) = p (s, t) = ((u - 0.5), (v - 0.5)) (iu, iv) = (ti.floor(s), ti.floor(t)) (fu, fv) = ((s - iu), (t - iv)) a = sample(vf, iu, iv) b = sample(vf, (iu + 1), iv) c = sample(vf, iu, (iv + 1)) d = sample(vf, (iu + 1), (iv + 1)) return lerp(lerp...
def evaluate(args, model, tokenizer, prefix=''): eval_output_dir = args.output_dir eval_dataset = load_and_cache_examples(args, tokenizer, evaluate=True) if ((not os.path.exists(eval_output_dir)) and (args.local_rank in [(- 1), 0])): os.makedirs(eval_output_dir) args.eval_batch_size = (args.per_...
class VarGRU(VarRNNBase): def __init__(self, *args, **kwargs): super(VarGRU, self).__init__(*args, mode='GRU', Cell=nn.GRUCell, **kwargs) def forward(self, x, hx=None): return super(VarGRU, self).forward(x, hx)
def convert_to_float(image, preserve_range): if (image.dtype == np.float16): return image.astype(np.float32) if preserve_range: if (image.dtype.char not in 'df'): image = image.astype(float) else: from ..util.dtype import img_as_float image = img_as_float(image) ...
def main(args, init_distributed=False): utils.import_user_module(args) try: from fairseq.fb_pathmgr import fb_pathmgr global fb_pathmgr_registerd if (not fb_pathmgr_registerd): fb_pathmgr.register() fb_pathmgr_registerd = True except (ModuleNotFoundError, Impo...
def makevocabs(line, ratio): toks = line.split() ret_sets = [] for i in range(ratio): sub_toks = toks[i::ratio] ret_sets.append(set(sub_toks)) return ret_sets
def wer_details_for_batch(ids, refs, hyps, compute_alignments=False): refs = _batch_to_dict_format(ids, refs) hyps = _batch_to_dict_format(ids, hyps) return wer_details_by_utterance(refs, hyps, compute_alignments=compute_alignments, scoring_mode='strict')
def parse_version(string_version): match = SEMVER_REGEX.match(string_version) if (match is None): msg = ('Invalid version: %s. Accepted versions must match the following regex pattern: %s' % (string_version, SEMVER_PATTERN)) raise ValueError(msg) return match.groupdict()
def display_failures_for_single_test(context: ExecutionContext, result: SerializedTestResult) -> None: from ...transports.responses import get_reason display_subsection(result) if result.is_flaky: click.secho(FLAKY_FAILURE_MESSAGE, fg='red') click.echo() for (idx, (code_sample, group)) i...
class DeviceRootKeys_V1_1(DeviceRootKeys): def __init__(self, joinEUI=None, nwkKey=None, **kwargs): super().__init__(**kwargs) self.joinEUI = joinEUI self.nwkKey = nwkKey
class MemoryMeasurements(Measurements): def __init__(self, pids, output_dir): super().__init__(pids, output_dir) smaps_files = ' '.join([' /proc/{pid}/smaps '.format(pid=pid) for pid in self._pids]) self._copy_cmd = 'cat {smaps} > {output_dir}/smaps_{{id}}'.format(smaps=smaps_files, output_d...
class TestHipify(TestCase): def test_import_hipify(self): from torch.utils.hipify import hipify_python
def trapezoid_integration_caller(data, h, actual): x = cuda.grid(1) actual[x] = formal_integral_cuda.trapezoid_integration_cuda(data, h)
def register_types(module): root_module = module.get_root() module.add_class('Address', import_from_module='ns.network') module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') module.add_class('AttributeConstructionList', import_from_module='...
def getAllObjs(v): rights = list(v.rights) objs = [tok for tok in rights if (tok.dep_ in OBJECTS)] objs.extend(getObjsFromPrepositions(rights)) (potentialNewVerb, potentialNewObjs) = getObjFromXComp(rights) if ((potentialNewVerb is not None) and (potentialNewObjs is not None) and (len(potentialNewOb...
def all_newer(src_files, dst_files): from distutils.dep_util import newer return all(((os.path.exists(dst) and newer(dst, src)) for dst in dst_files for src in src_files))
def get_precision(input_number): try: number_str = str(input_number) (_, decimalpart) = number_str.split('.') return len(decimalpart) except Exception: return 0
def _int_or_half_int(k): if (k in ZZ): return (True, ZZ(k)) try: k = QQ(k) if (k.denominator() == 2): return (False, k.floor()) except (ValueError, TypeError): pass raise ValueError('k must be an integer or an integer + 1/2')
def preProcess(data_path, use_preprocess, publish_time, filter_len): if use_preprocess: print('Loading preprocessed middle file...') sess_clicks = pickle.load(open('../data/mind/sess_clicks.mid.1', 'rb')) sess_date_sorted = pickle.load(open('../data/mind/sess_date_sorted.mid.1', 'rb')) ...
def main(): parser = argparse.ArgumentParser(description='OGBN-papers100M (MLP)') parser.add_argument('--device', type=int, default=0) parser.add_argument('--log_steps', type=int, default=1) parser.add_argument('--use_node_embedding', action='store_true') parser.add_argument('--use_sgc_embedding', a...
def tadgan_hyperparameters(): return {'mlstars.custom.timeseries_preprocessing.time_segments_aggregate#1': {'interval': 1, 'time_column': 'timestamp'}, 'mlstars.custom.timeseries_preprocessing.rolling_window_sequences#1': {'target_column': 0, 'window_size': 100, 'target_size': 1}, 'orion.primitives.tadgan.TadGAN#1'...
def test_arrow_struct_null(): a = pyarrow.array([{'x': 1, 'y': 1.1}, {'x': 2, 'y': None}, {'x': 3, 'y': 3.3}]) assert (to_list(ak._connect.pyarrow.handle_arrow(a)) == [{'x': 1, 'y': 1.1}, {'x': 2, 'y': None}, {'x': 3, 'y': 3.3}])
def register_Ns3UlCqiInfo_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::UlCqiInfo const &', 'arg0')]) cls.add_instance_attribute('m_sinr', 'std::vector< double >', is_const=False) cls.add_instance_attribute('m_type', 'ns3::UlCqiInfo::UlCqiType', is_const=False) ...