code
stringlengths
101
5.91M
def per_class_iu(hist): return (np.diag(hist) / ((hist.sum(axis=1) + hist.sum(axis=0)) - np.diag(hist)))
def stirling_series(N): with mpmath.workdps(100): coeffs = [(mpmath.bernoulli((2 * n)) / ((2 * n) * ((2 * n) - 1))) for n in range(1, (N + 1))] return coeffs
def test_unequal_union(): union_1 = ak.from_iter([1, None, {'x': 2}, 3], highlevel=False) union_2 = ak.from_iter([1, None, {'x': 2}, 2], highlevel=False) assert (not union_1.is_equal_to(union_2))
class AutoModel(object): def __init__(self): raise EnvironmentError('AutoModel is designed to be instantiated using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` or `AutoModel.from_config(config)` methods.') def from_config(cls, config): if isinstance(config, DistilBertConfig): ...
class TinyImageNetDataset(ShardDataset): NUM_IMAGES_PER_CLASS = 500 def __init__(self, data_folder: Path, data_type='train', rank=1, worldsize=1): self.data_type = data_type self._common_data_folder = data_folder self._data_folder = os.path.join(data_folder, data_type) self.label...
class FNetTokenizer(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', 'token_type_ids'] def __init__(self, vocab_file, do_lower_case=Fals...
.parametrize('region_sparse,region_dense,base_sparse,base_dense,bias_sparse,bias_dense', [(0, 2, 0, 2, 0, 1), (0, 2, 0, 1, 0, 2), (0, 2, 0, 0, 1, 0), (0, 1, 1, 2, 1, 1), (0, 1, 1, 1, 1, 2), (0, 1, 1, 0, 2, 0), (1, 0, 2, 2, 2, 1), (2, 0, 2, 1, 2, 2), (2, 0, 2, 0, 0, 0)]) def test_MLRs(region_sparse, region_dense, base_s...
class LeNet(nn.Module): def __init__(self, pretrained=False, num_classes=10, input_size=28, **kwargs): super(LeNet, self).__init__() suffix = f'dim{input_size}_nc{num_classes}' self.model_path = os.path.join(MODELS_DIR, f'lenet_mnist_{suffix}.pt') assert (input_size in [28, 32]), 'Ca...
class MultiAgentEnv(object): def __init__(self, batch_size=None, **kwargs): args = kwargs['env_args'] if isinstance(args, dict): args = convert(args) self.args = args if (getattr(args, 'seed', None) is not None): self.seed = args.seed self.rs = np....
def meijering(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0): image = image.astype(_supported_float_type(image.dtype), copy=False) if (not black_ridges): image = (- image) if (alpha is None): alpha = (1 / (image.ndim + 1)) mtx = linalg.circulant([1,...
def single_pinyin(han, style, heteronym, errors='default', strict=True): return _default_convert._single_pinyin(han, style, heteronym, errors=errors, strict=strict)
def iter_slices(string, slice_length): pos = 0 if ((slice_length is None) or (slice_length <= 0)): slice_length = len(string) while (pos < len(string)): (yield string[pos:(pos + slice_length)]) pos += slice_length
def AtLeast(*args): args = _get_args(args) if z3_debug(): _z3_assert((len(args) > 1), 'Non empty list of arguments expected') ctx = _ctx_from_ast_arg_list(args) if z3_debug(): _z3_assert((ctx is not None), 'At least one of the arguments must be a Z3 expression') args1 = _coerce_expr_...
def test_construct_schema_2positional(): def fun(x: int, y: float): pass model_type = schema.construct_schema('FunSchema', fun, skip_first_arg=False) assert (model_type({'x': 5, 'y': 2}).to_native() == {'x': 5, 'y': 2})
class EvalConfig(): dataset: str = 'kspon' dataset_path: str = '' transcripts_path: str = '../../../data/eval_transcript.txt' model_path: str = '' output_unit: str = 'character' batch_size: int = 32 num_workers: int = 4 print_every: int = 20 decode: str = 'greedy' k: int = 3 ...
class LapCore(CPAlgorithm): def __init__(self, beta=0.1): self.beta = beta def detect(self, G): (A, nodelabel) = utils.to_adjacency_matrix(G) x = self._lap_core(A) Q = self._score(A, None, x) self.nodelabel = nodelabel self.c_ = np.zeros(A.shape[0]).astype(int) ...
def _is_packed(dtype): total_offset = 0 for name in dtype.names: (fld_dtype, fld_offset, title) = _unpack_field(*dtype.fields[name]) if (fld_offset != total_offset): return False total_offset += fld_dtype.itemsize if (total_offset != dtype.itemsize): return False ...
def get_model(point_cloud, is_training, num_class, bn_decay=None, gripper_feat=None, env_feat=None): batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value end_points = {} l0_xyz = point_cloud l0_points = None end_points['l0_xyz'] = l0_xyz (l1_xyz, l1_poin...
class DomainTransitionGraph(): def __init__(self, init, size): self.init = init self.size = size self.arcs = defaultdict(set) def add_arc(self, u, v): self.arcs[u].add(v) def reachable(self): queue = [self.init] reachable = set(queue) while queue: ...
class Saver(): def __init__(self, opts): self.display_dir = os.path.join(opts.display_dir, opts.name) self.model_dir = os.path.join(opts.result_dir, opts.name) self.image_dir = os.path.join(self.model_dir, 'images') self.display_freq = opts.display_freq self.img_save_freq = o...
class TD_LSTM(nn.Module): def __init__(self, embedding_matrix, opt): super(TD_LSTM, self).__init__() self.embed = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float)) self.lstm_l = DynamicLSTM(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True) s...
def get_eval_dataset(dataset_name, num_shots, seed=42): top_k = 1 top_p = 0 temperature = 1 num_shots = num_shots max_new_tokens = 20 shuffle_train = True eval_func = eval_func_default pred_postprocess_func = pred_postprocess_default if (dataset_name == 'trivia_qa'): dataset ...
def load_experts(expert_files, flatten=True): transitions = [] for file in tqdm(expert_files): with open(file, 'rb') as f: new_trajectories = pickle.load(f) transitions += new_trajectories if flatten: transitions = flatten_trajectories(transitions) return transitions
def cover_and_relations_from_invariants(invs): n = len(invs) A = (ZZ ** n) B = A.span([(A.gen(i) * invs[i]) for i in range(n)]) return (A, B)
def check_and_enlist_bcs(bcs_list: Union[(fenics.DirichletBC, List[fenics.DirichletBC], List[List[fenics.DirichletBC]])]) -> List[List[fenics.DirichletBC]]: if isinstance(bcs_list, fenics.DirichletBC): return [[bcs_list]] elif (isinstance(bcs_list, list) and (len(bcs_list) == 0)): return [bcs_li...
def main(): graph = electrical() params = {'runs': 1, 'steps': 100, 'seed': 1, 'l': 0.8, 'r': 0.2, 'c': int((0.1 * len(graph))), 'k_a': 5, 'attack': 'id_node', 'attack_approx': None, 'k_d': 0, 'defense': None, 'robust_measure': 'largest_connected_component', 'plot_transition': False, 'gif_animation': True, 'gif...
class TestChannelStatsOp(serial.SerializedTestCase): def channel_stats_nchw_ref(self, X): dims = X.shape N = dims[0] C = dims[1] X = X.reshape(N, C, (- 1)) sum1 = np.sum(X, axis=(0, 2), keepdims=False) sum2 = np.sum((X ** 2), axis=(0, 2), keepdims=False) retur...
class Network(nn.Module): def __init__(self, init_ch, dataset, config): super(Network, self).__init__() self.config = config self._C_input = init_ch self._head_dim = self.config.optim.head_dim self._dataset = dataset self.initialize() def initialize(self): ...
def test_attri2vec_apply(): attri2vec = Attri2Vec(layer_sizes=[2, 2, 2], bias=False, input_dim=2, node_num=4, multiplicity=2, activation='linear', normalize=None) model = keras.Model(*attri2vec.in_out_tensors()) model.set_weights([np.ones_like(w) for w in model.get_weights()]) x = np.array([[1, 2]]) ...
def find_all_linear_names(peft_model, int4=False, int8=False): cls = torch.nn.Linear if (int4 or int8): import bitsandbytes as bnb if int4: cls = bnb.nn.Linear4bit elif int8: cls = bnb.nn.Linear8bitLt lora_module_names = set() for (name, module) in peft_mo...
class FractionFieldEmbeddingSection(Section): def _call_(self, x, check=True): codom = self.codomain() if (self.domain()._R is codom): num = x.numerator() den = x.denominator() else: num = codom(x.numerator()) den = codom(x.denominator()) ...
.typeof_impl.register(RecordView) def typeof_RecordView(obj, c): return RecordViewType(numba.typeof(obj.arrayview))
def partial_ld_offset(): return (((12 + (4 * (np.dtype('uint64').alignment > 4))) + 8) + (8 * (np.dtype('longdouble').alignment > 8)))
class TFAlbertForMaskedLM(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class EvalConfig(Config): evaluate: bool = True n_eval_episodes: int = 100 eval_random: bool = False name: str = 'eval' vary_map_shapes: bool = False
class AckleyBenchmark(Benchmark): def __init__(self, nb_features: int=2): self.nb_features = nb_features ind_domain = ((- 32.768), 32.768) super().__init__(fn=algorithms.partial(illumination_ackley, nb_features=nb_features), ind_domain=ind_domain, fitness_domain=((0.0, math.inf),), features_...
class TransformerDecoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttention(d...
class ReshapeChannel(Channel): def __init__(self, prev_shape, next_shape): self.prev_shape = prev_shape self.next_shape = next_shape self.repr_init() def sample(self, Z): return Z.reshape(self.next_shape) def math(self): return '$\\delta$' def second_moment(self, ...
class SkewPartitions_all(SkewPartitions): def __init__(self): SkewPartitions.__init__(self, True) def _repr_(self): return 'Skew partitions' def __iter__(self): n = 0 while True: for p in SkewPartitions_n(n): (yield self.element_class(self, p)) ...
def check_install_build_global(options, check_options=None): if (check_options is None): check_options = options def getname(n): return getattr(check_options, n, None) names = ['build_options', 'global_options', 'install_options'] if any(map(getname, names)): control = options.fo...
class TentPreBN(TentFull): def configure_model_optimizer(self, algorithm, alpha): adapted_algorithm = copy.deepcopy(algorithm) adapted_algorithm.classifier = PreBN(adapted_algorithm.classifier, adapted_algorithm.featurizer.n_outputs) adapted_algorithm.network = torch.nn.Sequential(adapted_al...
def compute_eisenstein_params(character, k): if isinstance(character, (int, Integer)): return __find_eisen_chars_gamma1(character, k) elif isinstance(character, GammaH_class): return __find_eisen_chars_gammaH(character.level(), character._generators_for_H(), k) else: return __find_ei...
def target_nll_c(inputs, targets, reduction='none'): conf = torch.softmax(inputs, dim=1) conf_t = (- F.nll_loss(conf, targets, reduction='none')) conf_diff = (conf - conf_t.view((- 1), 1)) conf_diff = conf_diff.scatter(1, targets.view((- 1), 1), (- 1)) diff_max = conf_diff.max(1)[0] if (reductio...
class RE23(): def __init__(self): self.problem_name = 'RE23' self.n_objectives = 2 self.n_variables = 4 self.n_constraints = 0 self.n_original_constraints = 3 self.ubound = np.zeros(self.n_variables) self.lbound = np.zeros(self.n_variables) self.lbound...
class StaticTzInfo(BaseTzInfo): def fromutc(self, dt): if ((dt.tzinfo is not None) and (dt.tzinfo is not self)): raise ValueError('fromutc: dt.tzinfo is not self') return (dt + self._utcoffset).replace(tzinfo=self) def utcoffset(self, dt, is_dst=None): return self._utcoffset ...
class ConvBlock(Layer): def __init__(self, features: int, kernel_size: int, stride: Tuple[(int, int)], cnn_padding: str, pool_size: Tuple[(int, int)], batchnorm: bool, **kwargs): super(ConvBlock, self).__init__(**kwargs) self.conv = Conv2D(features, kernel_size, strides=stride, padding=cnn_padding) ...
class Localization(nn.Module): def __init__(self, cfg): super(Localization, self).__init__() self.cfg = cfg self.batch_size = cfg.BATCH_SIZE_TRAIN self.model_df = DynamicFilter(cfg) self.reduction = nn.Linear(cfg.REDUCTION.INPUT_SIZE, cfg.REDUCTION.OUTPUT_SIZE) self.m...
def default_representative(part, G): D = G.domain() total = 0 cycles = [] for p in part: cycles.append(tuple(D[total:(total + p)])) total += p return G.element_class(cycles, G, check=False)
def bidirectional_merge_overlapping(A, B, key=None): if (key is None): Akeys = A Bkeys = B else: Akeys = tuple((key(a) for a in A)) Bkeys = tuple((key(b) for b in B)) def find_overlapping_index(A, B): if (len(B) > (len(A) - 2)): raise StopIteration ...
def resnet50w5(pretrained=True, **kwargs): model = _resnet50w5(**kwargs) if pretrained: state_dict = torch.hub.load_state_dict_from_url(url=' map_location='cpu') state_dict = {k.replace('module.', ''): v for (k, v) in state_dict.items()} model.load_state_dict(state_dict, strict=False) ...
def _format_data(root_path, data_tag, name, wav_folder): data_path = ((((args.target_dir + data_tag) + '/') + name) + '/') new_transcript_path = (data_path + '/txt/') new_wav_path = (data_path + '/wav/') os.makedirs(new_transcript_path) os.makedirs(new_wav_path) wav_path = (root_path + 'wav/') ...
def contextual_accuracy(expected, observed, data=None, start=None, end=None, weighted=True): def _cm(x, y, z, w, f): return contextual_confusion_matrix(x, y, z, w, f, weighted) return _accuracy(expected, observed, data, start, end, _cm)
class Mlp(nn.Module): def __init__(self, in_features, act_layer=nn.GELU, drop=0.0): super().__init__() self.fc1 = nn.Linear(in_features, in_features) self.act = act_layer() self.drop = nn.Dropout(drop) def forward(self, x): x = self.fc1() x = self.act(x) x...
def find_numba_methods(layouttype, behavior): behavior = overlay_behavior(behavior) rec = layouttype.parameters.get('__record__') if isinstance(rec, str): for (key, typer) in behavior.items(): if (isinstance(key, tuple) and (len(key) == 4) and (key[0] == '__numba_typer__') and (key[1] ==...
_spec_function('landing_page') def get_landing_page_spec(run_human_eval: bool=False) -> RunSpec: scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.image_generation.landing_page_scenario.LandingPageScenario', args={}) adapter_spec = get_image_generation_adapter_spec(num_outputs=4) metric_spec...
def get_binary_stream(name): opener = binary_streams.get(name) if (opener is None): raise TypeError("Unknown standard stream '{}'".format(name)) return opener()
def parse_args(): parser = argparse.ArgumentParser('Conversion script') parser.add_argument('--data_path', required=True, type=str, help='Path to the gqa dataset') parser.add_argument('--img_path', required=True, type=str, help='Path to the gqa image dataset') parser.add_argument('--sg_path', required=T...
def register_Ns3Ipv6InterfaceContainer_methods(root_module, cls): cls.add_constructor([param('ns3::Ipv6InterfaceContainer const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface')]) cls.add_method('Add', 'void', [par...
def merge_all_csvs(args): cache_dir = (args.data.output.path.parent / 'caches') name = args.data.output.path.name paths = list(cache_dir.glob('cache_*_*_{}'.format(name))) groups = group_cache_paths(paths) for key in sorted(list(groups.keys())): print('processing cache set {}'.format(key)) ...
def getBoundingBoxes(directory, isGT, bbFormat, coordType, allBoundingBoxes=None, allClasses=None, imgSize=(0, 0)): if (allBoundingBoxes is None): allBoundingBoxes = BoundingBoxes() if (allClasses is None): allClasses = [] os.chdir(directory) files = glob.glob('*.txt') files.sort() ...
def _dispatch_kl(type_p, type_q): matches = [(super_p, super_q) for (super_p, super_q) in _KL_REGISTRY if (issubclass(type_p, super_p) and issubclass(type_q, super_q))] if (not matches): return NotImplemented (left_p, left_q) = min((_Match(*m) for m in matches)).types (right_q, right_p) = min((_...
def main(): args = get_args() if args.split_sents: from pyrouge.utils.sentence_splitter import PunktSentenceSplitter tmp = mkdtemp() PunktSentenceSplitter.split_files(args.input_dir, tmp) args.input_dir = tmp Rouge155.convert_summaries_to_rouge_format(args.input_dir, args.out...
def test_callable(): A = np.random.rand(20) cls = MyTestClass(12) assert np.allclose(cls(A), (A * 12))
class Report(OrderedDict): def __init__(self, batch: SampleList=None, model_output: Dict[(str, Any)]=None, *args): super().__init__(self) if (batch is None): return if (model_output is None): model_output = {} if self._check_and_load_tuple(batch): ...
def retrieval_yr(cls, year, target): from ecmwfapi import ECMWFDataServer server = ECMWFDataServer() if (cls.levtype == 'sfc'): server.retrieve({'dataset': cls.dataset, 'class': cls.dclass, 'expver': '1', 'grid': '{}/{}'.format(cls.grid, cls.grid), 'date': '{}-01-01/TO/{}-12-31'.format(year, year), ...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, dat...
def serre_cartan_basis(n, p=2, bound=1, **kwds): generic = kwds.get('generic', (p != 2)) if (n == 0): return ((),) elif (not generic): result = [(n,)] for last in range(bound, (1 + (n // 3))): for vec in serre_cartan_basis((n - last), bound=(2 * last)): ne...
def load_belle(): dataset_dict = load_dataset('BelleGroup/train_0.5M_CN') print(dataset_dict) dataset_dict = cast(DatasetDict, dataset_dict) dataset_dict = dataset_dict.rename_columns({'instruction': 'text1', 'output': 'text2'}) dataset_dict = dataset_dict.map(add_label, batched=True, remove_columns...
def _seg_49(): return [(64943, 'M', u''), (64944, 'M', u''), (64945, 'M', u''), (64946, 'M', u''), (64947, 'M', u''), (64948, 'M', u''), (64949, 'M', u''), (64950, 'M', u''), (64951, 'M', u''), (64952, 'M', u''), (64953, 'M', u''), (64954, 'M', u''), (64955, 'M', u''), (64956, 'M', u''), (64957, 'M', u''), (64958, ...
def _create_mac(key, msg, method): if callable(method): return hmac.HMAC(key, msg, method) def hashfunc(d=b''): return hashlib.new(method, d) hashfunc.__call__ = hashfunc return hmac.HMAC(key, msg, hashfunc)
class OPTEngine(CausalEngine): config_name: str = 'opt_engine' def __init__(self, weights_path: Optional[Union[(str, Path)]]=None): super().__init__(model_name='facebook/opt-1.3b', weights_path=weights_path) self.tokenizer.pad_token = self.tokenizer.eos_token self.tokenizer.pad_token_id ...
class Colors(): default_colors = [Color(1, 0, 0), Color(0, 1, 0), Color(0, 0, 1), Color(1, 1, 0), Color(1, 0, 1), Color(0, 1, 1)] def __init__(self): self.__colors = {} def add(self, name, color): self.__colors[name] = color def lookup(self, name): if (not self.__colors.has_key(n...
def get_distance_fn(dist_metric): if (dist_metric == 'mse'): return (lambda a, b: (np.sum(((a - b) ** 2)) / float(a.size))) if (dist_metric == 'ssim'): return (lambda a, b: compare_ssim(a, b, multichannel=True)) if (dist_metric == 'nrmse_euc'): return (lambda a, b: compare_nrmse(a, b...
def get_pretrained_tag(pretrained_model): pretrained_model = pretrained_model.lower() if (('laion' in pretrained_model) or ('open_clip' in pretrained_model)): return 'open_clip' elif ('openai' in pretrained_model): return 'clip' elif (('eva' in pretrained_model) and ('clip' in pretrained...
def cross_entropy(pred, target): logsoftmax = nn.LogSoftmax() return torch.mean(torch.sum(((- target) * logsoftmax(pred)), dim=1))
def transfer_prev_model_weights_to_new_model(prev_model, new_model): params1 = prev_model.named_parameters() params2 = new_model.named_parameters() dict_params2 = dict(params2) for (name1, param1) in params1: if (name1 in dict_params2): dict_params2[name1].data.copy_(param1.data) ...
def worker_init_fn(worker_id: int, num_workers: int, rank: int, seed: int): worker_seed = (((num_workers * rank) + worker_id) + seed) np.random.seed(worker_seed) random.seed(worker_seed)
class FreeModule_ambient_pid(FreeModule_generic_pid, FreeModule_ambient_domain): def __init__(self, base_ring, rank, sparse=False, coordinate_ring=None, category=None): FreeModule_ambient_domain.__init__(self, base_ring=base_ring, rank=rank, sparse=sparse, coordinate_ring=coordinate_ring, category=category)...
def test_ListArray_getitem(): array = ak.highlevel.Array([[0.0, 1.1, 2.2], [], [3.3, 4.4], [5.5], [6.6, 7.7, 8.8, 9.9]]) def f1(x, i): return x[i] assert (ak.operations.to_list(f1(array, 0)) == [0.0, 1.1, 2.2]) assert (ak.operations.to_list(f1(array, 1)) == []) assert (ak.operations.to_list(...
def test_UnmaskedArray_RecordArray_NumpyArray(): v1 = json.loads('{"class":"UnmaskedArray","content":{"class":"RecordArray","contents":{"nest":{"class":"NumpyArray","inner_shape":[],"itemsize":8,"format":"d","primitive":"float64","parameters":{},"form_key":null}},"parameters":{},"form_key":null},"parameters":{},"fo...
def test_smart_array_concatenate_single(): arr = np.random.rand(3, 4, 5) result = _check_smart_concatenate([arr]) assert (result is arr) rng = range(10) result = _check_smart_concatenate([rng], check_strides=False) assert (result is rng)
def _build(model, optimizer, weights_only=False, use_param_info_optim=True, max_gradient_norm=None, allow_lr_injection=False): param_to_device = _get_param_to_device(model) model.Validate() params = [] for param_info in model.GetOptimizationParamInfo(): if (weights_only and (param_info.blob not ...
class Base(Layer, Graphable): __ases: Dict[(int, AutonomousSystem)] __ixes: Dict[(int, InternetExchange)] __name_servers: List[str] def __init__(self): super().__init__() self.__ases = {} self.__ixes = {} self.__name_servers = [] def getName(self) -> str: retu...
def remove_variation_selectors(text): for var in VARIATION_SELECTORS: text = text.replace(var, u'') return text
def create_or_load_model(model, model_dir, session, name, ckpt_index=None): if (model_dir and (ckpt_index is not None)): ckpt_state = tf.train.get_checkpoint_state(model_dir) ckpt_path = ckpt_state.all_model_checkpoint_paths[ckpt_index] else: ckpt_path = tf.train.latest_checkpoint(model_...
def theano_multinomial(n, pvals, seed): rng = RandomStreams(seed) return rng.multinomial(n=n, pvals=pvals, dtype='float32')
class CustomDatasetTests(unittest.TestCase): def setUp(self): super().setUp() self.data_dir = osp.join(osp.dirname(osp.dirname(osp.dirname(__file__))), 'data') self.dataset_class = DATASETS.get('XMLDataset') def test_data_infos__default_db_directories(self): test_dataset_root = o...
class BroadcastedLinear(nn.Module): def __init__(self, P_x, in_features, out_features, dtype=torch.float32): super().__init__() self.P_x = P_x self.P_0 = create_root_partition(P_x) self.in_features = in_features self.out_features = out_features self.dtype = dtype ...
() ('p_e_m_file', type=click.Path(exists=True)) ('dump_db_file', type=click.Path(exists=True)) ('wiki_mention_db_file', type=click.Path(exists=True)) ('out_file', type=click.Path()) ('--max-mention-length', default=20) def build_from_p_e_m_file(p_e_m_file, dump_db_file, wiki_mention_db_file, **kwargs): dump_db = Du...
def register_Ns3DefaultDeleter__Ns3Dot11sIeBeaconTimingUnit_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::DefaultDeleter< ns3::dot11s::IeBeaconTimingUnit > const &', 'arg0')]) cls.add_method('Delete', 'void', [param('ns3::dot11s::IeBeaconTimingUnit *', 'object')], is_st...
def hexstring2npbytearray(hexstring, remove_prefix='0x'): if hexstring.startswith(remove_prefix): lrp = len(remove_prefix) hexstring = hexstring[lrp:] return np.asarray(bytearray.fromhex(hexstring), dtype=np.uint8)
def generate_data(args): if (args.perturbation2 != 'identity'): if (args.perturbation3 != 'identity'): perturbed_dir = ((((Path(args.dst_dir) / args.perturbation) / args.perturbation2) / args.perturbation3) / f'level_{args.level}') else: perturbed_dir = (((Path(args.dst_dir) ...
def update_email_subject(downloaded_email, email_subject): new_subject = f'[ACTIONED] {email_subject}' downloaded_email.replace_header('Subject', new_subject) logger.info('Message subject modified to: %s', new_subject) return downloaded_email
class Scores(object): def __init__(self): self.true_positives = 0 self.false_positives = 0 self.true_negatives = 0 self.false_negatives = 0 def recall(self): numerator = self.true_positives denominator = (self.true_positives + self.false_negatives) return ...
def test_inheritance(): class Empty(interface.LinearOperator): pass with warns(RuntimeWarning, match='should implement at least'): assert_raises(TypeError, Empty) class Identity(interface.LinearOperator): def __init__(self, n): super(Identity, self).__init__(dtype=None, s...
def main(args): args = parse_args(args) if (args.eval and args.format_only): raise ValueError('--eval and --format_only cannot be both specified') if ((args.out is not None) and (not args.out.endswith(('.pkl', '.pickle')))): raise ValueError('The output file must be a pkl file.') cfg = C...
class DalleBartConfig(PretrainedFromWandbMixin, PretrainedConfig): model_type = 'dallebart' keys_to_ignore_at_inference = ['past_key_values'] attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__(self, normalize_text=False, encoder_vocab_size=50264, im...
class _Player(): def __init__(self, num_strategies): self.num_strategies = num_strategies def add_strategy(self): self.num_strategies += 1
def register_model_func(generated_file_name_or_path, _get_normal_model_instance, get_extra=None): d = dict(_get_normal_model_instance=_get_normal_model_instance) if get_extra: d['get_extra'] = get_extra handler_cls = type('AutoGeneratedModelHandler', (CommonModelHandler,), d) handler: CommonMode...
def create_updown_map(logfile): updown_map = {'up': {}, 'down': {}} fcnt_up = None linkadrreq = None with open(logfile, 'r', encoding='utf8') as log: block_id = None block_data = {} for line in log: line = line.strip() if line.startswith('>'): ...