code
stringlengths
281
23.7M
def eval_para(model, iterator, sent_ids, output_path): model.eval() (Words, Is_heads, Tags, Y, Y_hat) = ([], [], [], [], []) with torch.no_grad(): for (i, batch) in enumerate(tqdm(iterator)): (words, x, is_heads, tags, y, seqlens) = batch (_, _, y_hat) = model(x, y) ...
class MDense(Layer): def __init__(self, outputs, channels=2, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): if (('input_shape' n...
.parametrize('q', [quantize(symmetric=True, initialized=True), quantize(symmetric=False, initialized=True), quantize_dequantize(symmetric=True, initialized=True), quantize_dequantize(symmetric=False, initialized=True)]) def test_backward(q: _QuantizerBase, x: torch.Tensor): output = q(x) output.backward(torch.z...
def box(text): lines = text.split('\n') w = width(lines) top_bar = ((TOP_LEFT_CORNER + (HORIZONTAL_BAR * (2 + w))) + TOP_RIGHT_CORNER) bottom_bar = ((BOTTOM_LEFT_CORNER + (HORIZONTAL_BAR * (2 + w))) + BOTTOM_RIGHT_CORNER) lines = [LINES_FORMAT_STR.format(line=line, width=w) for line in lines] re...
def lookup_connections(backend, identities): from rapidsms.models import Backend if isinstance(backend, str): (backend, _) = Backend.objects.get_or_create(name=backend) connections = [] for identity in identities: (connection, _) = backend.connection_set.get_or_create(identity=identity) ...
def evaluate_extractive(result_file, article_file, summary_file, entity_map_file=None, out_rouge_file=None, cmd='-a -c 95 -m -n 4 -w 1.2', length=(- 1), eval_type='lead', topk=3, rerank=False, with_m=False, add_full_stop=True, nsent_budget_file=None, nword_budget_file=None, multi_ref=False, trigram_block=False): ar...
def remove_silence(silence_parts_list: list[tuple[(float, float)]], transcribed_data: list[TranscribedData]): new_transcribed_data = [] for data in transcribed_data: new_transcribed_data.append(data) origin_end = data.end was_split = False for (silence_start, silence_end) in sile...
def text(session, *args, **kwargs): txt = (args[0] if args else None) if (txt is None): return if (txt.strip() in _IDLE_COMMAND): session.update_session_counters(idle=True) return if session.account: puppet = session.puppet if puppet: txt = puppet.nick...
def test_format_failure_ignore_multidoc(run_line_simple, tmp_path): schemafile = (tmp_path / 'schema.json') schemafile.write_text(json.dumps(FORMAT_SCHEMA)) doc1 = (tmp_path / 'doc1.json') doc1.write_text(json.dumps(FAILING_DOCUMENT)) doc2 = (tmp_path / 'doc2.json') doc2.write_text(json.dumps(PA...
class BufferedOutput(Output): def __init__(self, verbosity: Verbosity=Verbosity.NORMAL, decorated: bool=False, formatter: (Formatter | None)=None, supports_utf8: bool=True) -> None: super().__init__(decorated=decorated, verbosity=verbosity, formatter=formatter) self._buffer = StringIO() self...
def deep_dgl_graph_copy(graph: DGLGraph): start = time() copy_graph = DGLGraph() copy_graph.add_nodes(graph.number_of_nodes()) graph_edges = graph.edges() copy_graph.add_edges(graph_edges[0], graph_edges[1]) for (key, value) in graph.edata.items(): copy_graph.edata[key] = value for (...
def _save_item_model(request, item: Item, form, change) -> None: prev_status = False if (not item.pk): item.user = request.user if (not item.issue): la = lna = False qs = Issue.objects try: la = qs.filter(status='active').order_by('-pk')[0:1].g...
def drop_channels(edf_source, edf_target=None, to_keep=None, to_drop=None): (signals, signal_headers, header) = hl.read_edf(edf_source, ch_nrs=to_keep, digital=False) clean_file = {} for (signal, header) in zip(signals, signal_headers): channel = header.get('label') if (channel in clean_file...
.parametrize('configuration, expected_value', [((0.0, 0.0, 1.0, 50.0, 100.0), 50.0), ((1.0, 0.0, 1.0, 50.0, 100.0), 100.0), ((0.5, 0.0, 1.0, 50.0, 100.0), 75.0), ((0.0, 0.5, 1.0, 50.0, 100.0), 50.0), ((0.75, 0.5, 1.0, 50.0, 100.0), 75.0)]) def test_interpolation(configuration, expected_value): (current_position, lo...
def test_features_for(): vuln_report_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vulnerabilityreport.json') security_info_filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'securityinformation.json') with open(vuln_report_filename) as vuln_report_file: vuln...
class MLP(torch.nn.Module): def __init__(self, config): super(MLP, self).__init__() self.config = config self.num_users = config['num_users'] self.num_items = config['num_items'] self.latent_dim = config['latent_dim'] self.embedding_user = torch.nn.Embedding(num_embed...
class TestSequenceImpl(TestNameCheckVisitorBase): _passes() def test(self): from typing import Sequence from typing_extensions import Literal def capybara(x, ints: Sequence[Literal[(1, 2)]]): assert_is_value(set(), KnownValue(set())) assert_is_value(list(), KnownV...
class JsonConverter(Converter): def dumps(self, obj: Any, unstructure_as: Any=None, **kwargs: Any) -> str: return dumps(self.unstructure(obj, unstructure_as=unstructure_as), **kwargs) def loads(self, data: Union[(bytes, str)], cl: Type[T], **kwargs: Any) -> T: return self.structure(loads(data, *...
class ModelData(): def __init__(self, model: ModelProto): self.model = model self.module_to_info = {} self._populate_model_data() def _populate_model_data(self): cg = ConnectedGraph(self.model) for op in cg.ordered_ops: self.module_to_info[op.name] = ModuleInf...
class DescribeCT_Row(): def it_can_add_a_trPr(self, add_trPr_fixture): (tr, expected_xml) = add_trPr_fixture tr._add_trPr() assert (tr.xml == expected_xml) def it_raises_on_tc_at_grid_col(self, tc_raise_fixture): (tr, idx) = tc_raise_fixture with pytest.raises(ValueError)...
def train_model(max_epochs): model = Model(20) optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=0.0001) def step(engine, batch): model.train() optimizer.zero_grad() (x, y) = batch y_pred = model(x) loss = F.nll_loss(y_pred, y) ...
class TestPerTestCapturing(): def test_capture_and_fixtures(self, pytester: Pytester) -> None: p = pytester.makepyfile('\n def setup_module(mod):\n print("setup module")\n def setup_function(function):\n print("setup " + function.__name__)\n def...
class Checkpoint(object): CHECKPOINT_DIR_NAME = 'checkpoints' TRAINER_STATE_NAME = 'trainer_states.pt' MODEL_NAME = 'model.pt' INPUT_VOCAB_FILE = 'input_vocab.pt' OUTPUT_VOCAB_FILE = 'output_vocab.pt' def __init__(self, model, optimizer, epoch, step, input_vocab, output_vocab, path=None): ...
class ServoFlags(Value): SYNC = 1 OVERTEMP_FAULT = 2 OVERCURRENT_FAULT = 4 ENGAGED = 8 INVALID = (16 * 1) PORT_PIN_FAULT = (16 * 2) STARBOARD_PIN_FAULT = (16 * 4) BADVOLTAGE_FAULT = (16 * 8) MIN_RUDDER_FAULT = (256 * 1) MAX_RUDDER_FAULT = (256 * 2) CURRENT_RANGE = (256 * 4) ...
def _create_app(emails=True): global _PORT_NUMBER _PORT_NUMBER = (_PORT_NUMBER + 1) (public_key, private_key_data) = _generate_certs() users = [{'name': 'cool.user', 'email': '', 'password': 'password'}, {'name': 'some.neat.user', 'email': '', 'password': 'foobar'}, {'name': 'blacklistedcom', 'email': '...
class IterativeRefinementGenerator(nn.Module): def __init__(self, models, tgt_dict, eos_penalty=0.0, max_iter=2, max_ratio=2, decoding_format=None, retain_dropout=False, adaptive=True): super().__init__() self.models = models self.bos = tgt_dict.bos() self.pad = tgt_dict.pad() ...
('pypyr.config.config.init') def test_main_pass_with_sysargv_single_group(mock_config_init): arg_list = ['pypyr', 'blah', 'ctx string', '--loglevel', '50', '--dir', 'dir here', '--groups', 'group1', '--success', 'sg', '--failure', 'f g'] with patch('sys.argv', arg_list): with patch('pypyr.pipelinerunner...
class ResourceAllocation(Predictor): def predict(self, weight=None): res = Scoresheet() for (a, b) in self.likely_pairs(): intersection = (set(neighbourhood(self.G, a)) & set(neighbourhood(self.G, b))) w = 0 for c in intersection: if (weight is not...
.parametrize(['constraint', 'expected'], [('*', ['19.10b0']), ('>=19.0a0', ['19.10b0']), ('>=20.0a0', []), ('>=21.11b0', []), ('==21.11b0', ['21.11b0'])]) def test_find_packages_yanked(constraint: str, expected: list[str]) -> None: repo = MockRepository() packages = repo.find_packages(Factory.create_dependency(...
(name='fake_dataset') def fixture_fake_dataset(): count_ir = da.linspace(0, 255, 4, dtype=np.uint8).reshape(2, 2) count_wv = da.linspace(0, 255, 4, dtype=np.uint8).reshape(2, 2) count_vis = da.linspace(0, 255, 16, dtype=np.uint8).reshape(4, 4) sza = da.from_array(np.array([[45, 90], [0, 45]], dtype=np.f...
def get_num_processes(): cpu_count = multiprocessing.cpu_count() if (config.NUMBER_OF_CORES == 0): raise ValueError('Invalid NUMBER_OF_CORES; value may not be 0.') if (config.NUMBER_OF_CORES > cpu_count): log.info('Requesting %s cores; only %s available', config.NUMBER_OF_CORES, cpu_count) ...
def test_item(func: Callable[(..., bool)], description: str) -> Parser: def test_item_parser(stream, index): if (index < len(stream)): if isinstance(stream, bytes): item = stream[index:(index + 1)] else: item = stream[index] if func(item): ...
def read_plane_paramters_file(filepath): file = open(filepath, 'r') lines = file.readlines() planes = [] for line in lines: if (not line.startswith('#')): paras = line.split() plane = {'index': int(paras[0]), 'num_of_points': int(paras[1]), 'ratio': (float(paras[1]) / (64...
class Solution(object): def mergeTwoLists(self, l1, l2): pos = dummyHead = ListNode((- 1)) while ((l1 is not None) and (l2 is not None)): if (l1.val <= l2.val): pos.next = l1 l1 = l1.next else: pos.next = l2 l2 =...
class BatchScoringFunction(ScoringFunction): def __init__(self, score_modifier: ScoreModifier=None) -> None: super().__init__(score_modifier=score_modifier) def score(self, smiles: str) -> float: return self.score_list([smiles])[0] def score_list(self, smiles_list: List[str]) -> List[float]:...
class MarioNet(nn.Module): def __init__(self, input_dim, output_dim): super().__init__() (c, h, w) = input_dim if (h != 84): raise ValueError(f'Expecting input height: 84, got: {h}') if (w != 84): raise ValueError(f'Expecting input width: 84, got: {w}') ...
def tabulate_events(dpath): summary_iterators = [EventAccumulator(os.path.join(dpath, dname)).Reload() for dname in os.listdir(dpath)] tags = summary_iterators[0].Tags()['scalars'] for it in summary_iterators: assert (it.Tags()['scalars'] == tags) out = defaultdict(list) steps = [] for t...
def in_ring(pt: Tuple[(float, float)], ring: List[Tuple[(float, float)]], ignore_boundary: bool) -> bool: is_inside = False if ((ring[0][0] == ring[(len(ring) - 1)][0]) and (ring[0][1] == ring[(len(ring) - 1)][1])): ring = ring[0:(len(ring) - 1)] j = (len(ring) - 1) for i in range(0, len(ring)):...
def process_split_fully(train_ratio=0.8): if (not os.path.exists(os.path.join(config.save_dir, 'split_txts'))): os.makedirs(os.path.join(config.save_dir, 'split_txts')) for tag in ['Tr']: img_ids = [] for path in tqdm(glob.glob(os.path.join(base_dir, f'images{tag}', '*.nii.gz'))): ...
class TestSolver(unittest.TestCase): def setUp(self): self.num_output = 13 net_f = simple_net_file(self.num_output) f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write((("net: '" + net_f) + "'\n test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9\n ...
def get_min_dcf(Pfa, Pmiss, p_tar=0.01, normalize=True): p_tar = np.asarray(p_tar) p_non = (1 - p_tar) cdet = np.dot(np.vstack((p_tar, p_non)).T, np.vstack((Pmiss, Pfa))) idxdcfs = np.argmin(cdet, 1) dcfs = cdet[(np.arange(len(idxdcfs)), idxdcfs)] if normalize: mins = np.amin(np.vstack((...
def check_required_param(param_desc: list[str], param: inspect.Parameter, method_or_obj_name: str) -> bool: is_ours_required = (param.default is inspect.Parameter.empty) telegram_requires = is_parameter_required_by_tg(param_desc[2]) if (param.name in ignored_param_requirements(method_or_obj_name)): ...
class Effect6501(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Energy Turret')), 'damageMultiplier', src.getModifiedItemAttr('shipBonusDreadnoughtA1'), skill='Amarr Dreadnought', **kwarg...
class IntermediateLayerGetter(nn.Module): _version = 2 __constants__ = ['layers'] __annotations__ = {'return_layers': Dict[(str, str)]} def __init__(self, model, return_layers): if (not set(return_layers).issubset([name for (name, _) in model.named_children()])): raise ValueError('re...
def odnoklassniki_oauth_sig(data, client_secret): suffix = md5('{:s}{:s}'.format(data['access_token'], client_secret).encode('utf-8')).hexdigest() check_list = sorted((f'{key:s}={value:s}' for (key, value) in data.items() if (key != 'access_token'))) return md5((''.join(check_list) + suffix).encode('utf-8')...
class TimeStampTextFrame(TextFrame): _framespec = [EncodingSpec('encoding', default=Encoding.UTF16), MultiSpec('text', TimeStampSpec('stamp'), sep=u',', default=[])] def __bytes__(self): return str(self).encode('utf-8') def __str__(self): return u','.join([stamp.text for stamp in self.text])...
class Execute(Message): type = message_types[b'E'[0]] __slots__ = ('name', 'max') def __init__(self, name, max=0): self.name = name self.max = max def serialize(self): return ((self.name + b'\x00') + ulong_pack(self.max)) def parse(typ, data): (name, max) = data.split...
('/classify_upload', methods=['POST']) def classify_upload(): try: imagefile = flask.request.files['imagefile'] filename_ = (str(datetime.datetime.now()).replace(' ', '_') + werkzeug.secure_filename(imagefile.filename)) filename = os.path.join(UPLOAD_FOLDER, filename_) imagefile.save...
def subdispatch_to_paymenttask(chain_state: ChainState, state_change: StateChange, secrethash: SecretHash) -> TransitionResult[ChainState]: block_number = chain_state.block_number block_hash = chain_state.block_hash sub_task = chain_state.payment_mapping.secrethashes_to_task.get(secrethash) events: List...
class VNet(MetaModule): def __init__(self, input, hidden1, hidden2, output, num_classes): super(VNet, self).__init__() self.feature = share(input, hidden1, hidden2) self.classfier = task(hidden2, output, num_classes) def forward(self, x, num, c): output = self.classfier(self.feat...
def resp_update_link(): updated_content = dict(link_content) updated_content['link_type'] = new_link_type with responses.RequestsMock() as rsps: rsps.add(method=responses.PUT, url=link_id_url, json=updated_content, content_type='application/json', status=200) (yield rsps)
def train_model_swag_binning(model, arch, opt, train_data, test_data, args, lamb_lr, verbose=True): model.train() MI_data = train_data (train_accs, train_losses) = ([], []) (test_accs, test_losses) = ([], []) binning_MIs = [] l_MIs = [] maxes = [] t = 0 analyse(model, grads=True) ...
def test_to_recap_record(): converter = AvroConverter() avro_record = {'type': 'record', 'name': 'Test', 'fields': [{'name': 'a', 'type': 'int'}, {'name': 'b', 'type': 'string'}]} actual = converter.to_recap(json.dumps(avro_record)) assert isinstance(actual, StructType) assert (len(actual.fields) ==...
def dumped(parameters=True, returnvalue=True, fork_inst=JsonSerializable, dumper=dump, **kwargs): if (dumper not in (dump, dumps, dumpb)): raise InvalidDecorationError("The 'dumper' argument must be one of: jsons.dump, jsons.dumps, jsons.dumpb") return _get_decorator(parameters, returnvalue, fork_inst, ...
def get_config(): config = get_default_configs() training = config.training training.sde = 'vpsde' training.continuous = True training.reduce_mean = True sampling = config.sampling sampling.method = 'pc' sampling.predictor = 'euler_maruyama' sampling.corrector = 'none' data = con...
def get_private_repo_count(username): return Repository.select().join(Visibility).switch(Repository).join(Namespace, on=(Repository.namespace_user == Namespace.id)).where((Namespace.username == username), (Visibility.name == 'private')).where((Repository.state != RepositoryState.MARKED_FOR_DELETION)).count()
def test_flask_restful_integration_works(): class HelloWorld(flask_restful.Resource): def __init__(self, *args, int: int, **kwargs): self._int = int super().__init__(*args, **kwargs) def get(self): return {'int': self._int} app = Flask(__name__) api = flas...
(scope='session') def truncated_geos_area(create_test_area): proj_dict = {'a': '6378169', 'h': '', 'lon_0': '9.5', 'no_defs': 'None', 'proj': 'geos', 'rf': '295.', 'type': 'crs', 'units': 'm', 'x_0': '0', 'y_0': '0'} area_extent = (5567248.0742, 5570248.4773, (- 5570248.4773), 1393687.2705) shape = (1392, 3...
def _error_text(because: str, text: str, backend: usertypes.Backend, suggest_other_backend: bool=False) -> str: text = f'<b>Failed to start with the {backend.name} backend!</b><p>qutebrowser tried to start with the {backend.name} backend but failed because {because}.</p>{text}' if suggest_other_backend: ...
def convert_acdc(src_data_folder: str, dataset_id=27): (out_dir, train_dir, labels_dir, test_dir) = make_out_dirs(dataset_id=dataset_id) num_training_cases = copy_files(Path(src_data_folder), train_dir, labels_dir, test_dir) generate_dataset_json(str(out_dir), channel_names={0: 'cineMRI'}, labels={'backgrou...
def _load_config(composite_configs): if (not isinstance(composite_configs, (list, tuple))): composite_configs = [composite_configs] conf = {} for composite_config in composite_configs: with open(composite_config, 'r', encoding='utf-8') as conf_file: conf = recursive_dict_update(c...
def patch_builtin_len(modules=()): def _new_len(obj): return obj.__len__() with ExitStack() as stack: MODULES = (['detectron2.modeling.roi_heads.fast_rcnn', 'detectron2.modeling.roi_heads.mask_head', 'detectron2.modeling.roi_heads.keypoint_head'] + list(modules)) ctxs = [stack.enter_cont...
def gd(fcn: Callable[(..., torch.Tensor)], x0: torch.Tensor, params: List, step: float=0.001, gamma: float=0.9, maxiter: int=1000, f_tol: float=0.0, f_rtol: float=1e-08, x_tol: float=0.0, x_rtol: float=1e-08, verbose=False, **unused): x = x0.clone() stop_cond = TerminationCondition(f_tol, f_rtol, x_tol, x_rtol,...
def cookie_decode(data, key): data = tob(data) if cookie_is_encoded(data): (sig, msg) = data.split(tob('?'), 1) if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())): return pickle.loads(base64.b64decode(msg)) return None
class Adjoint(GateWithRegisters): subbloq: 'Bloq' _property def signature(self) -> 'Signature': return self.subbloq.signature.adjoint() def decompose_bloq(self) -> 'CompositeBloq': return self.subbloq.decompose_bloq().adjoint() def supports_decompose_bloq(self) -> bool: retur...
class _CfdRunnable(object): def __init__(self, solver): if (solver and solver.isDerivedFrom('Fem::FemSolverObjectPython')): self.solver = solver else: raise TypeError('FemSolver object is missing in constructing CfdRunnable object') self.analysis = CfdTools.getParentA...
def _fig_add_predictions(fig: Figure, category_data_frame: DataFrame, columns: List[str], column_color_map: Dict[(str, str)], show_legend: bool, row: int) -> None: for column in columns: if (column == COLUMN_DELTA): marker_dict = dict(color=column_color_map[column], size=2) fig.add_s...
def test_image_to_tensor(): original_results = dict(imgs=np.random.randn(256, 256, 3)) keys = ['imgs'] image_to_tensor = ImageToTensor(keys) results = image_to_tensor(original_results) assert (results['imgs'].shape == torch.Size([3, 256, 256])) assert isinstance(results['imgs'], torch.Tensor) ...
('builtins.open', new_callable=mock.mock_open) ('pytube.request.urlopen') def test_create_mock_html_json(mock_url_open, mock_open): video_id = '2lAe1cqCOXo' gzip_html_filename = ('yt-video-%s-html.json.gz' % video_id) pytube_dir_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))...
def attach(parser): add_input(parser, pages=False) subparsers = parser.add_subparsers(dest='action') subparsers.add_parser(ACTION_LIST) parser_extract = subparsers.add_parser(ACTION_EXTRACT) parser_extract.add_argument('--numbers', type=parse_numtext) parser_extract.add_argument('--output-dir', ...
class HonggfuzzEngineDescriptor(FuzzingEngineDescriptor): NAME = 'HONGGFUZZ' SHORT_NAME = 'HF' VERSION = '1.0.0' HF_PERSISTENT_SIG = b'\x01_LIBHFUZZ_PERSISTENT_BINARY_SIGNATURE_\x02\xff' config_class = HonggfuzzConfigurationInterface def __init__(self): pass def accept_file(binary_fi...
def test_perform_indexing_failed_within_reindex_threshold(initialized_db, set_secscan_config): application.config['SECURITY_SCANNER_V4_REINDEX_THRESHOLD'] = 300 secscan = V4SecurityScanner(application, instance_keys, storage) secscan._secscan_api = mock.Mock() secscan._secscan_api.state.return_value = {...
def test_prepare_metadata_for_build_wheel_with_bad_path_dep_succeeds(caplog: LogCaptureFixture) -> None: with temporary_directory() as tmp_dir, cwd(os.path.join(fixtures, 'with_bad_path_dep')): api.prepare_metadata_for_build_wheel(tmp_dir) assert (len(caplog.records) == 1) record = caplog.records[0]...
_module() class CCHead(FCNHead): def __init__(self, recurrence=2, **kwargs): if (CrissCrossAttention is None): raise RuntimeError('Please install mmcv-full for CrissCrossAttention ops') super(CCHead, self).__init__(num_convs=2, **kwargs) self.recurrence = recurrence self....
class PreSuDataset(data.Dataset): def __init__(self, img_list, low_size=64, loader=default_loader): super(PreSuDataset, self).__init__() self.imgs = list(img_list) self.loader = loader def append(imgs): imgs.append(transforms.Scale(low_size, interpolation=Image.NEAREST)(i...
def setupEnv(reinitialize=False): dsz.env.Set('OPS_TIME', ops.timestamp()) dsz.env.Set('OPS_DATE', ops.datestamp()) for i in flags(): if ((not dsz.env.Check(i)) or reinitialize): ops.env.set(i, False) dszflags = dsz.control.Method() dsz.control.echo.Off() if (not dsz.cmd.Run(...
def log_features(feas, tb_writer, tb_index, rank): fea_cls = feas['cls'] fea_loc = feas['loc'] for i in range(len(fea_cls)): fea = fea_cls[i].detach() s = fea.shape fea = fea.view((s[0] * s[1]), (- 1)) fea = fea.norm(dim=1) fea = fea.cpu().numpy() fea = np.flo...
def sc_zaleplon_with_other_formula() -> GoalDirectedBenchmark: specification = uniform_specification(1, 10, 100) benchmark_object = zaleplon_with_other_formula() sa_biased = ScoringFunctionSAWrapper(benchmark_object.objective, SCScoreModifier()) return GoalDirectedBenchmark(name='SC_zaleplon', objective...
class TestCLS(): def test_graph_search_utils_single_residual_model(self): if (version.parse(torch.__version__) >= version.parse('1.13')): model = models_for_tests.single_residual_model() connected_graph = ConnectedGraph(model) ordered_module_list = get_ordered_list_of_con...
def getNameFromSid(sid, domain=None): name = LPWSTR() cbName = DWORD(0) referencedDomainName = LPWSTR() cchReferencedDomainName = DWORD(0) peUse = DWORD(0) try: LookupAccountSidW(domain, sid, None, byref(cbName), None, byref(cchReferencedDomainName), byref(peUse)) except Exception as...
_image_displayer('ueberzug') class UeberzugImageDisplayer(ImageDisplayer): IMAGE_ID = 'preview' is_initialized = False def __init__(self): self.process = None def initialize(self): if (self.is_initialized and (self.process.poll() is None) and (not self.process.stdin.closed)): ...
class BatchStudy(): INPUT_LIST = ['experiments', 'geometries', 'parameter_values', 'submesh_types', 'var_pts', 'spatial_methods', 'solvers', 'output_variables', 'C_rates'] def __init__(self, models, experiments=None, geometries=None, parameter_values=None, submesh_types=None, var_pts=None, spatial_methods=None,...
def test_profile_weir(): with tempfile.TemporaryDirectory() as tempdir: temp_model_path = os.path.join(tempdir, 'model.inp') temp_pdf_path = os.path.join(tempdir, 'test.pdf') mymodel = swmmio.Model(MODEL_EXAMPLE6) mymodel.inp.save(temp_model_path) with pyswmm.Simulation(temp_...
_sentencepiece _tokenizers class DebertaV2TokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = DebertaV2Tokenizer rust_tokenizer_class = DebertaV2TokenizerFast test_sentencepiece = True test_sentencepiece_ignore_case = True def setUp(self): super().setUp() tok...
class TypoScriptCssDataLexer(RegexLexer): name = 'TypoScriptCssData' aliases = ['typoscriptcssdata'] url = ' version_added = '2.2' tokens = {'root': [('(.*)(###\\w+###)(.*)', bygroups(String, Name.Constant, String)), ('(\\{)(\\$)((?:[\\w\\-]+\\.)*)([\\w\\-]+)(\\})', bygroups(String.Symbol, Operator,...
class ScantronClient(): def __init__(self, secrets_file_location='./scantron_api_secrets.json', **kwargs): SECRETS = {} try: with open(secrets_file_location) as config_file: SECRETS = json.loads(config_file.read()) except OSError: print(f'Error: {secre...
def enc_obj2bytes(obj, max_size=16000): assert (max_size <= MAX_SIZE_LIMIT) byte_tensor = torch.zeros(max_size, dtype=torch.uint8) obj_enc = pickle.dumps(obj) obj_size = len(obj_enc) if (obj_size > max_size): raise Exception('objects too large: object size {}, max size {}'.format(obj_size, m...
def make_device(device_str: Optional[str]) -> torch.device: if device_str: try: device = torch.device(device_str) except RuntimeError as error: device_type = device_str.split(':')[0] msg = f"Unknown device type '{device_type}'." match = re.match('Expec...
class AttributeSliderChangeEvent(): def __init__(self, obj, old_value, new_value, old_percentage, new_percentage, affect_modified_flag=True): self.__obj = obj self.__old = old_value self.__new = new_value self.__old_percent = old_percentage self.__new_percent = new_percentage...
def get_no_augmentation(dataloader_train, dataloader_val, params=default_3D_augmentation_params, deep_supervision_scales=None, soft_ds=False, classes=None, pin_memory=True, regions=None): tr_transforms = [] if (params.get('selected_data_channels') is not None): tr_transforms.append(DataChannelSelectionT...
def _iter_translations(args, task, dataset, translations, align_dict, rescorer, modify_target_dict): is_multilingual = pytorch_translate_data.is_multilingual_many_to_one(args) for (sample_id, src_tokens, target_tokens, hypos) in translations: target_tokens = target_tokens.int().cpu() if is_multi...
class TestStickerWithoutRequest(TestStickerBase): def test_slot_behaviour(self, sticker): for attr in sticker.__slots__: assert (getattr(sticker, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(sticker)) == len(set(mro_slots(sticker)))), 'duplicate slot' def ...
class GammaL(BinaryScalarOp): def st_impl(k, x): return (scipy.special.gammainc(k, x) * scipy.special.gamma(k)) def impl(self, k, x): return GammaL.st_impl(k, x) def c_support_code(self, **kwargs): with open(os.path.join(os.path.dirname(__file__), 'c_code', 'gamma.c')) as f: ...
def test_axis_azimuth(): apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([90]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=90, max_angle=90, backtrack=True, gcr=(2.0 / 7.0)) expect = pd.DataFrame({'aoi': 30, 'surface_azimuth': 180, 'surf...
def sendrecv(sendbuf, source=0, dest=0): if (source == dest): return sendbuf if (rank == source): sendbuf = numpy.asarray(sendbuf, order='C') comm.send((sendbuf.shape, sendbuf.dtype), dest=dest) comm.Send(sendbuf, dest=dest) return sendbuf elif (rank == dest): ...
class Database(LiveDict): def __init__(self, path): super(Database, self).__init__(json.loads(open(path).read())) self.path = path def update(self): with open(self.path, 'w+') as f: f.write(json.dumps(self.todict())) def refresh(self): with open(self.path, 'w+') a...
class UpdateLog(): def __init__(self, started, completed, versions, periodic) -> None: self.started = started self.completed = completed self.versions = versions self.periodic = periodic def from_dict(cls, dictionary): if (dictionary is None): dictionary = {} ...
def test_tar_extract_one_with_interpolation(): context = Context({'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'tar': {'extract': [{'in': './{key3}.tar.xz', 'out': 'path/{key2}/dir'}]}}) with patch('tarfile.open') as mock_tarfile: pypyr.steps.tar.run_step(context) mock_tarfile.assert_called...
def load_and_covnert_case(input_image: str, input_seg: str, output_image: str, output_seg: str, min_component_size: int=50): seg = io.imread(input_seg) seg[(seg == 255)] = 1 image = io.imread(input_image) image = image.sum(2) mask = (image == (3 * 255)) mask = generic_filter_components(mask, fil...
class OptionSetOption(models.Model): optionset = models.ForeignKey('OptionSet', on_delete=models.CASCADE, related_name='optionset_options') option = models.ForeignKey('Option', on_delete=models.CASCADE, related_name='option_optionsets') order = models.IntegerField(default=0) class Meta(): orderi...