code
stringlengths
101
5.91M
def main(): DATASETS = ['Augmented MSRA10K Experiment VIII'] DATASETS_NAME = ['Augmented MSRA10K Experiment VIII'] j = 0 for dataset in DATASETS: FOLDER_MASK = '/home/dvruiz/scriptPosProcessObjects/29_05_2019_FullMix/multipleBG/masks/' fileList = os.listdir(FOLDER_MASK) xs = np.e...
def get_head_wh(x_coords, y_coords): (final_w, final_h) = ((- 1), (- 1)) component_count = 0 save_componets = [] for component in PARTS_SEL: if ((x_coords[component] == MISSING_VALUE) or (y_coords[component] == MISSING_VALUE)): continue else: component_count += 1 ...
def Optimizer_w_Initializer(class_loss, LR, epoch, init_epoch, global_step): with tf.variable_scope('Optimizer_w_Distillation'): variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) teacher_variables = tf.get_collection('Teac...
class RuntimeVariable(str, enum.Enum): TargetModule = 'TargetModule' ConfigurationId = 'ConfigurationId' RunId = 'RunId' ProjectName = 'ProjectName' TotalTime = 'TotalTime' SearchTime = 'SearchTime' AlgorithmIterations = 'AlgorithmIterations' ExecutionResults = 'ExecutionResults' Ran...
class miniImagenetOneshotDataset(data.Dataset): def __init__(self, dataroot=(('/home/' + userName) + '/data/miniImagenet'), type='train', ways=5, shots=1, test_num=1, epoch=100, galleryNum=10): self.ways = ways self.shots = shots self.test_num = test_num self.__size = epoch s...
.parametrize('dtype', [ti.u8, ti.f32]) _utils.test(arch=get_host_arch_list()) def test_save_image_without_window(dtype): n = 255 pixels = ti.field(dtype=dtype, shape=(n, n, 3)) def paint(c: dtype): for (i, j, k) in pixels: pixels[(i, j, k)] = c gui = ti.GUI('Test', res=(n, n), show_g...
def get_scare_snippets(nlp, csv_dir_path, text_id_map, filename_pattern='*.csv'): num_short_items = 0 snippets = [] csv_files = glob.glob(os.path.join(csv_dir_path, filename_pattern)) for csv_filename in csv_files: with open(csv_filename, newline='') as fin: cin = csv.reader(fin, del...
class SNLinear(Linear): def __init__(self, in_size, out_size, use_gamma=False, nobias=False, initialW=None, initial_bias=None, Ip=1, factor=None): self.Ip = Ip self.use_gamma = use_gamma self.factor = factor super(SNLinear, self).__init__(in_size, out_size, nobias, initialW, initial_...
class TestGaussianMLPRegressor(TfGraphTestCase): def test_fit_normalized(self): gmr = GaussianMLPRegressor(input_shape=(1,), output_dim=1) data = np.linspace((- np.pi), np.pi, 1000) obs = [{'observations': [[x]], 'returns': [np.sin(x)]} for x in data] observations = np.concatenate([p...
def eval(model, device, loader, evaluator): model.eval() loss_accum = 0 y_true_list = [] y_pred_list = [] for (step, batch) in enumerate(tqdm(loader, desc='Iteration')): (x_mini, y_true_mini) = batch with torch.no_grad(): y_pred_mini = model(x_mini.to(device)).cpu() ...
def create_aspect_ratio_groups(dataset, k=0): bins = ((2 ** np.linspace((- 1), 1, ((2 * k) + 1))).tolist() if (k > 0) else [1.0]) groups = _quantize(dataset._aspect_ratios, bins) counts = np.unique(groups, return_counts=True)[1] fbins = (([0] + bins) + [np.inf]) print(f'Using {fbins} as bins for asp...
class IntelItaniumCCompiler(IntelCCompiler): compiler_type = 'intele' for cc_exe in map(find_executable, ['icc', 'ecc']): if cc_exe: break
class FairseqEncoder(nn.Module): def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, src_tokens, src_lengths=None, **kwargs): raise NotImplementedError def forward_torchscript(self, net_input: Dict[(str, Tensor)]): if torch.jit.is...
def main(): args = parse_args() if (args.experiment_name is not None): wandb.init(project=args.experiment_name, config=args) if (args.output_dir is not None): if os.path.exists(args.output_dir): if args.overwrite_output_dir: shutil.rmtree(args.output_dir) ...
def get_dataset(): if (FLAGS.dataset == 'imagenet1k'): return get_imagenet() elif ('cifar' in FLAGS.dataset): return get_cifar() else: raise NotImplementedError('dataset not implemented.')
def add_label(img, label, bbox, draw_bg=True, text_bg_color=(255, 255, 255), text_color=(0, 0, 0), top=True): text_width = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)[0][0] if top: label_bg = [bbox[0], bbox[1], (bbox[0] + text_width), (bbox[1] - 30)] if draw_bg: cv2.rectan...
class MaxPool3d(nn.MaxPool3d): def forward(self, x: torch.Tensor) -> torch.Tensor: if ((x.numel() == 0) and obsolete_torch_version(TORCH_VERSION, (1, 9))): out_shape = list(x.shape[:2]) for (i, k, p, s, d) in zip(x.shape[(- 3):], _triple(self.kernel_size), _triple(self.padding), _tri...
class StaticErrorRateChannel(Channel): def __init__(self, space, number_errors): if isinstance(number_errors, (Integer, int)): number_errors = (number_errors, number_errors) if (not isinstance(number_errors, (tuple, list))): raise ValueError('number_errors must be a tuple, a ...
def test_two_columns(): array = ak.Array([[{'x': 1, 'y': [1.1]}, {'x': 2, 'y': [2.2, 0.2]}], [], [{'x': 3, 'y': [3.0, 0.3, 3.3]}]]) ak_array_1 = array['x'] ak_array_2 = array['y'] data_frame = ak.to_rdataframe({'x': ak_array_1, 'y': ak_array_2}, flatlist_as_rvec=True) assert (set(data_frame.GetColum...
def train(config: ConfigParser): logger = config.get_logger('train') config['data_loader']['args']['training'] = True data_loader = config.init_obj('data_loader', module_data) valid_data_loader = data_loader.split_validation() config = update_lr_scheduler(config, len(data_loader)) model = config...
def path_map(src_path, obj_path): def inner_map(full_path): return full_path.replace(src_path, obj_path)
def plane_grid_2d(xbound, ybound): (xmin, xmax) = (xbound[0], xbound[1]) num_x = int(((xbound[1] - xbound[0]) / xbound[2])) (ymin, ymax) = (ybound[0], ybound[1]) num_y = int(((ybound[1] - ybound[0]) / ybound[2])) y = torch.linspace(xmin, xmax, num_x).cuda() x = torch.linspace(ymin, ymax, num_y)....
def embed(documents: dict, ctx_encoder: DPRContextEncoder, ctx_tokenizer: DPRContextEncoderTokenizerFast) -> dict: input_ids = ctx_tokenizer(documents['title'], documents['text'], truncation=True, padding='longest', return_tensors='pt')['input_ids'] embeddings = ctx_encoder(input_ids.to(device=device), return_d...
def evaluate(sess, model, minibatch_iter, size=None): t_test = time.time() (feed_dict_val, labels) = minibatch_iter.node_val_feed_dict(size) node_outs_val = sess.run([model.preds, model.loss], feed_dict=feed_dict_val) (mic, mac) = calc_f1(labels, node_outs_val[0]) return (node_outs_val[1], mic, mac,...
def dropout_flop_jit(inputs, outputs): input_shapes = [get_shape(v) for v in inputs[:1]] flop = prod(input_shapes[0]) flop_counter = Counter({'dropout': flop}) return flop_counter
class Project(): def __init__(self, base_path): self.base_path = base_path def get_sources_paths(self): source_paths = {} for (root, dirs, files) in os.walk(self.base_path): for file in files: if file.endswith('.java'): source_root = self._...
def _save_tags(tag_list, output_labels): with open(output_labels, 'w') as f: f.write('\n'.join(tag_list))
def add_numeric_values_to_question(question): original_text = question question = normalize_for_match(question) numeric_spans = parse_text(question) return Question(original_text=original_text, text=question, numeric_spans=numeric_spans)
def main(): parser = argparse.ArgumentParser(description='Download the MNIST dataset from the internet') parser.add_argument('-d', '--destination', default='.', help='Destination directory') parser.add_argument('-q', '--quiet', action='store_true', help="Don't report about progress") options = parser.pa...
class softmax(nn.Module): def __init__(self, input_size: int, output_size: int): super().__init__() self._indim = input_size self._outdim = output_size self.fc = nn.Linear(input_size, output_size) self.criertion = nn.CrossEntropyLoss() def input_size(self): return...
def evaluate_policy(policy, env_name, seed, eval_episodes=10, render=False): eval_env = gym.make(env_name) eval_env.seed((seed + 100)) avg_reward = 0.0 for _ in range(eval_episodes): (state, done) = (eval_env.reset(), False) while (not done): action = policy.select_action(np....
def count_params(model, verbose=False): total_params = sum((p.numel() for p in model.parameters())) if verbose: print(f'{model.__class__.__name__} has {(total_params * 1e-06):.2f} M params.') return total_params
def test_minimum_rule(): expected = 2 result = minimum_rule(example_kuncheva_batch) assert np.allclose(expected, result)
class TestGPT2WindowService(): def setup_method(self): self.path: str = tempfile.mkdtemp() service: TokenizerService = get_tokenizer_service(self.path) self.window_service = WindowServiceFactory.get_window_service('huggingface/gpt2', service) def teardown_method(self, method): sh...
class SimpleTokenizer(object): def __init__(self, bpe_path: str=default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') merges = merges[1:(((49152 - 256) ...
class MvpConfig(PretrainedConfig): model_type = 'mvp' keys_to_ignore_at_inference = ['past_key_values'] attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__(self, vocab_size=50267, max_position_embeddings=1024, encoder_layers=12, encoder_ffn_dim=4096,...
def estimate_kikuchi_marginal(domain, total, marginals): marginals = dict(marginals) regions = set(marginals.keys()) size = 0 while (len(regions) > size): size = len(regions) for (r1, r2) in itertools.combinations(regions, 2): z = tuple(sorted((set(r1) & set(r2)))) ...
def wsf_exponential(table: Table, attrs: List[str], centers: List[Any], params: Dict[(str, Any)]) -> Query: query = new_query(table, ncols=len(attrs)) for (a, c) in zip(attrs, centers): if (pd.isnull(c) or is_categorical(table.columns[a].dtype)): query.predicates[a] = ('=', c) co...
class NoisyObservationEnv(ProxyEnv, Serializable): ('obs_noise', type=float, help='Noise added to the observations (note: this makes the problem non-Markovian!)') def __init__(self, env, obs_noise=0.1): super(NoisyObservationEnv, self).__init__(env) Serializable.quick_init(self, locals()) ...
class EventList(list): def __init__(self, *args, **kwargs): super(EventList, self).__init__(*args, **kwargs) def __str__(self): return self.table() def table(self, sort_by=None): return build_table(self, sort_by) def export_chrome_trace(self, path): import json wi...
def require_sudachi(test_case): return unittest.skipUnless(is_sudachi_available(), 'test requires sudachi')(test_case)
class Locked(HTTPException): code = 423 description = 'The resource that is being accessed is locked.'
def weights_init_mlp(m, gain=1.0): classname = m.__class__.__name__ if (classname.find('Linear') != (- 1)): init_normc_(m.weight.data, gain) if (m.bias is not None): m.bias.data.fill_(0)
def load_tsv_to_dicts(path: Union[(str, Path)]) -> List[dict]: with open(path, 'r') as f: reader = csv.DictReader(f, delimiter='\t', quotechar=None, doublequote=False, lineterminator='\n', quoting=csv.QUOTE_NONE) rows = [dict(e) for e in reader] return rows
def test_later_default_lr(): import tempfile tmp_file = tempfile.mktemp() lr = 0.0005 learning_rates = list(numpy.linspace(0.0003, lr, num=10)) config = Config() config.update({'learning_rate_file': tmp_file, 'learning_rate_control': 'newbob_multi_epoch', 'learning_rate_control_relative_error_re...
def fasterrcnn_resnet8_fpn(num_classes=91, pretrained_backbone=True, weight_loss=False, detection_score_thres=0.05, use_soft_nms=False, nms_thres=0.4, anchor_sizes=[32, 64, 128, 256, 512], n_channel_backbone=5, use_context=False, use_track_branch=False, **kwargs): backbone = resnet_fpn_backbone('resnet8', pretraine...
def model_fn(config, batch): model = femr.models.transformer.EHRTransformer(config)(batch) return model
class CharacteristicCohomologyClassRing(FiniteGCAlgebra): Element = CharacteristicCohomologyClassRingElement def __init__(self, base, vbundle): self._vbundle = vbundle self._domain = vbundle._base_space dim = self._domain._dim rk = vbundle._rank if (vbundle._field_type ==...
def get_data_path(name): if (name == 'cityscapes'): return './data/city_dataset/' if (name == 'pascal_context'): return './data/'
def mytqdm(list_, desc='', show=True): if show: pbar = tqdm(list_) pbar.set_description(desc) return pbar return list_
class Lgmres(Benchmark): params = [[10, 50, 100, 1000, 10000], [10, 30, 60, 90, 180]] param_names = ['n', 'm'] def setup(self, n, m): rng = np.random.default_rng(1234) self.A = (sparse.eye(n, n) + sparse.rand(n, n, density=0.01, random_state=rng)) self.b = np.ones(n) def time_inn...
def grapheme_pipeline(char, grapheme_encoder=None, uppercase=True): if uppercase: char = char.upper() grapheme_list = [grapheme for grapheme in char if (grapheme in grapheme_encoder.lab2ind)] (yield grapheme_list) grapheme_encoded_list = grapheme_encoder.encode_sequence(grapheme_list) (yield...
def _has_hash(path, expected_hash): if (not os.path.exists(path)): return False return (pooch.file_hash(path) == expected_hash)
def plot_all_labeling_functions(df_results: pd.DataFrame, score: str, path_to_output_dir: str, model_heads: Optional[List[Tuple[(str, str)]]]=None, is_x_scale_log: bool=True, is_std_bars: bool=True): (fig, axes) = plt.subplots(5, 3, figsize=(20, 20)) labeling_functions: List[str] = df_results[(df_results['score...
def rms_norm(x, weight=None, eps=1e-05): output = (x * torch.rsqrt((x.pow(2).mean((- 1), keepdim=True) + eps))) if (weight is not None): return (output * weight) return output
def train_val_split(base_dataset: torchvision.datasets.CIFAR10, subset_percent=1.0): num_classes = 10 base_dataset = np.array(base_dataset) train_n = int((((len(base_dataset) * subset_percent) * 1.0) / num_classes)) val_n = int(((len(base_dataset) * 0.9) / num_classes)) train_idxs = [] val_idxs ...
class TestCompositeParametrization(unittest.TestCase): def test_get_structure(self): param_1 = parametrization.DirectParam(np.array([1, 2, 1, 4]), bounds=[0, 1]) param_2 = parametrization.DirectParam(np.array([2, 2, 1]), bounds=[0.9, 2.1]) param_3 = QuadraticParam(np.array([1, 2, 1, 1, 5]), ...
def write_csv_data_from_pkl(pkl_inputfile, csv_outputfile, fields, windowt=8, thresh=4, flag_increase_data=True, namefilebasin=None): file = open(pkl_inputfile, 'rb') list_tracks = pickle.load(file) file.close() name_cols = ['stormid', 'delay_tsteps', 'intenseStorm'] for field in fields: if ...
class BilateralFilter(AbstractFilter): def __init__(self, image, alpha, beta): self.alpha = alpha self.beta = beta super(BilateralFilter, self).__init__(image) def _calc_features(self, image): xy = _spatial_features(image, self.alpha) rgb = (image / float(self.beta)).perm...
def run(args): tokenizer = AutoTokenizer.from_pretrained(args.t5_model) dataloader = get_loader(args.test_file, args.batch_size, args.t5_model, args.max_length, args.max_decode_step, shuffle=False) device = torch.cuda.current_device() model = T5ForConditionalGeneration.from_pretrained(args.t5_model) ...
def arrange_disamb_results_in_lagacy_format(split_id, entity_predictions_file): dataset_id = 'grail' example_cache = join('feature_cache', f'{dataset_id}_{split_id}_disamb_examples.bin') entities_file = f'outputs/grail_{split_id}_entities.json' if os.path.exists(example_cache): instances = torch...
class L1(nn.Module): def __init__(self): super(L1, self).__init__() def forward(self, output, target): lossvalue = torch.abs((output - target)).mean() return lossvalue
def butterworth(image, cutoff_frequency_ratio=0.005, high_pass=True, order=2.0, channel_axis=None, *, squared_butterworth=True, npad=0): if (npad < 0): raise ValueError('npad must be >= 0') elif (npad > 0): center_slice = tuple((slice(npad, (s + npad)) for s in image.shape)) image = np.p...
class A001147(SloaneSequence): def __init__(self): SloaneSequence.__init__(self, offset=0) def _repr_(self): return 'Double factorial numbers: (2n-1)!! = 1.3.5....(2n-1).' def _eval(self, n): return (arith.factorial((2 * n)) / (arith.factorial(n) * (2 ** n)))
class ResBlock(nn.Module): def __init__(self, conv, n_feats, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1): super(ResBlock, self).__init__() m = [] for i in range(2): m.append(conv(n_feats, n_feats, kernel_size, bias=bias)) if bn: m...
def Ring(n, order='lp', names=None, blocks=None): if (blocks is None): blocks = [] pbnames = names if (pbnames is None): pbnames = [(('x(' + str(idx)) + ')') for idx in range(n)] order = TermOrder_from_pb_order(n, order, blocks) return BooleanPolynomialRing(n, names=pbnames, order=or...
def cppunparse(node, expr_semicolon=True, locals=None, defined_symbols=None): strio = StringIO() CPPUnparser(node, 0, (locals or CPPLocals()), strio, expr_semicolon=expr_semicolon, defined_symbols=defined_symbols) return strio.getvalue().strip()
def _check_matching_outputs(): rf.get_run_ctx().check_outputs_complete() model_outputs_raw_keys = set(_get_model_outputs_raw_keys()) outputs_raw = rf.get_run_ctx().outputs.as_raw_tensor_dict(include_scalar_dyn_sizes=False) outputs_raw_keys = set(outputs_raw.keys()) assert (model_outputs_raw_keys == ...
def _text_to_num_mark(text: str, return_nan_mark: bool=True): if text.endswith('%'): text4num = text[:(- 1)] is_percent = True else: text4num = text is_percent = False try: possible_value = float(text4num) except: if return_nan_mark: return '<n...
def register_Ns3UdpEchoServerHelper_methods(root_module, cls): cls.add_constructor([param('ns3::UdpEchoServerHelper const &', 'arg0')]) cls.add_constructor([param('uint16_t', 'port')]) cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) cls.add...
class GroupLinearLayer(nn.Module): def __init__(self, num_blocks, din, dout, bias=True): super(GroupLinearLayer, self).__init__() self.bias = bias self.w = nn.Parameter(torch.Tensor(num_blocks, din, dout)) self.b = nn.Parameter(torch.Tensor(1, num_blocks, dout)) stdv = (math....
def test_change_call_function(function_mock, default_test_case): default_test_case.add_statement(stmt.FloatPrimitiveStatement(default_test_case, 3.5)) to_replace = stmt.NoneStatement(default_test_case) default_test_case.add_statement(to_replace) test_cluster = default_test_case.test_cluster feed_typ...
def hierarchical_dataset(root, opt, select_data='/', data_type='label', mode='train'): dataset_list = [] dataset_log = f'dataset_root: {root} dataset: {select_data}' print(dataset_log) dataset_log += '\n' for (dirpath, dirnames, filenames) in os.walk((root + '/')): if (not dirnames): ...
def rule_vs_node_stat(): line_num = 0 parse_trees = [] code_file = '/Users/yinpengcheng/Research/SemanticParsing/CodeGeneration/card_datasets/hearthstone/all_hs.out' node_nums = rule_nums = 0.0 for line in open(code_file): code = line.replace('', '\n').strip() parse_tree = parse(code...
class ImplBase(metaclass=ABCMeta): _observation_shape: Shape _action_size: int _modules: Modules _checkpointer: Checkpointer _device: str def __init__(self, observation_shape: Shape, action_size: int, modules: Modules, device: str): self._observation_shape = observation_shape sel...
def get_specific_file(path, last_entry='tif'): base_path = path for i in os.listdir(path): if i.endswith(last_entry): return os.path.join(base_path, i) return '-1'
def _faulty_process_group_init_backend_handler(store, name, rank, world_size, rpc_backend_options): from . import FaultyProcessGroupAgent if dist.is_initialized(): raise RuntimeError('Process group must not be initialized before init_rpc.') process_group_timeout = rpc_constants.DEFAULT_PROCESS_GROUP...
def register_optimizer(name, optimizer_class): if (name in _OPTIMIZER_TYPES): raise RegistrationError(f"Optimizer '{name}' is already registered") _OPTIMIZER_TYPES[name] = optimizer_class
class HMI(Device): def _start(self): self.main_loop() def _stop(self): if (self.protocol['mode'] > 0): self._protocol._server_subprocess.kill() def main_loop(self, sleep=0.5): sec = 0 while (sec < 1): print('TODO HMI main_loop: please override me') ...
def device_type(device: Union[(str, int)]): if (device == 'cpu'): return device assert device.isnumeric() return f'cuda:{device}'
def beta_prior_d(k, n, lk, ln, a0=1, b0=1, plot=True): from scipy.stats import beta as beta_d a = (a0 + n.sum()) b = ((b0 + k.sum()) - n.sum()) posterior = beta_d(a, b) def p_d(d): p = (compute_discrete_volume(ln, d) / compute_discrete_volume(lk, d)) dp_dd = _compute_jacobian(lk, ln,...
class SuperbPR(SuperbASR): def default_config(self) -> dict: return dict(start=0, stop=None, target_dir=MISSING, cache_dir=None, remove_all_cache=False, prepare_data=dict(dataset_root=MISSING, train_sets=['train-clean-100'], valid_sets=['dev-clean'], test_sets=['test-clean']), prepare_tokenizer_data=dict(),...
def test_is_datetime_type_with_int(): data = 2 is_datetime = is_datetime_type(data) assert (is_datetime is False)
def multiple_tensors_mse_loss(y_list: List[tf.Tensor], x_list: List[tf.Tensor], fxp_w_list: List[List[tf.Tensor]], flp_w_list: List[List[tf.Tensor]], act_bn_mean: List, act_bn_std: List, loss_weights: List[float]=None) -> tf.Tensor: loss_values_list = [] for (i, (y, x)) in enumerate(zip(y_list, x_list)): ...
def default_signature(fn, source, _n_arguments, _n_binders): if (_n_binders is None): raise RuntimeError('default_signature needs to know the number of binders') if ((source is None) and (_n_arguments is None)): raise RuntimeError('default_signature needs either the source or the number of argum...
class TestNewton(TestScalarRootFinders): def test_newton_collections(self): known_fail = ['aps.13.00'] known_fail += ['aps.12.05', 'aps.12.17'] for collection in ['aps', 'complex']: self.run_collection(collection, zeros.newton, 'newton', smoothness=2, known_fail=known_fail) d...
.parametrize('gzip_response', [True, False]) .parametrize('dataset_params', [{'data_id': 40675}, {'data_id': None, 'name': 'glass2', 'version': 1}]) def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params): data_id = 40675 _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response) ...
def encode_spm(model, direction, prefix='', splits=['train', 'test', 'valid'], pairs_per_shard=None): (src, tgt) = direction.split('-') for split in splits: (src_raw, tgt_raw) = (f'{RAW_DIR}/{split}{prefix}.{direction}.{src}', f'{RAW_DIR}/{split}{prefix}.{direction}.{tgt}') if (os.path.exists(sr...
class _OSA_stage(nn.Sequential): def __init__(self, in_ch, stage_ch, concat_ch, block_per_stage, layer_per_block, stage_num, SE=False, depthwise=False): super(_OSA_stage, self).__init__() if (not (stage_num == 2)): self.add_module('Pooling', nn.MaxPool2d(kernel_size=3, stride=2, ceil_mod...
def header_to_xml(header_lines, book, output_xml_path): header_lines = [[y for y in x] for x in group_ranges(header_lines)] d = {x[0]: x[(- 1)] for x in header_lines} ET.strip_tags(book, 'section') for (from_line, to_line) in d.items(): f = book.find((('.//line[="' + str(from_line)) + '"]')) ...
def valuetype_type(t: Type) -> Optional[str]: if isinstance(t, BaseType): if (t.name == BaseTy.Tensor): return None elif (t.name == BaseTy.int): return 'int64_t' elif (t.name == BaseTy.float): return 'double' elif (t.name == BaseTy.str): ...
class RoIPool(torch.nn.Module): def __init__(self, pooled_height, pooled_width, spatial_scale): super(RoIPool, self).__init__() self.pooled_width = int(pooled_width) self.pooled_height = int(pooled_height) self.spatial_scale = float(spatial_scale) def forward(self, features, rois...
class DataProcessor(): _DTYPE_TO_SDTYPE = {'i': 'numerical', 'f': 'numerical', 'O': 'categorical', 'b': 'boolean', 'M': 'datetime'} def _update_numerical_transformer(self, enforce_rounding, enforce_min_max_values): custom_float_formatter = rdt.transformers.FloatFormatter(missing_value_replacement='mean'...
class EmailTrashPlayer(RecipePlayer): def __init__(self, state): fields = state.fields by = [element for element in state.dom_elements if ((element.text == fields['by']) and (element.ref in EMAIL_SENDER_REFS))] by = by[0] for (sender_ref, trash_ref) in zip(EMAIL_SENDER_REFS, EMAIL_TR...
def _parse(value, function, fmt): try: return function(value) except ValueError as e: raise_from(ValueError(fmt.format(e)), None)
def get_true_mi(syn_file_cat, z_dim): cmi_est = np.load('../data/cat{}/ksg_gt.dz{}.npy'.format(syn_file_cat, z_dim)) return float(cmi_est)
class Graph(): dict_contracts_per_vuln = {'ARTHM': 0, 'DOS': 0, 'LE': 0, 'RENT': 0, 'TimeM': 0, 'TimeO': 0, 'TX-Origin': 0, 'UE': 0} no_of_vuln = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0} def majority_warnings_per_vuln(self): filename = (data_path + 'scrawld_majority_all.txt') f...
def load_dataset(dataset_name, subset_name): try: return datasets.load_dataset(dataset_name, subset_name) except datasets.builder.ManualDownloadError: cache_root_dir = (os.environ['PROMPTSOURCE_MANUAL_DATASET_DIR'] if ('PROMPTSOURCE_MANUAL_DATASET_DIR' in os.environ) else DEFAULT_PROMPTSOURCE_CA...
class Lamb(Optimizer): def __init__(self, params, lr=0.001, warmup=(- 1), t_total=(- 1), schedule='warmup_linear', betas=(0.9, 0.999), eps=1e-08, weight_decay=0.0, adam=False, correct_bias=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0...
(params=['2.0', '3.0']) def schema_with_optional_headers(request): if (request.param == '2.0'): base_schema = request.getfixturevalue('empty_open_api_2_schema') base_schema['paths'] = {'/data': {'get': {'responses': {'200': {'description': 'OK', 'schema': {'type': 'object'}, 'headers': {'X-Optional'...