code
stringlengths
281
23.7M
.parametrize('section', ['console', 'gui']) .parametrize('kind', ['win-ia32', 'win-amd64', 'win-arm']) def test_script_generate_launcher(section, kind): launcher_data = _read_launcher_data(section, kind) script = Script('foo', 'foo.bar', 'baz.qux', section=section) (name, data) = script.generate('#!C:\\path...
def get_matched_files(refresh=False): TMP_MATCHED_FILES = '/tmp/matched_files.txt' if (refresh or (not os.path.exists(TMP_MATCHED_FILES))): with st.spinner('Refreshing... (this may take a while)'): matched_files = subprocess.run(['gsutil', 'ls', glob_pattern], capture_output=True) ...
class SnapshotRollbackView(ObjectPermissionMixin, RedirectViewMixin, DetailView): model = Snapshot queryset = Snapshot.objects.all() permission_required = 'projects.rollback_snapshot_object' template_name = 'projects/snapshot_rollback.html' def get_queryset(self): return Snapshot.objects.fil...
class TalkieConnectionOwner(object): def __init__(self): self._connections = [] def talkie_connect(self, state, path, listener, drop_args=False): if drop_args: listener = drop_args_wrapper(listener) if (not isinstance(path, str)): return [self.talkie_connect(state...
def test_instanceloader_yaml_dup_anchor(tmp_path, open_wide): f = (tmp_path / 'foo.yaml') f.write_text('a:\n b: &anchor\n - 1\n - 2\n c: &anchor d\n') loader = InstanceLoader(open_wide(f)) data = list(loader.iter_files()) assert (data == [(str(f), {'a': {'b': [1, 2], 'c': 'd'}})])
def test_cross_layer_equalization_stepwise(): orig = tf.keras.applications.ResNet50(input_shape=(224, 224, 3)) (folded_pairs, model) = fold_all_batch_norms(orig) bn_dict = {} for (conv_or_linear, bn) in folded_pairs: bn_dict[conv_or_linear] = bn (conv1, conv2, conv3) = (model.layers[6], mode...
class HTLCManager(): def __init__(self, log: 'StoredDict', *, initial_feerate=None): if (len(log) == 0): initial = {'adds': {}, 'locked_in': {}, 'settles': {}, 'fails': {}, 'fee_updates': {}, 'revack_pending': False, 'next_htlc_id': 0, 'ctn': (- 1)} log[LOCAL] = deepcopy(initial) ...
def get_normalize_mesh(model_file, norm_mesh_sub_dir): total = 16384 print('[*] loading model with trimesh...', model_file) mesh_list = trimesh.load_mesh(model_file, process=False) print('[*] done!', model_file) mesh = as_mesh(mesh_list) if (not isinstance(mesh, list)): mesh_list = [mesh...
def test_python_option(tester: CommandTester) -> None: inputs = ['my-package', '1.2.3', 'This is a description', 'n', 'MIT', 'n', 'n', '\n'] tester.execute("--python '~2.7 || ^3.6'", inputs='\n'.join(inputs)) expected = '[tool.poetry]\nname = "my-package"\nversion = "1.2.3"\ndescription = "This is a descrip...
def test_apply_classical_cbloq(): bb = BloqBuilder() x = bb.add_register(Register('x', 1, shape=(5,))) (x, y) = bb.add(ApplyClassicalTest(), x=x) (y, z) = bb.add(ApplyClassicalTest(), x=y) cbloq = bb.finalize(x=x, y=y, z=z) xarr = np.zeros(5) (x, y, z) = cbloq.call_classically(x=xarr) np...
class ChoiceFeedbackQuestionValueFactory(Factory): class Meta(): model = 'feedback.ChoiceFeedbackQuestionValue' strategy = factory.CREATE_STRATEGY question = factory.SubFactory('tests.factories.ChoiceFeedbackQuestionFactory') title = factory.Sequence((lambda n: 'title{}'.format(n))) valu...
def pdb_reformat(reference, target): from qubekit.molecules.protein import Protein pro = Protein(reference) print(pro.pdb_names) with open(target, 'r') as traj: lines = traj.readlines() PRO = False i = 0 new_traj = open('QUBE_traj.pdb', 'w+') for line in lines: if ('MODEL...
class MitreParser(): def __init__(self, name): self.graph = QBIxora(name) self.mitrepath = path.abspath(path.join(path.dirname(__file__), 'mitrefiles')) if (not self.mitrepath.endswith(path.sep)): self.mitrepath = (self.mitrepath + path.sep) if (not path.isdir(self.mitrep...
def get_files(**kwargs): metadata_directory = kwargs.get('metadata_directory', '') files = [] for f in get_template_files(**kwargs): if (str(f.path) == 'LICENSE.txt'): files.append(File(Path(metadata_directory, 'licenses', f.path), f.contents)) if (f.path.parts[0] not in {kwargs[...
def get_beam_indices_of_fraction_group(dicom_dataset, fraction_group_number): (beam_numbers, _) = get_referenced_beam_sequence(dicom_dataset, fraction_group_number) beam_sequence_numbers = [beam_sequence.BeamNumber for beam_sequence in dicom_dataset.BeamSequence] beam_indexes = [beam_sequence_numbers.index(...
def _load_library(): osp = os.path if sys.platform.startswith('darwin'): libfile = osp.abspath(osp.join(osp.dirname(__file__), '../../vendor/mujoco/libglfw.3.dylib')) elif sys.platform.startswith('linux'): libfile = osp.abspath(osp.join(osp.dirname(__file__), '../../vendor/mujoco/libglfw.so....
def AddExtraLayers(net, use_batchnorm=True): use_relu = True from_layer = net.keys()[(- 1)] out_layer = 'conv6_1' ConvBNLayer(net, from_layer, out_layer, use_batchnorm, use_relu, 256, 1, 0, 1) from_layer = out_layer out_layer = 'conv6_2' ConvBNLayer(net, from_layer, out_layer, use_batchnorm,...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True dataset = build_dataset(cfg.data.val) data_loader = build_dataloader(dataset, samples_per_gpu=1, workers_per_gpu=cfg.data.workers_per_gpu, dist=False...
def contractreceivechannelclosed_from_event(canonical_identifier: CanonicalIdentifier, event: DecodedEvent) -> ContractReceiveChannelClosed: data = event.event_data args = data['args'] return ContractReceiveChannelClosed(transaction_from=args['closing_participant'], canonical_identifier=canonical_identifier...
class ASFInfo(StreamInfo): length = 0.0 sample_rate = 0 bitrate = 0 channels = 0 codec_type = u'' codec_name = u'' codec_description = u'' def __init__(self): self.length = 0.0 self.sample_rate = 0 self.bitrate = 0 self.channels = 0 self.codec_type...
def remap(raw_file, remap_dict_file, remap_file): with open(remap_dict_file, 'rb') as f: uid_remap_dict = pkl.load(f) iid_remap_dict = pkl.load(f) cid_remap_dict = pkl.load(f) sid_remap_dict = pkl.load(f) bid_remap_dict = pkl.load(f) aid_remap_dict = pkl.load(f) ...
class MsgContainer(TLObject): ID = __slots__ = ['messages'] QUALNAME = 'MsgContainer' def __init__(self, messages: List[Message]): self.messages = messages def read(data: BytesIO, *args: Any) -> 'MsgContainer': count = Int.read(data) return MsgContainer([Message.read(data) f...
def exportMultiBuy(fit, options, callback): itemAmounts = {} for module in fit.modules: if module.item: if module.isMutated: continue _addItem(itemAmounts, module.item) if (module.charge and options[PortMultiBuyOptions.LOADED_CHARGES]): _addIte...
class CacheFTPHandler(FTPHandler): def __init__(self): self.cache = {} self.timeout = {} self.soonest = 0 self.delay = 60 self.max_conns = 16 def setTimeout(self, t): self.delay = t def setMaxConns(self, m): self.max_conns = m def connect_ftp(self,...
class Representer(SafeRepresenter): def represent_str(self, data): tag = None style = None try: data = unicode(data, 'ascii') tag = u'tag:yaml.org,2002:str' except UnicodeDecodeError: try: data = unicode(data, 'utf-8') ...
def test_is_open_on_minute(benchmark): xhkg = get_calendar('XHKG') timestamps = [pd.Timestamp('2019-10-11 01:20:00', tz=UTC), pd.Timestamp('2019-10-11 01:30:00', tz=UTC), pd.Timestamp('2019-10-11 01:31:00', tz=UTC), pd.Timestamp('2019-10-11 04:31:00', tz=UTC), pd.Timestamp('2019-10-11 08:00:00', tz=UTC), pd.Tim...
def make_dataset(path, impl, skip_warmup=False): if (not IndexedDataset.exists(path)): print(f'Dataset does not exist: {path}') print('Path should be a basename that both .idx and .bin can be appended to get full filenames.') return None if (impl == 'infer'): impl = infer_dataset...
class UperNetPyramidPoolingBlock(nn.Module): def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None: super().__init__() self.layers = [nn.AdaptiveAvgPool2d(pool_scale), UperNetConvModule(in_channels, channels, kernel_size=1)] for (i, layer) in enumerate(self.layers): ...
class Bottleneck(_Bottleneck): expansion = 4 def __init__(self, inplanes, planes, groups=1, base_width=4, base_channels=64, **kwargs): super(Bottleneck, self).__init__(inplanes, planes, **kwargs) if (groups == 1): width = self.planes else: width = (math.floor((sel...
def dL3_hat(mu, C_hat, r, m, n): vals = numpy.zeros(2) for i in range(m): numer0 = (C_hat[i][0] - C_hat[i][2]) numer1 = (C_hat[i][1] - C_hat[i][2]) denom = ((((C_hat[i][0] - C_hat[i][(n - 1)]) * mu[0]) + ((C_hat[i][1] - C_hat[i][(n - 1)]) * mu[1])) + C_hat[i][2]) vals[0] += (r[i]...
class TestInhibitAnyPolicyExtension(): def test_inhibit_any_policy(self, backend): cert = _load_cert(os.path.join('x509', 'custom', 'inhibit_any_policy_5.pem'), x509.load_pem_x509_certificate) iap = cert.extensions.get_extension_for_class(x509.InhibitAnyPolicy).value assert (iap.skip_certs =...
def get_hyperplanes(p1, p2, wrap): d = len(wrap) p2_list = [p2] wrap_amount = (2.0 * np.pi) for i in range(d): if wrap[i]: list_lo = [] list_hi = [] for p_ in p2_list: lo = np.copy(p_) lo[i] -= wrap_amount list_l...
def remap_ids(w, old2new, id_order=[], **kwargs): if (not isinstance(w, W)): raise Exception('w must be a spatial weights object') new_neigh = {} new_weights = {} for (key, value) in list(w.neighbors.items()): new_values = [old2new[i] for i in value] new_key = old2new[key] ...
class F39_Network(F27_Network): removedKeywords = F27_Network.removedKeywords removedAttrs = F27_Network.removedAttrs def _getParser(self): op = F27_Network._getParser(self) op.add_argument('--ipv4-dns-search', default=None, version=F39, dest='ipv4_dns_search', help='\n ...
def _find_dists(dists: List[str]) -> List[str]: uploads = [] for filename in dists: if os.path.exists(filename): uploads.append(filename) continue files = glob.glob(filename) if (not files): raise exceptions.InvalidDistribution(("Cannot find file (or e...
class Axicon(DOE): def __init__(self, period, radius=None, aberration=None): global bd from ..util.backend_functions import backend as bd self.period = period self.radius = radius def get_transmittance(self, xx, yy, ): t = 1 if (self.radius != None): t...
def cache_intermediate_datasets(cached_dataset, cache_on_cpu, model, module_name, forward_fn, path=None): cached_data = [] iterator = iter(cached_dataset) for idx in range(len(cached_dataset)): def fn(_, inputs): inputs = [*inputs] if cache_on_cpu: cached_data...
.parametrize('src_order', [15, 20, 25, 30]) .parametrize('src_gamma', [(- 1.0), (- 0.5), 0.0]) .parametrize('dst_order', [15, 20, 25, 30]) .parametrize('dst_gamma', [(- 1.0), (- 0.5), 0.0]) def test_gc2gc(src_order, src_gamma, dst_order, dst_gamma): np.random.seed(98765) src = np.random.rand((src_order + 1)) ...
.parametrize('has_output_dir', [False, True]) def test_on_output_file_button_exists(skip_qtbot, tmp_path, mocker, has_output_dir): mock_prompt = mocker.patch('randovania.gui.lib.common_qt_lib.prompt_user_for_output_file', autospec=True) if has_output_dir: output_directory = tmp_path.joinpath('output_pat...
def test_git_clone_fails_for_non_existent_revision(source_url: str) -> None: revision = sha1(uuid.uuid4().bytes).hexdigest() with pytest.raises(PoetryConsoleError) as e: Git.clone(url=source_url, revision=revision) assert (f"Failed to clone {source_url} at '{revision}'" in str(e.value))
(scope='session') def gerb_l2_hr_h5_dummy_file(tmp_path_factory): filename = (tmp_path_factory.mktemp('data') / FNAME) with h5py.File(filename, 'w') as fid: fid.create_group('/Angles') fid['/Angles/Relative Azimuth'] = np.ones(shape=(1237, 1237), dtype=np.dtype('>i2')) fid['/Angles/Relat...
_tests('aes_cbc_pkcs5_test.json') def test_aes_cbc_pkcs5(backend, wycheproof): key = binascii.unhexlify(wycheproof.testcase['key']) iv = binascii.unhexlify(wycheproof.testcase['iv']) msg = binascii.unhexlify(wycheproof.testcase['msg']) ct = binascii.unhexlify(wycheproof.testcase['ct']) padder = padd...
class HP11713A(Instrument): ATTENUATOR_X = {} ATTENUATOR_Y = {} channels = Instrument.MultiChannelCreator(SwitchDriverChannel, list(range(0, 9))) def __init__(self, adapter, name='Hewlett-Packard HP11713A', **kwargs): super().__init__(adapter, name, includeSCPI=False, send_end=True, **kwargs) ...
def pretix_quotas(): return {'count': 2, 'next': None, 'previous': None, 'results': [{'id': 1, 'name': 'Ticket Quota', 'size': 200, 'available_number': 118, 'items': [1], 'variations': [], 'subevent': None, 'close_when_sold_out': False, 'closed': False}, {'id': 2, 'name': 'T-shirt Quota', 'size': 200, 'available_nu...
class TasksRendererMixin(): def render_task(self, xml, task): if (task['uri'] not in self.uris): self.uris.add(task['uri']) xml.startElement('task', {'dc:uri': task['uri']}) self.render_text_element(xml, 'uri_prefix', {}, task['uri_prefix']) self.render_text_e...
def inspect_node(mixed, *, _partial=None): if isconfigurabletype(mixed, strict=True): (inst, typ) = (None, mixed) elif isconfigurable(mixed): (inst, typ) = (mixed, type(mixed)) elif hasattr(mixed, 'func'): return inspect_node(mixed.func, _partial=(mixed.args, mixed.keywords)) els...
class TweetEncoder(nn.Module): def __init__(self, output_dim=512): super().__init__() self._hidden_size = 768 self.bertweet = AutoModel.from_pretrained('vinai/bertweet-base') self.linear_transform = nn.Linear(self._hidden_size, output_dim) nn.init.xavier_normal_(self.linear_t...
def aggregate_text_similarities(result_dict): all_averages = [result_dict[prompt]['text_similarities'] for prompt in result_dict] all_averages = np.array(all_averages).flatten() total_average = np.average(all_averages) total_std = np.std(all_averages) return (total_average, total_std)
def reduce_leaky_relu(_, op_tensor_tuple: Tuple[(Op, List[tf.Tensor])], _op_mask) -> (str, tf.Operation, tf.Operation): name = ('reduced_' + op_tensor_tuple[0].dotted_name) alpha = op_tensor_tuple[0].get_module().get_attr('alpha') assert (alpha is not None) new_tensor = tf.nn.leaky_relu(op_tensor_tuple[...
def test_show_issue() -> None: class RESTObject(): def __init__(self, manager: str, attrs: int) -> None: ... class Mixin(RESTObject): ... with pytest.raises(TypeError) as exc_info: class Wrongv4Object(RESTObject, Mixin): ... assert ('MRO' in exc_info.excon...
def verify_build_token(token, aud, token_type, instance_keys): try: headers = jwt.get_unverified_header(token) except jwtutil.InvalidTokenError as ite: logger.error('Invalid token reason: %s', ite) raise InvalidBuildTokenException(ite) kid = headers.get('kid', None) if (kid is No...
class VolSDFTrainRunner(): def __init__(self, **kwargs): torch.set_default_dtype(torch.float32) torch.set_num_threads(1) f = open(kwargs['conf']) conf_text = f.read() conf_text = conf_text.replace('SCAN_ID', str(kwargs['scan_id'])) conf_text = conf_text.replace('VIEW_...
.parametrize('converter_cls', [BaseConverter, Converter]) .parametrize('unstructure_strat', [UnstructureStrategy.AS_DICT, UnstructureStrategy.AS_TUPLE]) def test_unstructure_attrs_mappings(benchmark, converter_cls, unstructure_strat): class FrozenCls(): a: int class C(): a: Mapping[(int, str)] ...
.parametrize('username,password', users) .parametrize('value_id', values) def test_detail(db, client, username, password, value_id): client.login(username=username, password=password) value = Value.objects.get(pk=value_id) url = reverse(urlnames['detail'], args=[value_id]) response = client.get(url) ...
def _update_user_newsletter(graphql_client, user, open_to_newsletter): query = '\n mutation(\n $open_to_newsletter: Boolean!,\n $open_to_recruiting: Boolean!,\n $date_birth: String\n ){\n update(input: {\n openToNewsletter: $open_to_newsletter,\n openToRecrui...
def load_ed25519_vectors(vector_data): data = [] for line in vector_data: (secret_key, public_key, message, signature, _) = line.split(':') secret_key = secret_key[0:64] signature = signature[0:128] data.append({'secret_key': secret_key, 'public_key': public_key, 'message': messa...
class NoneCoalesceTernaryVisitor(ast.NodeVisitor): def __init__(self, file_, callback): self.__file = file_ self.__callback = callback def visit_IfExp(self, ifexp): if isinstance(ifexp.test, ast.Compare): op = ifexp.test.ops[0] if (isinstance(op, (ast.Is, ast.IsNo...
_fixtures(ConfigWithFiles) def test_config_defaults_dangerous(config_with_files): fixture = config_with_files fixture.set_config_spec(easter_egg, 'reahl.component_dev.test_config:ConfigWithDangerousDefaultedSetting') config = StoredConfiguration(fixture.config_dir.name) with CallMonitor(logging.getLogge...
def test_parse_empty_string_default(default_parser): line = '' statement = default_parser.parse(line) assert (statement == '') assert (statement.args == statement) assert (statement.raw == line) assert (statement.command == '') assert (statement.arg_list == []) assert (statement.multilin...
class Migration(migrations.Migration): dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('schedule', '0002_auto__0043')] operations = [migrations.CreateModel(name='ScheduleItemType', fields=[('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True...
class TestBiasCorrection(unittest.TestCase): def test_get_output_data(self): tf.compat.v1.reset_default_graph() sess = tf.compat.v1.Session(graph=tf.Graph()) input_op_names = ['input_1'] output_op_name = 'scope_1/conv2d_2/Conv2D' with sess.graph.as_default(): _ = ...
class CssDjangoLexer(DelegatingLexer): name = 'CSS+Django/Jinja' aliases = ['css+django', 'css+jinja'] filenames = ['*.css.j2', '*.css.jinja2'] version_added = '' alias_filenames = ['*.css'] mimetypes = ['text/css+django', 'text/css+jinja'] url = ' def __init__(self, **options): ...
_rewriter([sparse.mul_s_v]) def local_mul_s_v(fgraph, node): if (node.op == sparse.mul_s_v): (x, y) = node.inputs x_is_sparse_variable = _is_sparse_variable(x) if x_is_sparse_variable: svar = x dvar = y else: svar = y dvar = x i...
class TarDataset(data.Dataset): def download_or_unzip(cls, root): path = os.path.join(root, cls.dirname) if (not os.path.isdir(path)): tpath = os.path.join(root, cls.filename) if (not os.path.isfile(tpath)): print('downloading') urllib.request....
def test_ConnectionState_inconsistent_protocol_switch() -> None: for (client_switches, server_switch) in [([], _SWITCH_CONNECT), ([], _SWITCH_UPGRADE), ([_SWITCH_UPGRADE], _SWITCH_CONNECT), ([_SWITCH_CONNECT], _SWITCH_UPGRADE)]: cs = ConnectionState() for client_switch in client_switches: ...
_module() class Compose(object): def __init__(self, transforms): assert isinstance(transforms, collections.abc.Sequence) self.transforms = [] for transform in transforms: if isinstance(transform, dict): transform = build_from_cfg(transform, PIPELINES) ...
class KeyPair(): def create_key_pair(key_size: int=1024): private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size) public_key = private_key.public_key() private_key_bytes = private_key.private_bytes(encoding=serialization.Encoding.DER, format=serialization.PrivateForm...
def file_content(): try: return importlib.resources.files('pytest_html').joinpath('resources', 'style.css').read_bytes().decode('utf-8').strip() except AttributeError: import pkg_resources return pkg_resources.resource_string('pytest_html', os.path.join('resources', 'style.css')).decode(...
def _model_variable_getter(getter, name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, rename=None, use_resource=None, synchronization=tf_variables.VariableSynchronization.AUTO, aggregation=tf_variables.VariableAggregation.NONE, **_)...
def get_resnet(blocks, bottleneck=None, conv1_stride=True, width_scale=1.0, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): if (bottleneck is None): bottleneck = (blocks >= 50) if (blocks == 10): layers = [1, 1, 1, 1] elif (blocks == 12): lay...
def plot_sapm(sapm_data, effective_irradiance): (fig, axes) = plt.subplots(2, 3, figsize=(16, 10), sharex=False, sharey=False, squeeze=False) plt.subplots_adjust(wspace=0.2, hspace=0.3) ax = axes[(0, 0)] sapm_data.filter(like='i_').plot(ax=ax) ax.set_ylabel('Current (A)') ax = axes[(0, 1)] s...
class DescribeCT_Tc(): def it_can_merge_to_another_tc(self, tr_, _span_dimensions_, _tbl_, _grow_to_, top_tc_): top_tr_ = tr_ (tc, other_tc) = (element('w:tc'), element('w:tc')) (top, left, height, width) = (0, 1, 2, 3) _span_dimensions_.return_value = (top, left, height, width) ...
def main(): parser = argparse.ArgumentParser(description='Baseline') parser.add_argument('--conf_path', type=str, metavar='conf_path', help='input the path of config file') parser.add_argument('--id', type=int, metavar='experiment_id', help='Experiment ID') args = parser.parse_args() option = Option...
class SawyerDialTurnV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'dial_pos': obs[3:6], 'goal_pos': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_pow': 3}) action['delta_pos...
def test_itransform_pipeline_radians(): trans = Transformer.from_pipeline('+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step +proj=unitconvert +xy_in=rad +xy_out=deg') assert_almost_equal(list(trans.itransform([((- 2704026.01), (- 4253051.81), 3895878.82)], radians=True)), [((- 2.), 0., (- 20.))]) ass...
.skipif((not fs_supports_symlink()), reason='symlink is not supported') def test_py_info_cached_symlink_error(mocker, tmp_path, session_app_data): spy = mocker.spy(cached_py_info, '_run_subprocess') with pytest.raises(RuntimeError): PythonInfo.from_exe(str(tmp_path), session_app_data) symlinked = (t...
def list2mat(input, undirected, sep, format): nodes = set() with open(input, 'r') as inf: for line in inf: if (line.startswith('#') or line.startswith('%')): continue line = line.strip() splt = line.split(sep) if (not splt): ...
def get_r50_l16_config(): config = get_l16_config() config.patches.grid = (16, 16) config.resnet = ml_collections.ConfigDict() config.resnet.num_layers = (3, 4, 9) config.resnet.width_factor = 1 config.classifier = 'seg' config.resnet_pretrained_path = '../model/vit_checkpoint/imagenet21k/R5...
def _box_aug_per_img(img, target, aug_type=None, scale_ratios=None, scale_splits=None, img_prob=0.1, box_prob=0.3, level=1): if (random.random() > img_prob): return (img, target) img_mean = torch.Tensor(pixel_mean).reshape(3, 1, 1).to(img.device) img = (img + img_mean) img /= 255.0 bboxes = ...
def get_model_params(model, cfg): optim_cfg = cfg.SOLVER base_lr = optim_cfg.BASE_LR params = [] for (key, value) in model.named_parameters(): if (not value.requires_grad): continue key_lr = [base_lr] if ('bias' in key): key_lr.append((cfg.SOLVER.BASE_LR *...
def format_rouge_scores(scores): return '\n\n****** ROUGE SCORES ******\n\n** ROUGE 1\nF1 >> {:.3f}\nPrecision >> {:.3f}\nRecall >> {:.3f}\n\n** ROUGE 2\nF1 >> {:.3f}\nPrecision >> {:.3f}\nRecall >> {:.3f}\n\n** ROUGE L\nF1 >> {:.3f}\nPrecision >> {:.3f}\nRecall >> {:.3f}'.format(score...
class UserDal(object): ALLOWED_ROLES = [u'owner', u'dev'] def __init__(self): pass def get_roles(): return {item.id: item.name_ch for item in Role.query.all()} def get_role_name(role_id): role = Role.query.get(role_id) if role: return role.name else: ...
class NegativeBaseEntryTestCase(unittest.TestCase): def setUpClass(cls): cls.entry = BaseEntry(**{'name': 'vw bully', 'value': (- 6000), 'date': '2000-01-01'}) def test_name(self): self.assertEqual(self.entry.name, 'vw bully') def test_value(self): self.assertEqual(self.entry.value, ...
() def _check_alazy_constant_ttl(): global constant_call_count constant_call_count = 0 _constant(ttl=100000) () def constant(): global constant_call_count constant_call_count += 1 return constant_call_count assert_eq(1, (yield constant.asynq())) assert_eq(1, (yield co...
(scope='module') def chat_join_request(bot, time): cjr = ChatJoinRequest(chat=TestChatJoinRequestBase.chat, from_user=TestChatJoinRequestBase.from_user, date=time, bio=TestChatJoinRequestBase.bio, invite_link=TestChatJoinRequestBase.invite_link, user_chat_id=TestChatJoinRequestBase.from_user.id) cjr.set_bot(bot...
.parametrize('progress, load_status, expected_visible', [(15, usertypes.LoadStatus.loading, True), (100, usertypes.LoadStatus.success, False), (100, usertypes.LoadStatus.error, False), (100, usertypes.LoadStatus.warn, False), (100, usertypes.LoadStatus.none, False)]) def test_tab_changed(fake_web_tab, progress_widget, ...
class SendContact(): async def send_contact(self: 'pyrogram.Client', chat_id: Union[(int, str)], phone_number: str, first_name: str, last_name: str=None, vcard: str=None, disable_notification: bool=None, reply_to_message_id: int=None, schedule_date: datetime=None, protect_content: bool=None, reply_markup: Union[('t...
def test_num_threads(): before = kvikio.defaults.get_num_threads() with kvikio.defaults.set_num_threads(3): assert (kvikio.defaults.get_num_threads() == 3) kvikio.defaults.num_threads_reset(4) assert (kvikio.defaults.get_num_threads() == 4) assert (before == kvikio.defaults.get_num_t...
def test_attn_label_convertor(): tmp_dir = tempfile.TemporaryDirectory() dict_file = osp.join(tmp_dir.name, 'fake_dict.txt') _create_dummy_dict_file(dict_file) with pytest.raises(NotImplementedError): AttnConvertor(5) with pytest.raises(AssertionError): AttnConvertor('DICT90', dict_f...
class LRUCacheDataset(BaseWrapperDataset): def __init__(self, dataset, token=None): super().__init__(dataset) _cache(maxsize=8) def __getitem__(self, index): return self.dataset[index] _cache(maxsize=8) def collater(self, samples): return self.dataset.collater(samples)
def test_accepts_none(msg): a = m.NoneTester() assert (m.no_none1(a) == 42) assert (m.no_none2(a) == 42) assert (m.no_none3(a) == 42) assert (m.no_none4(a) == 42) assert (m.no_none5(a) == 42) assert (m.ok_none1(a) == 42) assert (m.ok_none2(a) == 42) assert (m.ok_none3(a) == 42) a...
class RMSpropTFOptimizer(Optimizer): def __init__(self, params, lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon...
class VisaIOWarning(Warning): def __init__(self, error_code: int) -> None: (abbreviation, description) = completion_and_error_messages.get(error_code, ('?', 'Unknown code.')) super(VisaIOWarning, self).__init__(('%s (%d): %s' % (abbreviation, error_code, description))) self.error_code = erro...
.parametrize('schema', [{'required': ['\x00']}, {'properties': {'\x00': {'type': 'integer'}}}, {'dependencies': {'\x00': ['a']}}, {'dependencies': {'\x00': {'type': 'integer'}}}, {'required': ['y']}, {'properties': {'y': {'type': 'integer'}}}, {'dependencies': {'y': ['a']}}, {'dependencies': {'y': {'type': 'integer'}}}...
def make_dict_unstructure_fn(cl: type[T], converter: BaseConverter, _cattrs_omit_if_default: bool=False, _cattrs_use_linecache: bool=True, _cattrs_use_alias: bool=False, _cattrs_include_init_false: bool=False, **kwargs: AttributeOverride) -> Callable[([T], dict[(str, Any)])]: origin = get_origin(cl) attrs = ada...
class IRBuilderVisitor(IRVisitor): builder: IRBuilder def visit_mypy_file(self, mypyfile: MypyFile) -> None: assert False, 'use transform_mypy_file instead' def visit_class_def(self, cdef: ClassDef) -> None: transform_class_def(self.builder, cdef) def visit_import(self, node: Import) -> ...
def sync_states(states: Dict[(str, Dict[(str, Any)])], devices: Dict[(str, torch.device)], metrics_traversal_order: List[Tuple[(str, str)]], process_group: Optional[dist.ProcessGroup]=None, rank: Optional[int]=None) -> Optional[List[Dict[(str, Dict[(str, Any)])]]]: gathered_states = [_get_empty_metric_state_collect...
def main(argv): args = setup_args().parse_args(argv) if ((not args.show) and (not args.output)): raise ValueError('select output file destination or --show') scatters = [] for f in args.results_file: rv = parse_json_file(f, args.metric) scatters.append(rv) ylabel = f'{args.me...
class PermanentCheckBox(QtWidgets.QCheckBox): def enterEvent(self, e): if (self.window().showhelp is True): QtWidgets.QToolTip.showText(e.globalPos(), '<h3>Permanent Markers / Annotations</h3>If checked, the markers and annotations created with the Pick/Click callbacks will be permanent.(e.g. th...
def _create_pr_data_frame(evaluation_runs: List[EvaluationRun], methods: List[str]) -> DataFrame: data_frames = [] for (evaluation_run, name) in zip(evaluation_runs, methods): spotting_evaluation = evaluation_run.evaluation.spotting_evaluation pr_data_frame = spotting_evaluation.pr_data_frame ...