code
stringlengths
281
23.7M
def process_rule_tables(c, filenames, reporter): start_time = time.time() reporter.report('[Stage 3/7] Merging rule tables ...') create_rule_table(c) for (db_id, progress_str, filename) in enumerate_progress(filenames): with transaction(c): create_rule_map_table(c, db_id) wit...
def volume_weighted_average_price(prices_tms: PricesSeries, volumes_tms: QFSeries, interval: Timedelta) -> PricesSeries: assert prices_tms.index.equals(volumes_tms.index) last_date = prices_tms.index[(- 1)] beginning_of_window = prices_tms.index[0] end_of_window = (beginning_of_window + interval) we...
class TAM(nn.Module): def __init__(self, in_channels, n_segment, kernel_size=3, stride=1, padding=1): super(TAM, self).__init__() self.in_channels = in_channels self.n_segment = n_segment self.kernel_size = kernel_size self.stride = stride self.padding = padding ...
def _set_device(args): device_type = args['device'] gpus = [] for device in device_type: if (device_type == (- 1)): device = torch.device('cpu') else: device = torch.device('cuda:{}'.format(device)) gpus.append(device) args['device'] = gpus
class SawyerDisassembleV2Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'gripper': obs[3], 'wrench_pos': obs[4:7], 'peg_pos': obs[(- 3):], 'unused_info': obs[7:(- 3)]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos':...
class PrefetchDataLoader(DataLoader): def __init__(self, num_prefetch_queue, **kwargs): self.num_prefetch_queue = num_prefetch_queue super(PrefetchDataLoader, self).__init__(**kwargs) def __iter__(self): return PrefetchGenerator(super().__iter__(), self.num_prefetch_queue)
class _F0Gate(cirq.MatrixGate): def __init__(self): cirq.MatrixGate.__init__(self, np.array([[1, 0, 0, 0], [0, (- (2 ** (- 0.5))), (2 ** (- 0.5)), 0], [0, (2 ** (- 0.5)), (2 ** (- 0.5)), 0], [0, 0, 0, (- 1)]]), qid_shape=(2, 2)) def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq...
class TConfigCheckMenuItem(TestCase): def setUp(self): config.init() def tearDown(self): config.quit() def test_toggle(self): config.set('memory', 'bar', 'on') c = ConfigCheckMenuItem('dummy', 'memory', 'bar') c.set_active(True) self.assertTrue((config.getbool...
def _matmul_flop_jit(inputs: Tuple[torch.Tensor], outputs: Tuple[Any]) -> Number: input_shapes = [v.shape for v in inputs] assert (len(input_shapes) == 2), input_shapes assert (input_shapes[0][(- 1)] == input_shapes[1][(- 2)]), input_shapes flop = (inputs[0].numel() * input_shapes[(- 1)][(- 1)]) ret...
class MLP(): def __init__(self, env_spec, hidden_sizes=(64, 64), min_log_std=(- 3), init_log_std=0, seed=None, device=torch.device('cpu')): self.n = env_spec.observation_dim self.m = env_spec.action_dim self.min_log_std = min_log_std self.device = device if (seed is not None)...
_fixtures(WebFixture) def test_adding_chart_with_ajax(web_fixture): class MyForm(Form): def __init__(self, view): self.choice = 1 super().__init__(view, 'my_form') self.enable_refresh() self.use_layout(FormLayout()) self.layout.add_input(SelectInpu...
def _load_paradigms(filename): paradigms = [] with open(filename, 'rb') as f: paradigms_count = struct.unpack(str('<H'), f.read(2))[0] for x in range(paradigms_count): paradigm_len = struct.unpack(str('<H'), f.read(2))[0] para = array.array(str('H')) para.from...
def launch_experiments(variant_generator): variants = variant_generator.variants() for (i, variant) in enumerate(variants): tag = 'finetune__' print(variant['snapshot_filename']) tag += variant['snapshot_filename'].split('/')[(- 2)] tag += '____' tag += '__'.join([('%s_%s...
_transform('generic_image_transform') class GenericImageTransform(ClassyTransform): def __init__(self, transform: Optional[Callable]=None, split: Optional[str]=None): assert ((split is None) or (transform is None)), 'If split is not None then transform must be None' assert (split in [None, 'train', ...
class Binary(): file_path: Path fw_path: Path id: int = None lib_names: list[str] = field(default_factory=list) libs: list['Binary'] = field(default_factory=list) imported_symbols: list[str] = field(default_factory=list) imported_symbol_ids: list[int] = field(default_factory=list) non_re...
class SuperResDataset(BaseDataset): def __init__(self, opt, training): BaseDataset.__init__(self, opt, training) self.dir = opt.dir self.paths = file_utils.load_paths(self.dir) def generate(self, cache=True, shuffle_buffer_size=1000): dataset = tf.data.Dataset.from_tensor_slices(...
class SendCode(): async def send_code(self: 'pyrogram.Client', phone_number: str) -> 'types.SentCode': phone_number = phone_number.strip(' +') while True: try: r = (await self.invoke(raw.functions.auth.SendCode(phone_number=phone_number, api_id=self.api_id, api_hash=self....
def encode_content(content, nRows, nCols, actions_dict): encoded_content = np.zeros([nRows, nCols]) start = 0 s = 0 e = 0 for i in range(len(content)): if (content[i] != content[start]): frame_label = np.zeros(nCols) frame_label[actions_dict[content[start]]] = 1 ...
class Metric(object): def __init__(self): self.name = 'Metric' def compare_mse(self, x1, x2): err = np.sum(((x1 - x2) ** 2)) if (len(x1) == 4): err /= float((((x1.shape[0] * x1.shape[1]) * x1.shape[2]) * x1.shape[3])) else: err /= float(((x1.shape[0] * x1....
def load_backbone_pretrained(model, backbone): if ((cfg.PHASE == 'train') and cfg.TRAIN.BACKBONE_PRETRAINED and (not cfg.TRAIN.PRETRAINED_MODEL_PATH)): if os.path.isfile(cfg.TRAIN.BACKBONE_PRETRAINED_PATH): logging.info('Load backbone pretrained model from {}'.format(cfg.TRAIN.BACKBONE_PRETRAINE...
def test_get_build_requires_import(): expected = ['numpy >=1.16.0'] with cwd(osp.join(samples_dir, 'constructed_version')): assert (buildapi.get_requires_for_build_wheel() == expected) assert (buildapi.get_requires_for_build_editable() == expected) assert (buildapi.get_requires_for_build...
def main(): parser = HfArgumentParser(PyTorchBenchmarkArguments) try: benchmark_args = parser.parse_args_into_dataclasses()[0] except ValueError as e: arg_error_msg = 'Arg --no_{0} is no longer used, please use --no-{0} instead.' begin_error_msg = ' '.join(str(e).split(' ')[:(- 1)]) ...
def test_recovering_indices(tmpdir, bace_fragmented): for fragment in bace_fragmented.fragments: for pair in fragment.bond_indices: atom_indices = {a.atom_index for a in bace_fragmented.atoms if (a.map_index in pair)} assert (len(atom_indices) == 2) assert any((({b.atom1_...
(frozen=True, slots=True) class SystemClock(Clock): offset: float = attr.ib(factory=(lambda : _r.uniform(10000, 200000))) def start_clock(self) -> None: pass def current_time(self) -> float: return (self.offset + perf_counter()) def deadline_to_sleep_time(self, deadline: float) -> float:...
(scope='module') def inline_query_result_cached_photo(): return InlineQueryResultCachedPhoto(TestInlineQueryResultCachedPhotoBase.id_, TestInlineQueryResultCachedPhotoBase.photo_file_id, title=TestInlineQueryResultCachedPhotoBase.title, description=TestInlineQueryResultCachedPhotoBase.description, caption=TestInlin...
def benchmark(min_size=min(SIZES), max_size=max(SIZES), step_size=STEP, stars=STARS, noise=NOISE, seed=None, repeats=REPEATS, n_jobs=(- 1), comb_number=COMB_NUMBER): grid = get_parameters(min_size=min_size, max_size=max_size, step_size=step_size, repeats=repeats, stars=stars, noise=noise, seed=seed, comb_number=com...
class PluginsList(ListView): model = Plugin queryset = Plugin.approved_objects.all() title = _('All plugins') additional_context = {} paginate_by = settings.PAGINATION_DEFAULT_PAGINATION def get_paginate_by(self, queryset): try: paginate_by = int(self.request.GET.get('per_pag...
class BddQuantifierEliminator(QuantifierEliminator): LOGICS = [pysmt.logics.BOOL] def __init__(self, environment, logic=None): QuantifierEliminator.__init__(self) self.environment = environment self.logic = logic self.ddmanager = repycudd.DdManager() self.converter = BddC...
def augment_triplet_from_asins(triplets: List[Tuple[(str, str, str)]], docs: List[List[str]], sample_per_asin=3): negative_profile = defaultdict(list) for doc in docs: if (((len(doc) * (len(doc) - 1)) / 2) < sample_per_asin): continue pairs = utils.Rnd.random_pairs(doc, sample_per_as...
class Maker(AttributeDevice): _state_property = 'switch_state' _attributes: _Attributes def _required_services(self) -> list[RequiredService]: return (super()._required_services + [RequiredService(name='basicevent', actions=['SetBinaryState'])]) def set_state(self, state: int) -> None: s...
def test_while_exec_iteration_stop_evals_false(): wd = WhileDecorator({'stop': '{stop}'}) context = Context({'stop': False}) mock = MagicMock() assert (not wd.exec_iteration(2, context, mock)) assert (context['whileCounter'] == 2) assert (wd.while_counter == 2) assert (len(context) == 2) ...
.all_locales def test_smoke_numbers(locale): locale = Locale.parse(locale) for number in NUMBERS: assert numbers.format_decimal(number, locale=locale) assert numbers.format_decimal(number, locale=locale, numbering_system='default') assert numbers.format_currency(number, 'EUR', locale=loc...
def continue2discrete_coordY(y): if (y < 150): return 100.0 elif (y < 260): return 205.0 elif (y < 370): return 315.0 elif (y < 480): return 425.0 elif (y < 590): return 535.0 elif (y < 700): return 645.0 elif (y < 810): return 755.0 ...
class InceptionI3d(nn.Module): VALID_ENDPOINTS = ('Conv3d_1a_7x7', 'MaxPool3d_2a_3x3', 'Conv3d_2b_1x1', 'Conv3d_2c_3x3', 'MaxPool3d_3a_3x3', 'Mixed_3b', 'Mixed_3c', 'MaxPool3d_4a_3x3', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_4f', 'MaxPool3d_5a_2x2', 'Mixed_5b', 'Mixed_5c', 'Logits', 'Predictions') ...
() ('-n', '--nsteps', default=(- 1), help='number of steps to process. use -1 to for no limit (will run workflow to completion)') ('--track/--no-track', default=False) ('-u', '--update-interval', default=1) ('-g', '--strategy', help='set execution stragegy') ('-y', '--strategyopt', help='strategy option', multiple=True...
def read_tb(path): import pandas import numpy as np from glob import glob from collections import defaultdict import tensorflow as tf if osp.isdir(path): fnames = glob(osp.join(path, 'events.*')) elif osp.basename(path).startswith('events.'): fnames = [path] else: ...
def save_file(data, filename): logging.info(f'Saving data to file: {filename}') file_ext = os.path.splitext(filename)[1] if (file_ext in ['.pkl', '.pickle']): with PathManager.open(filename, 'wb') as fopen: pickle.dump(data, fopen, pickle.HIGHEST_PROTOCOL) elif (file_ext == '.npy'): ...
class BSDMountPoint(MountPoint): def _iter_mountpoints(cls): check_output = cls(None).check_output for line in check_output('mount -p').splitlines(): splitted = line.split() (yield {'path': splitted[1], 'device': splitted[0], 'filesystem': splitted[2], 'options': splitted[3]....
class Records(Base): def _backfill_fields(self, fields: Optional[List[str]], forms: Optional[List[str]]): if (forms and (not fields)): return ([f'{form}_complete' for form in forms] + [self.def_field]) if (fields and (self.def_field not in fields)): return (fields + [self.def...
def _populate_kernel_cache(np_type, k_type): if (np_type not in _SUPPORTED_TYPES): raise ValueError("Datatype {} not found for '{}'".format(np_type, k_type)) if ((str(np_type), k_type) in _cupy_kernel_cache): return _cupy_kernel_cache[(str(np_type), k_type)] = _get_function('/peak_finding/_p...
class AsType(InDataMutatingTransform): def __init__(self, indices, dtypes): assert (len(indices) == len(dtypes)) self._indices = indices self._dtypes = dtypes def transform(self, in_data): for (index, dtype) in zip(self._indices, self._dtypes): in_data[index] = in_dat...
('os.execvpe', new=execvpe_mock) def test_run_script_by_absolute_name(caplog, pipx_temp_env, tmp_path): script = (tmp_path / 'test.py') out = (tmp_path / 'output.txt') test_str = 'Hello, world!' script.write_text(textwrap.dedent(f''' from pathlib import Path Path({repr(st...
def check_for_ccdc_structures(cid): url0 = ' cid = str(cid) url = ((url0 + cid) + '/JSON') csd_codes = [] try: response = urllib.request.urlopen(url) data = json.loads(response.read()) if (len(data['Record']['Section'][0]['Section']) == 3): infos = data['Record'][...
def load_file(filename, onehot=True): ID1 = [] ID2 = [] D1 = [] D2 = [] L = [] with open(filename, 'r', encoding='utf-8') as read: for (i, line) in enumerate(read): if (not (len(line.split('\t')) == 5)): print(line.split('\t')) (id1, id2, d1, d2, l...
def test_reading_and_writing_repository(): repository_state_dir = temp_dir() (PackageIndex) class RepositoryStub(): def unique_id(self): return 'myid' def transfer(self, package): pass repository_state_directory = repository_state_dir.name repository = Rep...
class BatchedFusedEmbedding(BaseBatchedEmbedding[torch.Tensor], FusedOptimizerModule): def __init__(self, config: GroupedEmbeddingConfig, pg: Optional[dist.ProcessGroup]=None, device: Optional[torch.device]=None) -> None: super().__init__(config, pg, device) managed: List[EmbeddingLocation] = [] ...
.parametrize('text, expected', [('foo|bar', 'fo|bar'), ('foobar|', 'fooba|'), ('|foobar', '|foobar'), ('f<oo>bar', 'f|bar')]) def test_rl_backward_delete_char(text, expected, lineedit): lineedit.set_aug_text(text) readlinecommands.rl_backward_delete_char() assert (lineedit.aug_text() == expected)
def test_reveal(hatch, config_file, helpers, default_cache_dir, default_data_dir): config_file.model.project = 'foo' config_file.model.publish['index']['auth'] = 'bar' config_file.save() result = hatch('config', 'show', '-a') default_cache_directory = str(default_cache_dir).replace('\\', '\\\\') ...
class AlreadyBuiltWheelError(Exception): def __init__(self, wheel_name: str) -> None: message = textwrap.dedent(f''' cibuildwheel: Build failed because a wheel named {wheel_name} was already generated in the current run. If you expected another wheel to be generated, check your proje...
def decode_spans(start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray) -> Tuple: if (start.ndim == 1): start = start[None] if (end.ndim == 1): end = end[None] outer = np.matmul(np.expand_dims(start, (- 1)), np.expand_dims(end, 1)) candidates = ...
def test_connection_list_tables(): with patch(PATCH_METHOD) as req: req.return_value = LIST_TABLE_DATA conn = Connection(REGION) conn.list_tables(exclusive_start_table_name='Thread') assert (req.call_args[0][1] == {'ExclusiveStartTableName': 'Thread'}) with patch(PATCH_METHOD) as...
class Bottleneck(nn.Module): def __init__(self, in_channels, bottleneck_channels, out_channels, num_groups, stride_in_1x1, stride, dilation, norm_func=BatchNorm2d, dcn_config={}): super(Bottleneck, self).__init__() self.downsample = None if (in_channels != out_channels): down_str...
class MaxPool3x3Conv1x1(BaseOp): def build(self, inputs, channels): with tf.variable_scope('MaxPool3x3-Conv1x1'): net = tf.layers.max_pooling2d(inputs=inputs, pool_size=(3, 3), strides=(1, 1), padding='same', data_format=self.data_format) net = conv_bn_relu(net, 1, channels, self.is_...
def initialize_model(train, input_vocab, output_vocab, max_len=10, hidden_size=256, dropout_p=0.5, bidirectional=True, n_beam=5): encoder = EncoderRNN(len(input_vocab), max_len, hidden_size, bidirectional=bidirectional, variable_lengths=True) decoder = DecoderRNN(len(output_vocab), max_len, (hidden_size * (2 if...
def validate_list_of_str(name, data): if (name in data): if (not isinstance(data[name], list)): raise DistutilsSetupError(('"%s" should be a list' % name)) elif (not all([isinstance(i, str) for i in data[name]])): raise DistutilsSetupError(('"%s" should be a list of strings' ...
def test_unused_udp_port_factory_duplicate(unused_udp_port_factory, monkeypatch): counter = 0 def mock_unused_udp_port(_ignored): nonlocal counter counter += 1 if (counter < 5): return 10000 else: return (10000 + counter) monkeypatch.setattr(pytest_asy...
_funcify.register(ptr.BernoulliRV) def numba_funcify_BernoulliRV(op, node, **kwargs): out_dtype = node.outputs[1].type.numpy_dtype def body_fn(a): return f''' if {a} < np.random.uniform(0, 1): return direct_cast(0, out_dtype) else: return direct_cast(1, out_dtype) ''' ...
def show_result_pyplot(model, img, result, score_thr=0.3, title='result', wait_time=0): if hasattr(model, 'module'): model = model.module model.show_result(img, result, score_thr=score_thr, show=True, wait_time=wait_time, win_name=title, bbox_color=(72, 101, 241), text_color=(72, 101, 241))
def _fuzzy_contiguity(geoms, ids, tolerance=None, buffer=None, predicate='intersects'): if ((buffer is not None) and (tolerance is not None)): raise ValueError('Only one of `tolerance` and `buffer` can be speciifed, not both.') if (not isinstance(geoms, geopandas.base.GeoPandasBase)): geoms = ge...
def test_etuples(): x_pt = pt.vector('x') y_pt = pt.vector('y') z_pt = etuple(x_pt, y_pt) res = apply(pt.add, z_pt) assert (res.owner.op == pt.add) assert (res.owner.inputs == [x_pt, y_pt]) w_pt = etuple(pt.add, x_pt, y_pt) res = w_pt.evaled_obj assert (res.owner.op == pt.add) as...
def test_central_subprocess(testdir): scripts = testdir.makepyfile(parent_script=SCRIPT_PARENT, child_script=SCRIPT_CHILD) parent_script = scripts.dirpath().join('parent_script.py') result = testdir.runpytest('-v', f'--cov={scripts.dirpath()}', '--cov-report=term-missing', parent_script) result.stdout.f...
def test_cast_tensor_type(): inputs = torch.FloatTensor([5.0]) src_type = torch.float32 dst_type = torch.int32 outputs = cast_tensor_type(inputs, src_type, dst_type) assert isinstance(outputs, torch.Tensor) assert (outputs.dtype == dst_type) inputs = 'tensor' src_type = str dst_type ...
(qseis.have_backend(), 'backend qseis not available') class GFQSeisTestCase(unittest.TestCase): tempdirs = [] def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) def tearDownClass(cls): for d in cls.tempdirs: shutil.rmtree(d) def test_pyrock...
class DepthwiseSeparableConv(nn.Module): def __init__(self, in_ch, out_ch, stride=1, kernel_size=3, bias=False): super().__init__() if isinstance(kernel_size, list): padding = [(i // 2) for i in kernel_size] else: padding = (kernel_size // 2) self.depthwise = ...
def language_eval(dataset, preds, model_id, split): import sys sys.path.append('coco-caption') annFile = 'coco-caption/annotations/captions_val2014.json' from pycocotools.coco import COCO from pycocoevalcap.eval import COCOEvalCap if (not os.path.isdir('eval_results')): os.mkdir('eval_re...
def batched(iterable, n): if (hexversion >= ): warnings.warn('batched will be removed in a future version of more-itertools. Use the standard library itertools.batched function instead', DeprecationWarning) it = iter(iterable) while True: batch = list(islice(it, n)) if (not batch): ...
.parametrize('replace_missing_translation', boolean_toggle) .parametrize('test_language', test_languages) def test_translationmixin_trans_empty_field(settings, replace_missing_translation, test_language): settings.REPLACE_MISSING_TRANSLATION = replace_missing_translation empty_lang = 'en' settings.LANGUAGE_...
def _get_abc_helper(view_vector, sat_pos, ellipsoid): flat2 = ((1 - ellipsoid.flattening) ** 2) (ux, uy, uz) = (view_vector.x, view_vector.y, view_vector.z) (x, y, z) = (sat_pos.x, sat_pos.y, sat_pos.z) a = ((flat2 * ((ux ** 2) + (uy ** 2))) + (uz ** 2)) b = ((flat2 * ((x * ux) + (y * uy))) + (z * u...
def test_unionize_dataframe_categories(uniontest_df1, uniontest_df2, uniontest_df3): (udf1, udf2, udf3) = janitor.unionize_dataframe_categories(uniontest_df1, uniontest_df2, uniontest_df3) assert (set(udf1['jerbs'].dtype.categories) == set(udf2['jerbs'].dtype.categories)) assert (set(udf1['jerbs'].dtype.cat...
(integers(min_value=0, max_value=100), integers(min_value=0, max_value=10000), integers(min_value=0, max_value=50000), integers(min_value=1, max_value=), integers(min_value=1, max_value=), integers(min_value=1, max_value=)) (suppress_health_check=[HealthCheck.filter_too_much]) def test_fee_round_trip(flat_fee, prop_fee...
class DummyDataset(FairseqDataset): def __init__(self, batch, num_items, item_size): super().__init__() self.batch = batch self.num_items = num_items self.item_size = item_size def __getitem__(self, index): return index def __len__(self): return self.num_items...
class VocabWithLock(VocabBase): def __init__(self, words=(), lock=None): self.lock = lock super().__init__(words) def word2index(self, word, train=False): if isinstance(word, (list, tuple)): return [self.word2index(w, train=train) for w in word] with self.lock: ...
class BlocksEndpoint(Endpoint): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.children = BlocksChildrenEndpoint(*args, **kwargs) def retrieve(self, block_id: str, **kwargs: Any) -> SyncAsync[Any]: return self.parent.request(path=f'blocks/{b...
def ql_syscall_dup(ql: Qiling, oldfd: int): f = get_opened_fd(ql.os, oldfd) if (f is None): return (- 1) newfd = next((i for i in range(NR_OPEN) if (ql.os.fd[i] is None)), (- 1)) if (newfd == (- 1)): return (- EMFILE) ql.os.fd[newfd] = f.dup() ql.log.debug(f'dup({oldfd:d}) = {new...
def rtn_fopen(se: 'SymbolicExecutor', pstate: 'ProcessState'): logger.debug('fopen hooked') arg0 = pstate.get_argument_value(0) arg1 = pstate.get_argument_value(1) arg0s = pstate.memory.read_string(arg0) arg1s = pstate.memory.read_string(arg1) pstate.concretize_memory_bytes(arg0, (len(arg0s) + 1...
class SetDataset(): def __init__(self, data_file, batch_size, transform): with open(data_file, 'r') as f: self.meta = json.load(f) self.cl_list = np.unique(self.meta['image_labels']).tolist() self.sub_meta = {} for cl in self.cl_list: self.sub_meta[cl] = [] ...
_fixtures(WebFixture, MaxNumberOfFilesFileUploadInputFixture) def test_async_number_files_validation(web_fixture, max_number_of_files_file_upload_input_fixture): fixture = max_number_of_files_file_upload_input_fixture web_fixture.reahl_server.set_app(fixture.new_wsgi_app(enable_js=True)) browser = web_fixtu...
class KFACOptimizer(optim.Optimizer): def __init__(self, model, lr=0.25, momentum=0.9, stat_decay=0.99, kl_clip=0.001, damping=0.01, weight_decay=0, fast_cnn=False, Ts=1, Tf=10): defaults = dict() def split_bias(module): for (mname, child) in module.named_children(): if (...
def test_connect_wr_x_conn_As_wr_y_conn_At_disjoint(): class Top(ComponentLevel3): def construct(s): s.x = Wire(Bits24) s.A = Wire(Bits32) s.y = Wire(Bits4) connect(s.A[8:32], s.x) connect(s.A[0:4], s.y) def up_wr_x(): s...
class ElfPatcher(): def replace_needed(self, file_name: str, *old_new_pairs: tuple[(str, str)]) -> None: raise NotImplementedError def set_soname(self, file_name: str, new_so_name: str) -> None: raise NotImplementedError def set_rpath(self, file_name: str, rpath: str) -> None: raise ...
def test_options_1(tmp_path, monkeypatch): with tmp_path.joinpath('pyproject.toml').open('w') as f: f.write(PYPROJECT_1) args = CommandLineArguments.defaults() args.package_dir = tmp_path monkeypatch.setattr(platform_module, 'machine', (lambda : 'x86_64')) options = Options(platform='linux',...
def _dist_train(model, dataset, cfg, validate=False, logger=None): data_loaders = [build_dataloader(dataset, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, dist=True)] model = MMDistributedDataParallel(model.cuda()) optimizer = build_optimizer(model, cfg.optimizer) runner = EpochBasedRunner(model, bat...
def inference(model_save_path, clip): with tf.Session() as sess: meta_graph_def = tf.saved_model.loader.load(sess, [MODEL_NAME], model_save_path) signature = meta_graph_def.signature_def bn_tensor_name = signature[SIGNATURE_KEY].inputs[BATCH_NORM_KEY].name x_tensor_name = signature[S...
class F19_TestCase(FC3_TestCase): def runTest(self): self.assert_parse('lang en_US') self.assert_parse('lang en_US --addsupport=cs_CZ', 'lang en_US --addsupport=cs_CZ\n') self.assert_parse('lang en_US --addsupport=sr_RS.UTF-', 'lang en_US --addsupport=sr_RS.UTF-\n') self.assert_parse...
def install_pyqt_binary(venv_dir: pathlib.Path, version: str) -> None: utils.print_title('Installing PyQt from binary') utils.print_col('No proprietary codec support will be available in qutebrowser.', 'bold') if _is_qt6_version(version): supported_archs = {'linux': {'x86_64'}, 'win32': {'AMD64'}, '...
def file_info_from_modpath(modpath: list[str], path: (Sequence[str] | None)=None, context_file: (str | None)=None) -> spec.ModuleSpec: if (context_file is not None): context: (str | None) = os.path.dirname(context_file) else: context = context_file if (modpath[0] == 'xml'): try: ...
class LenPredicate(): expected_length: int has_star: bool ctx: CanAssignContext def __call__(self, value: Value, positive: bool) -> Optional[Value]: value_len = len_of_value(value) if (isinstance(value_len, KnownValue) and isinstance(value_len.val, int)): if self.has_star: ...
def test_do_export_broken_internal_copy(tmp_path: Path): patch_data = {'menu_mod': False} export_params = EchoesGameExportParams(input_path=None, output_path=MagicMock(), contents_files_path=tmp_path.joinpath('contents'), asset_cache_path=tmp_path.joinpath('asset_cache_path'), backup_files_path=tmp_path.joinpat...
def gen_evaluation_file(semantic_mask, instance_mask, confidence_array, instance_mask_path, txt_path, file_name, additive=False, slide_semantic=False, mask_label=None, mask_idx=0, result_path=None): assert result_path, 'result_path must be specified' result_path = (result_path + '/') _ids = np.array(['0', '...
class EventChannel(RemoteMethod): def __init__(self, form, controller, name): super().__init__(form.view, name, self.delegate_event, None, idempotent=False, immutable=False, disable_csrf_check=True) self.controller = controller self.form = form def make_result(self, input_values): ...
def euler2mat(z=0, y=0, x=0): Ms = [] if z: cosz = math.cos(z) sinz = math.sin(z) Ms.append(np.array([[cosz, (- sinz), 0], [sinz, cosz, 0], [0, 0, 1]])) if y: cosy = math.cos(y) siny = math.sin(y) Ms.append(np.array([[cosy, 0, siny], [0, 1, 0], [(- siny), 0, c...
class DIAPreResNet(nn.Module): def __init__(self, channels, init_block_channels, bottleneck, conv1_stride, in_channels=3, in_size=(224, 224), num_classes=1000): super(DIAPreResNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() ...
def random_pad_clip_list(x, num): x = deepcopy(list(x)) if (len(x) > num): shuffle(x) return x[:num] else: ret = [] for i in range((num // len(x))): shuffle(x) ret = (ret + x) ret = (ret + x[:(num - len(ret))]) return ret
class Migration(migrations.Migration): dependencies = [('projects', '0051_alter_value_value_type')] operations = [migrations.AlterField(model_name='invite', name='email', field=models.EmailField(blank=True, help_text='The e-mail for this membership.', max_length=254, verbose_name='E-mail')), migrations.AlterFie...
class AstroidManagerBrain(TypedDict): astroid_cache: dict[(str, nodes.Module)] _mod_file_cache: dict[(tuple[(str, (str | None))], (spec.ModuleSpec | exceptions.AstroidImportError))] _failed_import_hooks: list[Callable[([str], nodes.Module)]] always_load_extensions: bool optimize_ast: bool max_in...
.parametrize('regimes', [['n', 'n', 's', 's', 'e', 'e', 'w', 'w', 'e', 'j'], [0, 0, 2, 2, 3, 3, 4, 4, 3, 1]]) def test_block_contiguity(regimes): neighbors = _block_contiguity(regimes) wn = {0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5], 9: []} assert ({f: n.tolist() for (f...
class Stats(object): def __init__(self, tracker: 'Optional[ClassTracker]'=None, filename: Optional[str]=None, stream: Optional[IO]=None): if stream: self.stream = stream else: self.stream = sys.stdout self.tracker = tracker self.index = {} self.snapsho...
class CanvasConfig(Config): def __init__(self, canvas, base_config): self.canvas = canvas self.major_version = base_config.major_version self.minor_version = base_config.minor_version self.forward_compatible = base_config.forward_compatible self.opengl_api = (base_config.open...
def get_model(name, **kwargs): models = {'fcn_resnet50_pcontext': get_fcn_resnet50_pcontext, 'encnet_resnet50_pcontext': get_encnet_resnet50_pcontext, 'encnet_resnet101_pcontext': get_encnet_resnet101_pcontext, 'encnet_resnet50_ade': get_encnet_resnet50_ade, 'encnet_resnet101_ade': get_encnet_resnet101_ade, 'fcn_re...
def parse_permissions(session=flask.session): perms = {x.name: False for x in Perms} perms['ADMIN'] = False perms['is_admin'] = False if (not session.get('authenticated', False)): return perms perms['ANY'] = True if (session.get('role') == Role.ADMIN): for key in perms.keys(): ...