code
stringlengths
281
23.7M
def simrank(G, nodelist=None, c=0.8, num_iterations=10, weight='weight'): n = len(G) M = raw_google_matrix(G, nodelist=nodelist, weight=weight) sim = np.identity(n, dtype=np.float32) for i in range(num_iterations): log.debug('Starting SimRank iteration %d', i) temp = (((c * M.T) sim) M...
def __get_occurrence_variance(occurrence_matrix: np.ndarray, axis=0) -> float: prob_matrix = __get_probability_matrix(occurrence_matrix) tmp_mean_vec = np.sum(prob_matrix, axis=axis) mean_value = __get_occurrence_mean(occurrence_matrix, axis=axis) var_value = 0.0 for i in range(len(tmp_mean_vec)): ...
def _matmul_to_gemm(node: NodeProto, model: ModelProto): assert (node.op_type == 'MatMul') (weight, transposed) = retrieve_constant_input(node, model, WEIGHT_INDEX) if transposed: node.input[WEIGHT_INDEX] = weight.name model.graph.initializer.remove(weight) weight = transpose_tensor(...
class PromoteChatMember(): async def promote_chat_member(self: 'pyrogram.Client', chat_id: Union[(int, str)], user_id: Union[(int, str)], privileges: 'types.ChatPrivileges'=None) -> bool: chat_id = (await self.resolve_peer(chat_id)) user_id = (await self.resolve_peer(user_id)) if (privileges...
.parametrize('method, command', [('x1', 'X1.'), ('y1', 'Y1.'), ('x2', 'X2.'), ('y2', 'Y2.')]) def test_failing_properties(method, command): with pytest.raises(ValueError): with expected_protocol(Ametek7270, [(f'{command}'.encode(), b'\n')]) as inst: (getattr(inst, method) == 0.0)
class CTCCriterion(nn.Module): def __init__(self, train_config): super().__init__() self.train_config = train_config self.logsoftmax = nn.LogSoftmax(dim=2) self.criterion = nn.CTCLoss(reduction='sum', zero_infinity=True) def forward(self, output_tensor: torch.tensor, output_lengt...
class MyR2plus1d(nn.Module): def __init__(self, num_classes, use_pretrained=True, init_std=0.01, model_name='r2plus1d'): super(MyR2plus1d, self).__init__() self.model_ft = models.video.r2plus1d_18(pretrained=use_pretrained) num_ftrs = self.model_ft.fc.in_features self.init_std = init...
class AoA_Decoder_Core(nn.Module): def __init__(self, opt): super(AoA_Decoder_Core, self).__init__() self.drop_prob_lm = opt.drop_prob_lm self.d_model = opt.rnn_size self.use_multi_head = opt.use_multi_head self.multi_head_scale = opt.multi_head_scale self.use_ctx_dro...
class Model(): def __init__(self, args): self.dataName = args.dataName self.dataSet = DataSet(self.dataName) self.shape = self.dataSet.shape self.maxRate = self.dataSet.maxRate self.train = self.dataSet.train self.test = self.dataSet.test self.negNum = args.ne...
def _get_dataframe_movielens(name: str, folder_path: Path) -> pd.DataFrame: if (name == 'ml-1m'): file_path = folder_path.joinpath('ratings.dat') df = pd.read_csv(file_path, sep='::', header=None) elif (name == 'ml-20m'): file_path = folder_path.joinpath('ratings.csv') df = pd.re...
def delimited_loads(explode: bool, name: str, schema_type: str, location: Mapping[(str, Any)], delimiter: str) -> Any: value = location[name] explode_type = (explode, schema_type) if (explode_type == (False, 'array')): return split(value, separator=delimiter) if (explode_type == (False, 'object'...
class PrintTextWavePass(BasePass): chars_per_cycle = MetadataKey(int) enable = MetadataKey(bool) textwave_func = MetadataKey() textwave_dict = MetadataKey() def __call__(self, top): if (top.has_metadata(self.enable) and top.get_metadata(self.enable)): assert (not top.has_metadata...
class TestAdamOptimizer(TestOptimizer, unittest.TestCase): def _check_momentum_buffer(self): return False def _get_config(self): return {'name': 'adam', 'num_epochs': 90, 'lr': 0.1, 'betas': (0.9, 0.99), 'eps': 1e-08, 'weight_decay': 0.0001, 'amsgrad': False} def _instance_to_test(self): ...
class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential(nn.Linear(channel, (channel // reduction), bias=False), nn.ReLU(inplace=True), nn.Linear((channel // reduction), (channel // re...
def simple_perturb(text: str, method: str, perturbation_level=0.2): if (not (0 <= perturbation_level <= 1)): raise ValueError('Invalid value for perturbation level.') if (method == 'segment'): return segmentation(text, perturbation_level) words = nltk.word_tokenize(text) word_indexes = l...
def build_augmentation(cfg, is_train): logger = logging.getLogger(__name__) aug_list = [] if is_train: if cfg.INPUT.CROP.ENABLED: aug_list.append(T.RandomCrop(cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE)) min_size = cfg.INPUT.MIN_SIZE_TRAIN max_size = cfg.INPUT.MAX_SIZE_TRAI...
class ResourceTest(unittest.TestCase): def test_copy_resource(self) -> None: old_capabilities = {'test_key': 'test_value', 'old_key': 'old_value'} resource = Resource(1, 2, 3, old_capabilities) new_resource = Resource.copy(resource, test_key='test_value_new', new_key='new_value') sel...
class OpenVPNCollector(diamond.collector.Collector): def get_default_config_help(self): config_help = super(OpenVPNCollector, self).get_default_config_help() config_help.update({'instances': 'List of instances to collect stats from', 'timeout': 'network timeout'}) return config_help def ...
def test_type(make_union): assert_normalize(type, type, [nt_zero(Any)]) assert_normalize(Type, type, [nt_zero(Any)]) assert_normalize(Type[int], type, [nt_zero(int)]) assert_normalize(Type[Any], type, [nt_zero(Any)]) assert_normalize(Type[make_union[(int, str)]], Union, [normalize_type(Type[int]), n...
def generate_number(vcf_number, alt_alleles): if (vcf_number == '.'): return np.random.randint(1, 10) elif str_is_int(vcf_number): return int(vcf_number) elif (vcf_number == 'A'): return alt_alleles elif (vcf_number == 'R'): return (alt_alleles + 1) elif (vcf_number =...
('hash-clear!', [W_HashTable], simple=False) def hash_clear_bang(ht, env, cont): from pycket.interpreter import return_value if ht.is_impersonator(): ht.hash_clear_proc(env, cont) return hash_clear_loop(ht, env, cont) else: ht.hash_empty() return return_value(values.w_void, e...
class BVMFExchangeCalendar(TradingCalendar): name = 'BVMF' tz = timezone('America/Sao_Paulo') open_times = ((None, time(10, 1)),) close_times = ((None, time(17, 0)), (pd.Timestamp('2019-11-04'), time(18, 0))) def adhoc_holidays(self): return [CopaDoMundo2014] def regular_holidays(self): ...
('/get/previewinfo', methods=['GET']) _wrapper_json def get_previewinfo(): trans = MigrateDal.get_isp_trans() domain_count = ViewRecordDal.zone_domain_count() migrate_list = [] histories = MigrateDal.get_migrated_history() for history in histories: migrate_list.append({'migrate_rooms': sorte...
def deprecated(*, reason, version): version = _vparse(str(version)) add_warning = _deprecated(reason=reason, version=version, category=SKCriteriaDeprecationWarning, action=('error' if (_ERROR_GE_VERSION <= version) else 'once')) def _dec(func): decorated_func = add_warning(func) decorated_fu...
class BoundingProvider(RequestClassDeterminedProvider, ProviderWithRC): def __init__(self, request_checker: RequestChecker, provider: Provider): self._request_checker = request_checker self._provider = provider def apply_provider(self, mediator: Mediator, request: Request[T]) -> T: self....
def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distributed: if ((args.dist_url == 'env://') and (args.rank == (- 1))): args.rank = int(os.environ['RANK']) ...
def GetTestData(path, cfg): sr = cfg.sampling_rate (wav, fs) = sf.read(path) (wav, _) = librosa.effects.trim(y=wav, top_db=cfg.top_db) if (fs != sr): wav = resampy.resample(x=wav, sr_orig=fs, sr_new=sr, axis=0) fs = sr assert (fs == 16000), 'Downsampling needs to be done.' peak =...
def generate_customers_sql_values(file_name): f = open(file_name, 'r') lines = f.readlines() out = [] lines = lines[1:] for line in lines: line = line.strip() (id, first_name, last_name, age, joined_at) = line.split(',') out.append("({id}, '{first_name}', '{last_name}', {age}...
class MultilingualDeltaLMTokenizer(DeltaLMTokenizer): vocab_files_names = VOCAB_FILES_NAMES max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP model_input_names = ['input_ids', 'attention_mask'] prefix_tokens: List[int] = [] suf...
.parametrize('has_global_name', [False, True]) .parametrize('existing', [False, True]) def test_browser_discord_login_callback_with_sid(mocker: pytest_mock.MockerFixture, clean_database, flask_app, existing, has_global_name): mock_emit = mocker.patch('flask_socketio.emit') mock_render = mocker.patch('flask.rend...
def duplicate_module(module_file: Union[(str, os.PathLike)], old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, dest_file: Optional[str]=None, add_copied_from: bool=True, attrs_to_remove: List[str]=None): if (dest_file is None): dest_file = str(module_file).replace(old_model_patterns.mode...
class TestRepositoryManifestLabels(ApiTestCase): def test_basic_labels(self): self.login(ADMIN_ACCESS_USER) repo_ref = registry_model.lookup_repository(ADMIN_ACCESS_USER, 'complex') tag = registry_model.get_repo_tag(repo_ref, 'prod') repository = (ADMIN_ACCESS_USER + '/complex') ...
class AtomDataType(object): IMPLICIT = 0 UTF8 = 1 UTF16 = 2 SJIS = 3 HTML = 6 XML = 7 UUID = 8 ISRC = 9 MI3P = 10 GIF = 12 JPEG = 13 PNG = 14 URL = 15 DURATION = 16 DATETIME = 17 GENRES = 18 INTEGER = 21 RIAA_PA = 24 UPC = 25 BMP = 27
def evaluate(args, iteration, miner, miner_semantic): (gen_i, gen_j) = args.gen_sample.get(args.image_size, (10, 5)) images = [] miner.eval() miner_semantic.eval() with torch.no_grad(): for i in range(gen_i): images.append(G_running_target(miner(fixed_noise[i].cuda()), step=step,...
def batch_psnr(gen_frames, gt_frames): x = np.int32(gen_frames) y = np.int32(gt_frames) num_pixels = float(np.size(gen_frames[0])) mse = (np.sum(((x - y) ** 2), axis=(1, 2), dtype=np.float32) / num_pixels) psnr = ((20 * np.log10(255)) - (10 * np.log10(mse))) return np.mean(psnr)
class TestArgs(): def test_simple(self, qtbot, signaller): with qtbot.waitSignal(signaller.signal_args) as blocker: signaller.signal_args.emit('test', 123) assert (blocker.args == ['test', 123]) def test_timeout(self, qtbot, signaller): with qtbot.waitSignal(signaller.signal,...
def test_035_parseTime_suppress_auto_month(): next_day = tomorrow.day if (next_day > today.day): last_year = (today.year - 1) timestr = ('%02d1651Z' % next_day) report = Metar.Metar(('KEWR ' + timestr), month=1) assert report.decode_completed assert (report.time.day == ne...
def test_add_opening_quote_basic_quote_added(cmd2_app): text = 'Ha' line = 'test_basic {}'.format(text) endidx = len(line) begidx = (endidx - len(text)) expected = sorted(['"Ham', '"Ham Sandwich'], key=cmd2_app.default_sort_key) first_match = complete_tester(text, line, begidx, endidx, cmd2_app)...
def test_struct_port_single(do_test): class struct(): bar: Bits32 foo: Bits32 class A(Component): def construct(s): s.in_ = InPort(struct) a = A() a._ref_symbols = {'struct__bar_32__foo_32': struct} a._ref_decls = ['s.in_ = InPort( struct__bar_32__foo_32 )'] d...
class GCN(object): def __init__(self, graph, learning_rate=0.01, epochs=200, hidden1=16, dropout=0.5, weight_decay=0.0005, early_stopping=10, max_degree=3, clf_ratio=0.1): self.graph = graph self.clf_ratio = clf_ratio self.learning_rate = learning_rate self.epochs = epochs se...
class Solution(object): def convertBST(self, root): total = 0 node = root stack = [] while (stack or (node is not None)): while (node is not None): stack.append(node) node = node.right node = stack.pop() total += nod...
def setUpModule(): global mol, mf, myadc r = 1.098 mol = gto.Mole() mol.atom = [['N', (0.0, 0.0, ((- r) / 2))], ['N', (0.0, 0.0, (r / 2))]] mol.basis = {'N': 'aug-cc-pvdz'} mol.verbose = 0 mol.build() mf = scf.RHF(mol) mf.conv_tol = 1e-12 mf.kernel() myadc = adc.ADC(mf)
def clear_mem(): global K, M, N, S, unum, ww global my_dict, sub_ptn_list, ptn_len, sDB global minsup, NumbS, freArr, canArr, candidate K = 600 M = 100 N = 60000 S = '' unum = [0.0 for i in range(K)] ww = 0 my_dict = dict() sub_ptn_list = [sub_ptn() for i in range(M)] ptn...
def get_inceptionv3(model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): init_block_channels = 192 channels = [[256, 288, 288], [768, 768, 768, 768, 768], [1280, 2048, 2048]] b_mid_channels = [128, 160, 160, 192] net = InceptionV3(channels=channels, init_block_channe...
_model_architecture('model_parallel_transformer_lm', 'transformer_lm_megatron_11b') def transformer_lm_megatron_11b(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 3072) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', (3072 * 6)) args.decoder_layers = getattr(args, 'de...
def list_models(filter='', module='', pretrained=False, exclude_filters='', name_matches_cfg=False): if module: all_models = list(_module_to_models[module]) else: all_models = _model_entrypoints.keys() if filter: models = [] include_filters = (filter if isinstance(filter, (tu...
class Trainer(): def __init__(self): self._opt = TrainOptions().parse() PRESET_VARS = PATH(self._opt) self._model = ModelsFactory.get_by_name(self._opt.model_name, self._opt) train_transforms = self._model.resnet50.backbone.augment_transforms val_transforms = self._model.resn...
class Overlord(cmd2.Cmd): os.system('clear') version = cmd2.ansi.style('v.1.0', fg=Fg.RED, bg=None, bold=True, underline=False) print(f''' _ _ _____ _____ _ __| | ___ _ __ __| | / _ \ \ / / _ \ '__| |/ _ \| '__/ _` | | (_) \ V / __/ | | | (_) | | | (_| | \___/ \_/...
_optionals.HAS_GAUSSIAN.require_in_instance class GaussianDriver(ElectronicStructureDriver): def __init__(self, config: (str | list[str])='# rhf/sto-3g scf(conventional)\n\nh2 molecule\n\n0 1\nH 0.0 0.0 0.0\nH 0.0 0.0 0.735\n\n') -> None: super().__init__() if ((not isinstance(config, st...
def jetson_clocks_gui(stdscr, offset, start, jetson): jc_status_name = jetson.jetson_clocks.get_status() if (jc_status_name == 'running'): color = (curses.A_BOLD | NColors.green()) elif (jc_status_name == 'inactive'): color = curses.A_NORMAL elif ('ing' in jc_status_name): color ...
def _prepare_prompt_learning_config(peft_config, model_config): if (peft_config.num_layers is None): if ('num_hidden_layers' in model_config): num_layers = model_config['num_hidden_layers'] elif ('num_layers' in model_config): num_layers = model_config['num_layers'] e...
def get_rxn_smarts(probs): rxn_smarts = [] for key in probs: tokens = key.split(']') smarts = tokens[0] if (('-' in key) and ('#16' not in smarts)): smarts += ';!H0:1]>>[*:1]' if (('=' in key) and ('#16' not in smarts)): smarts += ';!H1;!H0:1]>>[*:1]' ...
class ConvNextImageProcessor(BaseImageProcessor): model_input_names = ['pixel_values'] def __init__(self, do_resize: bool=True, size: Dict[(str, int)]=None, crop_pct: float=None, resample: PILImageResampling=PILImageResampling.BILINEAR, do_rescale: bool=True, rescale_factor: Union[(int, float)]=(1 / 255), do_no...
def test_metadata_path_with_prepare(tmp_dir, package_test_setuptools): builder = build.ProjectBuilder(package_test_setuptools) metadata = _importlib.metadata.PathDistribution(pathlib.Path(builder.metadata_path(tmp_dir))).metadata assert (metadata['name'] == 'test-setuptools') assert (metadata['Version']...
class Migration(migrations.Migration): dependencies = [('api', '0080_add_aoc_tables')] operations = [migrations.CreateModel(name='BumpedThread', fields=[('thread_id', models.BigIntegerField(help_text='The thread ID that should be bumped.', primary_key=True, serialize=False, validators=[django.core.validators.Mi...
def create_model(session, Model_class, path, load_vec, config, id_to_char, logger): model = Model_class(config) ckpt = tf.train.get_checkpoint_state(path) if (ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path)): logger.info(('Reading model parameters from %s' % ckpt.model_checkpoint_pat...
class Solution(): def isValid(self, s: str) -> bool: d = {'#': 0, '(': (- 1), ')': 1, '[': (- 2), ']': 2, '{': (- 3), '}': 3} stack = [0] (start, end) = (0, len(s)) while (start < end): if (stack[(- 1)] == (- d[s[start]])): stack.pop() else: ...
def fasttext_export(embedding_file): fin = io.open(embedding_file, 'r', encoding='utf-8', newline='\n', errors='ignore') vocabulary = [] embeddings = [] line_idx = 0 for line in fin: if (line_idx == 0): line_idx += 1 continue tokens = line.rstrip().split(' ') ...
.parametrize('with_root', [True, False]) .parametrize('error', ['module', 'readme', '']) def test_install_warning_corrupt_root(command_tester_factory: CommandTesterFactory, project_factory: ProjectFactory, with_root: bool, error: str) -> None: name = 'corrupt' content = f'''[tool.poetry] name = "{name}" version...
class CustomSelector(discord.ui.Select): def __init__(self, placeholder: str, options: List[discord.SelectOption]): super().__init__(placeholder=placeholder, options=options) async def callback(self, interaction: discord.Interaction): (await interaction.response.defer()) self.view.custom...
def postprocess_text(preds, labels, metric_name): preds = [pred.strip() for pred in preds] labels = [label.strip() for label in labels] if (metric_name == 'rouge'): preds = ['\n'.join(nltk.sent_tokenize(pred)) for pred in preds] labels = ['\n'.join(nltk.sent_tokenize(label)) for label in lab...
def get_training_eval_datasets(cfg: DatasetConfig, shard_id: int, num_shards: int, eval_steps: int, feature_converter_cls: Callable[(..., seqio.FeatureConverter)], deterministic: bool=False, model_dir: Optional[str]=None, start_step: int=0) -> Mapping[(str, tf.data.Dataset)]: if isinstance(cfg.mixture_or_task_name,...
def get_smart_contracts_start_at(chain_id: ChainID) -> BlockNumber: if (chain_id == Networks.MAINNET.value): smart_contracts_start_at = EthereumForks.CONSTANTINOPLE.value elif (chain_id == Networks.ROPSTEN.value): smart_contracts_start_at = RopstenForks.CONSTANTINOPLE.value elif (chain_id ==...
.parametrize('case_name', _get_explicit_cases('positive')) def test_explicit_positive_examples(case_name, run_line): _check_file_format_skip(case_name) casedir = ((EXAMPLE_EXPLICIT_FILES / 'positive') / case_name) instance = (casedir / 'instance.json') if (not instance.exists()): instance = (cas...
class FlowStep(nn.Module): FlowPermutation = {'reverse': (lambda obj, z, logdet, rev: (obj.reverse(z, rev), logdet)), 'shuffle': (lambda obj, z, logdet, rev: (obj.shuffle(z, rev), logdet)), 'invconv': (lambda obj, z, logdet, rev: obj.invconv(z, logdet, rev)), 'squeeze_invconv': (lambda obj, z, logdet, rev: obj.invc...
.parametrize('connection_error,response_code,exception', [(True, 200, requests.exceptions.Timeout), (True, 200, requests.exceptions.ConnectionError), (False, 200, requests.exceptions.RequestException), (False, 200, ValueError), (True, 500, api.Non200ResponseException(mock.Mock(status_code=500))), (False, 400, api.Non20...
def set_network(vm_server, vm, target_network): nic = None backing_network = None for network in vm_server.getObject(vim.Network): if (target_network == network.name): backing_network = network break for device in vm.vmObject.config.hardware.device: if isinstance(...
class encoder(nn.Module): def __init__(self, in_channels, out_channels): super(encoder, self).__init__() self.down_conv = x2conv(in_channels, out_channels) self.pool = nn.MaxPool2d(kernel_size=2, ceil_mode=True) def forward(self, x): x = self.down_conv(x) x = self.pool(x)...
def find_in_rally(clipinfo_data, rally_num, num_hit): cnt = 0 shift_round = 0 for i in range(len(clipinfo_data['rally'])): if ((clipinfo_data['rally'][i] + shift_round) == rally_num): cnt += 1 if ((clipinfo_data['rally'][i] == 1) and (i != 0) and (clipinfo_data['rally'][(i - 1)] ...
class KnownValues(unittest.TestCase): def test_hcore(self): h1ref = pbchf.get_hcore(cell) h1 = pbchf.RHF(cell).get_hcore() self.assertAlmostEqual(abs((h1 - h1ref)).max(), 0, 9) self.assertAlmostEqual(lib.fp(h1), 0., 8) cell1 = cell.copy() cell1.ecp = {'He': (2, (((- 1...
def find_all_documented_objects(): documented_obj = [] for doc_file in Path(PATH_TO_DOC).glob('**/*.rst'): with open(doc_file, 'r', encoding='utf-8', newline='\n') as f: content = f.read() raw_doc_objs = re.findall('(?:autoclass|autofunction):: transformers.(\\S+)\\s+', content) ...
class CheckTypes(RPathTest): def testExist(self): self.assertTrue(rpath.RPath(self.lc, self.prefix, ()).lstat()) self.assertFalse(rpath.RPath(self.lc, 'asuthasetuouo', ()).lstat()) def testDir(self): self.assertTrue(rpath.RPath(self.lc, self.prefix, ()).isdir()) self.assertFalse(...
def combine(img_file, mask_file, class_name_list='VOC', include_color0=False, has_legend=True): img = Image.open(img_file) mask_p = Image.open(mask_file) mask_index = np.array(mask_p) mask_alpha = np.where(np.equal(mask_index, 0), 0, 180) mask_alpha = Image.fromarray(mask_alpha.astype(np.uint8), mod...
class DiscriminatorBlock(chainer.Chain): def __init__(self, in_ch, out_ch, initialW, sn=True): super(DiscriminatorBlock, self).__init__() with self.init_scope(): if sn: self.c0 = SNConvolution2D(in_ch, in_ch, 3, 1, 1, initialW=initialW) self.c1 = SNConvolu...
.asyncio(scope='class') class TestClassScopedLoop(): loop: asyncio.AbstractEventLoop _asyncio.fixture(scope='class') async def my_fixture(self): TestClassScopedLoop.loop = asyncio.get_running_loop() async def test_runs_is_same_loop_as_fixture(self, my_fixture): assert (asyncio.get_runnin...
.parametrize('func', [qutip.spin_state, partial(qutip.spin_coherent, phi=0.5)]) def test_spin_output(func): assert qutip.isket(func(1.0, 0, type='ket')) assert qutip.isbra(func(1.0, 0, type='bra')) assert qutip.isoper(func(1.0, 0, type='dm')) with pytest.raises(ValueError) as e: func(1.0, 0, typ...
class ArchCheckerReportConstants(): OP_STRUCT_OP_TYPE = 'OpStructure' DF_GRAPH_NODENAME = 'Graph/Layer_name' DF_ISSUE = 'Issue' DF_RECOMM = 'Recommendation' UNDEFINED_ISSUE = 'Undefined issue from check: {}' UNDEFINED_RECOMM = 'Undefined recommendation from check: {}' OUTPUT_CSV_HEADER = [DF...
class Graph(): def __init__(self, labeling_mode='spatial'): self.A = self.get_adjacency_matrix(labeling_mode) self.num_node = num_node self.self_link = self_link self.inward = inward self.outward = outward self.neighbor = neighbor def get_adjacency_matrix(self, la...
class ClassificationEvaluator(object): MACRO_AVERAGE = 'macro_average' MICRO_AVERAGE = 'micro_average' def __init__(self, eval_dir): self.confusion_matrix_list = None self.precision_list = None self.recall_list = None self.fscore_list = None self.right_list = None ...
class _IdentityExpBase(_AlgebraicExpBase): _operator = ' ? ' def __init__(self, members=()): super().__init__(template=None) self.members = tuple(members) super()._freeze_() def kind(self): if (not self.members): return 'identity' return self.members[0].ki...
class ServoCalibration(object): def __init__(self, servo): self.server = servo.server self.run = self.Register(BooleanProperty, 'run', False) self.rawcommand = self.Register(SensorValue, 'raw_command') self.console = self.Register(Value, 'console', '') self.current_total = se...
def test_monitor(): class SomethingElse(): def foo(self, n, y=None): self.n = n return y s = SomethingElse() original_method = s.foo.__func__ with CallMonitor(s.foo) as monitor: assert (s.foo(1, y='a') == 'a') assert (s.foo(2) is None) assert (s.foo.__...
def clean_room_edges(all_room_edges): refined_room_paths = [_extract_room_path(room_edges) for room_edges in all_room_edges] corner_to_room = defaultdict(list) for (room_idx, room_path) in enumerate(refined_room_paths): for corner in room_path: corner_to_room[corner].append(room_idx) ...
.functions (df=categoricaldf_strategy()) def test_all_cat_None_2(df): result = df.encode_categorical(names='appearance') categories = pd.CategoricalDtype(categories=df.names.factorize(sort=False)[(- 1)], ordered=True) expected = df.astype({'names': categories}) assert expected['names'].equals(result['na...
class LIPSegmentation(SegmentationDataset): BASE_DIR = 'LIP' NUM_CLASS = 20 def __init__(self, root='datasets/LIP', split='train', mode=None, transform=None, **kwargs): super(LIPSegmentation, self).__init__(root, split, mode, transform, **kwargs) _trainval_image_dir = os.path.join(root, 'Tra...
def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True): if (nlayers == 1): return nn.Linear(in_dim, bottleneck_dim, bias=bias) else: layers = [nn.Linear(in_dim, hidden_dim, bias=bias)] if use_bn: layers.append(nn.BatchNorm1d(hidden_dim)) ...
def extract_flavors_and_pens(penalties, penalty_keys, force_base=False, restrict=None): penalty_map = {k: penalties[idx] for (idx, k) in enumerate(penalty_keys)} (flavors, flavor_keys) = extract_flavors(penalties=penalties, keys=penalty_keys, force_base=force_base, restrict=restrict) parent_penalties = [] ...
def main(): parser = argparse.ArgumentParser(description='Preprocess ACE event data.') parser.add_argument('output_name', help='Name for output directory.') parser.add_argument('--use_span_extent', action='store_true', help='Use full extent of entity mentions instead of just heads.') parser.add_argument...
.repeat(2) .parametrize('superrep', ['choi', 'super']) def test_rand_super(dimensions, dtype, superrep): random_qobj = rand_super(dimensions, dtype=dtype, superrep=superrep) assert random_qobj.issuper with CoreOptions(atol=1e-09): assert random_qobj.iscptp assert (random_qobj.superrep == superre...
class AliasMethod(nn.Module): def __init__(self, probs): super(AliasMethod, self).__init__() if (probs.sum() > 1): probs.div_(probs.sum()) K = len(probs) self.register_buffer('prob', torch.zeros(K)) self.register_buffer('alias', torch.LongTensor(([0] * K))) ...
class logRegClassificationEvaluator(Evaluator): def __init__(self, sentences_train, y_train, sentences_test, y_test, max_iter=100, batch_size=32, limit=None, **kwargs): super().__init__(**kwargs) if (limit is not None): sentences_train = sentences_train[:limit] y_train = y_tr...
def test_complex_cepstrum(): duration = 5.0 fs = 8000.0 samples = int((fs * duration)) t = (np.arange(samples) / fs) fundamental = 100.0 signal = sawtooth((((2.0 * np.pi) * fundamental) * t)) (ceps, _) = complex_cepstrum(signal) assert (fundamental == (1.0 / t[ceps.argmax()]))
def test_search_paths(temp_dir, helpers): source = CodeSource(str(temp_dir), {'path': 'a/b.py', 'search-paths': ['.']}) parent_dir = (temp_dir / 'a') parent_dir.mkdir() (parent_dir / '__init__.py').touch() (parent_dir / 'b.py').write_text(helpers.dedent("\n from a.c import foo\n\n ...
def pytest_addoption(parser): group = parser.getgroup('xdist', 'distributed and subprocess testing') group._addoption('-n', '--numprocesses', dest='numprocesses', metavar='numprocesses', action='store', type=parse_numprocesses, help="Shortcut for '--dist=load --tx=NUM*popen'. With 'auto', attempt to detect phys...
class Logic(): game: GameDescription configuration: BaseConfiguration additional_requirements: list[RequirementSet] _attempts: int _current_indent: int = 0 _last_printed_additional: dict[(Node, RequirementSet)] def __init__(self, game: GameDescription, configuration: BaseConfiguration): ...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1, norm_layer=None): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilat...
class F23Handler(BaseHandler): version = F23 commandMap = {'auth': commands.authconfig.FC3_Authconfig, 'authconfig': commands.authconfig.FC3_Authconfig, 'autopart': commands.autopart.F23_AutoPart, 'autostep': commands.autostep.FC3_AutoStep, 'bootloader': commands.bootloader.F21_Bootloader, 'btrfs': commands.btr...
def plt_hist(axis, data, hatch, label, bins, col): (counts, edges) = np.histogram(data, bins=bins, range=[0, 1]) edges = np.repeat(edges, 2) hist = np.hstack((0, np.repeat(counts, 2), 0)) (outline,) = axis.plot(edges, hist, linewidth=1.3, color=col) axis.fill_between(edges, hist, 0, edgecolor=col, h...
class Quantizer(nn.Module): def __init__(self, shape=1): super(Quantizer, self).__init__() self.register_buffer('maxq', torch.tensor(0)) self.register_buffer('scale', torch.zeros(shape)) self.register_buffer('zero', torch.zeros(shape)) def configure(self, bits, perchannel=False, ...
def _check_if_dag_has_cycles(dag: nx.DiGraph) -> None: try: cycles = nx.algorithms.cycles.find_cycle(dag) except nx.NetworkXNoCycle: pass else: msg = f'''The DAG contains cycles which means a dependency is directly or indirectly a product of the same task. See the following the path ...