code
stringlengths
281
23.7M
class SwinTransformer(nn.Module): def __init__(self, img_size=224, patch_size=4, embed_dim=96, depths=[2, 2, 6], num_heads=[3, 6, 12], window_size=7, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1, norm_layer=nn.LayerNorm, ape=False, patch_norm=True, **kwargs): ...
def str_to_bool(value): if isinstance(value, basestring): value = value.strip().lower() if (value in ['true', 't', 'yes', 'y']): return True elif (value in ['false', 'f', 'no', 'n', '']): return False else: raise NotImplementedError(('Unknown bool ...
def callgraphHTML(sv, hf, num, cg, title, color, devid): html_func_top = '<article id="{0}" class="atop" style="background:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n' html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label fo...
class ParseError(RuntimeError): def __init__(self, expected, stream, index): self.expected = expected self.stream = stream self.index = index def line_info(self): try: return '{}:{}'.format(*line_info_at(self.stream, self.index)) except (TypeError, AttributeEr...
def test_channelstate_repeated_contract_balance(): deposit_block_number = 10 block_number = ((deposit_block_number + DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS) + 1) deposit_block_hash = make_block_hash() (our_model1, _) = create_model(70) (partner_model1, partner_pkey1) = create_model(100) channel_s...
class InitDataset(Dataset): def __init__(self, data_root, img_transform, mask_transform, data='train'): super(InitDataset, self).__init__() self.img_transform = img_transform self.mask_transform = mask_transform if (data == 'train'): self.paths = glob('{}/train/**/*.jpg'....
def jsonl_iterator(input_fname, positive_only=False, ngram_order=3, eval=False): detok = get_detokenizer() nlp = get_spacy_nlp() with open(input_fname) as fin: for line in fin: sample = json.loads(line.strip()) if (positive_only and ('label' in sample) and (not sample['label'...
def testQueryURL(run_cli, backends): bz = _open_bz(REDHAT_URL, **backends) qurl = '/buglist.cgi?f1=creation_ts&list_id=973582&o1=greaterthaneq&classification=Fedora&o2=lessthaneq&query_format=advanced&f2=creation_ts&v1=2010-01-01&component=python-bugzilla&v2=2010-06-01&product=Fedora' url = REDHAT_URL i...
class DockerSchema2ManifestBuilder(object): def __init__(self): self.config = None self.filesystem_layers = [] def clone(self): cloned = DockerSchema2ManifestBuilder() cloned.config = self.config cloned.filesystem_layers = list(self.filesystem_layers) return clone...
def test_unique_uri_validator_serializer_create_error(db): validator = OptionSetUniqueURIValidator() serializer = OptionSetSerializer() with pytest.raises(RestFameworkValidationError): validator({'uri_prefix': settings.DEFAULT_URI_PREFIX, 'uri_path': OptionSet.objects.first().uri_path}, serializer)
def fill_result_with_error(result, error, trace, models_to_create): error = (error, trace) result['error'] = error for framework in FRAMEWORKS: if (framework in models_to_create): result[framework] = {} for model_arch in models_to_create[framework]: result[fra...
def get_patch_size(final_patch_size, rot_x, rot_y, rot_z, scale_range): if isinstance(rot_x, (tuple, list)): rot_x = max(np.abs(rot_x)) if isinstance(rot_y, (tuple, list)): rot_y = max(np.abs(rot_y)) if isinstance(rot_z, (tuple, list)): rot_z = max(np.abs(rot_z)) rot_x = min((((9...
def check_keys(model, pretrained_state_dict): ckpt_keys = set(pretrained_state_dict.keys()) model_keys = set(model.state_dict().keys()) used_pretrained_keys = (model_keys & ckpt_keys) unused_pretrained_keys = (ckpt_keys - model_keys) missing_keys = (model_keys - ckpt_keys) missing_keys = [x for ...
def train(cfg, args, model, device, distributed): optimizer = make_optimizer(cfg, model) scheduler = make_lr_scheduler(cfg, optimizer) arguments = {} arguments['iteration'] = 0 output_dir = cfg.OUTPUT_DIR save_to_disk = (comm.get_rank() == 0) checkpointer = DetectronCheckpointer(cfg, model, ...
def _verify_static_class_methods(stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str]) -> Iterator[str]: if (stub.name in ('__new__', '__init_subclass__', '__class_getitem__')): return if inspect.isbuiltin(runtime): probably_class_method = isinstance(geta...
_cache(maxsize=16) def _get_enum_field_values(enum_field): values = [] for row in enum_field.rel_model.select(): key = getattr(row, enum_field.enum_key_field) value = getattr(row, 'id') values.append((key, value)) return Enum(enum_field.rel_model.__name__, values)
_module class SingleStageDetector(BaseDetector): def __init__(self, backbone, neck=None, bbox_head=None, train_cfg=None, test_cfg=None, pretrained=None): super(SingleStageDetector, self).__init__() self.backbone = builder.build_backbone(backbone) if (neck is not None): self.neck ...
def rotation_matrix_axis(dim, theta): if (dim == 0): rm = np.array([[1.0, 0.0, 0.0], [0.0, math.cos(theta), (- math.sin(theta))], [0.0, math.sin(theta), math.cos(theta)]]) elif (dim == 1): rm = np.array([[math.cos(theta), 0.0, math.sin(theta)], [0.0, 1.0, 0.0], [(- math.sin(theta)), 0.0, math.co...
def _process_css(default_css, extra_css): with open(default_css, encoding='utf-8') as f: css = f.read() for path in extra_css: css += '\n/' css += '\n * CUSTOM CSS' css += f''' * {path}''' css += '\n /\n\n' with open(path, encoding='utf-8') as f: css ...
class TFAutoData(): def __init__(self): self.features_list = [] self._train_data_path = '' self.schema = '' self.stats_train = '' self.stats_eval = '' self.anom_train = '' self.anom_eval = '' self.file_headers = [] self._len_train = 0 s...
def _setup_single_view_dispatcher_route(api_blueprint: Blueprint, options: Options, constructor: RootComponentConstructor) -> None: sock = Sock(api_blueprint) def model_stream(ws: WebSocket, path: str='') -> None: def send(value: Any) -> None: ws.send(json.dumps(value)) def recv() ->...
def determine_ctype_from_vconv(ctype, unit, velocity_convention=None): unit = u.Unit(unit) if (len(ctype) > 4): in_physchar = ctype[5] else: lin_cunit = LINEAR_CUNIT_DICT[ctype] in_physchar = PHYSICAL_TYPE_TO_CHAR[parse_phys_type(lin_cunit)] if (parse_phys_type(unit) == 'speed'):...
def routedict_to_routelist_single(name, D, indent=1): Locals = dict() indents = dict(I0=('\t' * indent), I1=('\t' * (indent + 1)), I2=('\t' * (indent + 2)), I3=('\t' * (indent + 3)), I4=('\t' * (indent + 4))) if False: D0 = D keyname = 'src' valname = 'dest' else: keyname...
def _get_ordered_conv_linears(node_layer_map: Dict, layer_out_node_map: Dict) -> List[Union[(ConvType, LinearType)]]: list_of_ordered_layers = _get_ordered_layers(node_layer_map, layer_out_node_map) ordered_conv_linears = [] for layer in list_of_ordered_layers: if isinstance(layer, _supported_layers...
_tf class TFViTBertModelTest(TFVisionTextDualEncoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = TFVisionTextDualEncoderModel.from_vision_text_pretrained('hf-internal-testing/tiny-random-vit', 'hf-internal-testing/tiny-random-bert') batch_size = 13 pixel_valu...
def test_init_pq_lower_limit_option(tmpdir, mocker): mocker.patch.object(SentinelOne, '_authenticate') cred_file_path = tmpdir.mkdir('test_dir').join('test_creds.ini') cred_file_path.write('asdfasdfasdf') s1_product = SentinelOne(profile='default', creds_file=cred_file_path, account_id=None, site_id=Non...
def _print_collected_tasks(dictionary: dict[(Path, list[PTaskWithPath])], show_nodes: bool, editor_url_scheme: str, common_ancestor: Path) -> None: console.print() tree = Tree('Collected tasks:', highlight=True) for (module, tasks) in dictionary.items(): reduced_module = relative_to(module, common_a...
class TestSimpleUpdateProcessor(): def test_slot_behaviour(self): inst = SimpleUpdateProcessor(1) for attr in inst.__slots__: assert (getattr(inst, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(inst)) == len(set(mro_slots(inst)))), 'duplicate slot' ...
def generate_random_object_cluster(n_objects, object_generator, max_cluster_trans=1.0, max_cluster_rot=(np.pi / 8)): ref_obj = object_generator() cluster_objects = [] for i in range(n_objects): r = random_rotation_translation_rotor(maximum_translation=max_cluster_trans, maximum_angle=max_cluster_rot...
() def daily_update_geos(day=None, geo=True, region=True): (start_date, end_date) = get_day(day) if ((not geo) and (not region)): log.error('geo or region required, please pass one as True') return if geo: log.info('Updating GeoImpressions for %s-%s', start_date, end_date) if reg...
class RegStage(nn.Module): def __init__(self, depth, in_chs, out_chs, stride, dilation, drop_path_rates=None, block_fn=Bottleneck, **block_kwargs): super(RegStage, self).__init__() self.grad_checkpointing = False first_dilation = (1 if (dilation in (1, 2)) else 2) for i in range(dept...
def stop(name, location='\\'): if (name not in list_tasks(location)): return '{0} not found in {1}'.format(name, location) pythoncom.CoInitialize() task_service = win32com.client.Dispatch('Schedule.Service') task_service.Connect() task_folder = task_service.GetFolder(location) task = tas...
def is_valid_signature(data: bytes, signature: Signature, sender_address: Address) -> SuccessOrError: try: signer_address = recover(data=data, signature=signature) except Exception: return SuccessOrError('Signature invalid, could not be recovered.') is_correct_sender = (sender_address == sig...
class JaggedSparse(Callable): def __init__(self, *, weighted: bool, combine_option: CombineOption=CombineOption.JAGGED): self._weighted = weighted self._combine_option = combine_option def __call__(self, df): assert (df.device == 'cpu') raise NotImplementedError def weighted(...
class TestEvolution(QiskitAquaTestCase): def test_exp_i(self): op = Z.exp_i() gate = op.to_circuit().data[0][0] self.assertIsInstance(gate, qiskit.circuit.library.RZGate) self.assertEqual(gate.params[0], 2) def test_trotter_with_identity(self): op = (((2.0 * I) ^ I) + (Z ...
class TruncatedNormal(BoundedContinuous): rv_op = truncated_normal bound_args_indices = (5, 6) def dist(cls, mu: Optional[DIST_PARAMETER_TYPES]=0, sigma: Optional[DIST_PARAMETER_TYPES]=None, *, tau: Optional[DIST_PARAMETER_TYPES]=None, lower: Optional[DIST_PARAMETER_TYPES]=None, upper: Optional[DIST_PARAMET...
class _RepoIncrementITRB(_RepoPatchITRB): def __init__(self, basis_root_rp, inc_root_rp, rorp_cache, previous_time): self.inc_root_rp = inc_root_rp self.previous_time = previous_time _RepoPatchITRB.__init__(self, basis_root_rp, rorp_cache) def fast_process_file(self, index, diff_rorp): ...
def get_contrastive_aug(dataset, aug_type='simclr'): if ((dataset == 'miniImageNet') or (dataset == 'tieredImageNet') or (dataset == 'cross')): (mean, std) = MEAN_STD['imagenet'] crop_size = 84 elif ((dataset == 'CIFAR-FS') or (dataset == 'FC100')): (mean, std) = MEAN_STD['cifar'] ...
def undo_rule(workflow, ruleid): (r2s, s2r, r2subscopes) = utils.rule_steps_indices(workflow) if (not (ruleid in [r.identifier for r in workflow.applied_rules])): ruleobj = workflow.view().getRule(identifier=ruleid) log.debug('rule %s/%s not in list of applied rules. possibly already undone duri...
def check_molecule_data_structure(fname, verbose=True): with open(fname) as f: try: db = json.load(f) except json.JSONDecodeError as err: raise json.JSONDecodeError("Error reading '{0}' (line {2} col {3}): \n{1}".format(fname, err.msg, err.lineno, err.colno), err.doc, err.pos...
class RolloutBaseline(Baseline): def __init__(self, model, problem, opts, epoch=0): super(Baseline, self).__init__() self.problem = problem self.opts = opts self._update_model(model, epoch) def _update_model(self, model, epoch, dataset=None): self.model = copy.deepcopy(mo...
class PriceViewMinimal(StatsView): name = 'priceViewMinimal' def __init__(self, parent): StatsView.__init__(self) self.parent = parent self.settings = MarketPriceSettings.getInstance() def getHeaderText(self, fit): return 'Price' def populatePanel(self, contentPanel, head...
class BaseClient(): def __init__(self, client_id: str, **kwargs): loop = kwargs.get('loop', None) handler = kwargs.get('handler', None) self.pipe = kwargs.get('pipe', None) self.isasync = kwargs.get('isasync', False) self.connection_timeout = kwargs.get('connection_timeout', ...
def _compute_adjusted_exponent_length(exponent_length: int, first_32_exponent_bytes: bytes) -> int: exponent = big_endian_to_int(first_32_exponent_bytes) if ((exponent_length <= 32) and (exponent == 0)): return 0 elif (exponent_length <= 32): return get_highest_bit_index(exponent) else: ...
def generate_kaldi_data_files(utterances, outdir): logger.info('Exporting to {}...'.format(outdir)) speakers = {} with open(os.path.join(outdir, 'text'), 'w', encoding='latin-1') as f: for utt in utterances: f.write((utt.to_kaldi_utt_str() + '\n')) with open(os.path.join(outdir, 'wav...
def test_extra_saturate(debug_ctx, debug_trail): loader_getter = make_loader_getter(shape=shape(TestField('a', ParamKind.POS_ONLY, is_required=True)), name_layout=InputNameLayout(crown=InpDictCrown({'a': InpFieldCrown('a')}, extra_policy=ExtraCollect()), extra_move=ExtraSaturate(Gauge.saturate)), debug_trail=debug_...
class TestDOTAR2CNNKF(TestDOTA): def eval(self): txt_name = '{}.txt'.format(self.cfgs.VERSION) real_test_img_list = self.get_test_image() r2cnn_kf = build_whole_network.DetectionNetworkR2CNNKF(cfgs=self.cfgs, is_training=False) self.test_dota(det_net=r2cnn_kf, real_test_img_list=real...
def export_foam_mesh(obj, meshfileString, foamCaseFolder=None): gmsh = CaeMesherGmsh.CaeMesherGmsh(obj, CfdTools.getParentAnalysisObject(obj)) meshfile = gmsh.export_mesh(u'Gmsh MSH', meshfileString) if meshfile: msg = 'Info: Mesh is not written to `{}` by Gmsh\n'.format(meshfile) FreeCAD.Co...
class TestTaskRc(TestCase): def setUp(self): self.path_to_taskrc = os.path.join(os.path.dirname(__file__), 'data/default.taskrc') self.taskrc = TaskRc(self.path_to_taskrc) def test_taskrc_parsing(self): expected_config = {'data': {'location': '~/.task'}, 'alpha': {'one': 'yes', 'two': '2...
def _search_cross_references(call_graph_analysis_list, search_depth): reference_dict = defaultdict(set) if (not call_graph_analysis_list): return reference_dict apkinfo = call_graph_analysis_list[0]['apkinfo'] parent_set = {item['parent'] for item in call_graph_analysis_list} for parent in p...
def test_info_setup_complex_pep517_error(mocker: MockerFixture, demo_setup_complex: Path) -> None: mocker.patch('poetry.utils.env.VirtualEnv.run', autospec=True, side_effect=EnvCommandError(CalledProcessError(1, 'mock', output='mock'))) with pytest.raises(PackageInfoError): PackageInfo.from_directory(de...
class Generator(nn.Module): def __init__(self, dim=64): super(Generator, self).__init__() self.dim = dim self.linear1 = nn.Linear(128, (((4 * 4) * 4) * dim)) self.bn1 = nn.BatchNorm1d((((4 * 4) * 4) * dim)) self.relu1 = nn.ReLU(True) self.block1 = nn.Sequential(nn.Con...
_torch class TestActivations(unittest.TestCase): def test_gelu_versions(self): x = torch.tensor([(- 100), (- 1), (- 0.1), 0, 0.1, 1.0, 100]) torch_builtin = get_activation('gelu') self.assertTrue(torch.allclose(gelu_python(x), torch_builtin(x))) self.assertFalse(torch.allclose(gelu_p...
class InceptionCUnit(nn.Module): def __init__(self, in_channels, out_channels): super(InceptionCUnit, self).__init__() assert (out_channels == 2048) self.branches = Concurrent() self.branches.add_module('branch1', Conv1x1Branch(in_channels=in_channels, out_channels=320)) self...
class FrequencyValue(SensorValue): def __init__(self, name): super(FrequencyValue, self).__init__(name) self.loopc = 0 self.t0 = time.monotonic() def strobe(self): self.loopc += 1 if (self.loopc == 4): t1 = time.monotonic() self.set((self.loopc / (...
def test_properties(): prop = OSC.Properties() prop.add_property('mything', '2') prop.add_property('theotherthing', 'true') prop.add_file('propfile.xml') prettyprint(prop) prop2 = OSC.Properties() prop2.add_property('mything', '2') prop2.add_property('theotherthing', 'true') prop2.ad...
def _sharded_tensor_to_gpu(tensor: sharded_tensor.ShardedTensor) -> sharded_tensor.ShardedTensor: device = torch.device(f'cuda:{torch.cuda.current_device()}') shards: List[sharded_tensor.Shard] = [] for shard in tensor.local_shards(): new_tensor = shard.tensor.to(device=device) metadata = co...
class MatrixOperator(LegacyBaseOperator): def __init__(self, matrix, basis=None, z2_symmetries=None, atol=1e-12, name=None): super().__init__(basis, z2_symmetries, name) if (matrix is not None): matrix = (matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix)) ...
class Effect1020(BaseEffect): type = 'passive' def handler(fit, skill, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Large Artillery Specialization')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwar...
class TestLoadCFAreaPublic(): def test_load_cf_no_exist(self): cf_file = os.path.join(TEST_FILES_PATH, 'does_not_exist.nc') with pytest.raises(FileNotFoundError): load_cf_area(cf_file) def test_load_cf_from_not_nc(self): cf_file = os.path.join(TEST_FILES_PATH, 'areas.yaml') ...
class CompressedData(): __slots__ = ['data', 'dtype'] def __init__(self): self.data = None self.dtype = None def compression(self, a): self.data = compress(a.tobytes()) self.dtype = a.dtype def decompression(self): return fromstring(decompress(self.data), dtype=se...
class Effect5620(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Missile Launcher Rapid Heavy')), 'speed', ship.getModifiedItemAttr('shipBonusMB'), skill='Minmatar Battleship', **kwargs)
class ProjectDeployTokenManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager): _path = '/projects/{project_id}/deploy_tokens' _from_parent_attrs = {'project_id': 'id'} _obj_cls = ProjectDeployToken _create_attrs = RequiredOptional(required=('name', 'scopes'), optional=('expires_at', 'username'))...
class FragDBInfo(): filename: str num_compounds: int num_error_compounds: int num_fragmentations: int num_constants: int num_variables: int max_num_pairs: int options: object def get_cols(self): return [self.filename, str(self.num_compounds), str(self.num_error_compounds), st...
def ttrl(x, ranks, n_outputs): weight_initializer = tf.contrib.layers.xavier_initializer() suffix = n_outputs input_shape = x.get_shape().as_list()[1:] bias = tf.get_variable('bias_{}'.format(np.prod(n_outputs)), shape=(1, np.prod(n_outputs))) cores = [] for i in range(1, (len(ranks) - 1)): ...
def test_run_with_verbosity(tester: ApplicationTester) -> None: tester.execute('list --verbose') assert tester.io.is_verbose() tester.execute('list -v') assert tester.io.is_verbose() tester.execute('list -vv') assert tester.io.is_very_verbose() tester.execute('list -vvv') assert tester.i...
class RanksComparatorPlotter(AccessorABC): _default_kind = 'box' def __init__(self, ranks_cmp): self._ranks_cmp = ranks_cmp def flow(self, *, untied=False, grid_kws=None, **kwargs): df = self._ranks_cmp.to_dataframe(untied=untied) ax = sns.lineplot(data=df.T, estimator=None, sort=Fal...
def _load_model_file(load_path, model): load_optimizer_state_dict = None print(' [*] Loading model from {}'.format(load_path)) load_data = torch.load(os.path.join(os.getcwd(), load_path), map_location=(lambda storage, loc: storage)) if isinstance(load_data, dict): load_optimizer_state_dict = lo...
class PassThroughOpLastLayerModel(nn.Module): def __init__(self): super(PassThroughOpLastLayerModel, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=2, stride=2, padding=2, bias=False) self.passthrough = torch.nn.Identity() def forward(self, *inputs): x = self.conv1(in...
def makeUpdateMatrixSv(qnnArch, unitaries, trainingData, storedStates, lda, ep, l, j): numInputQubits = qnnArch[(l - 1)] summ = 0 for x in range(len(trainingData)): firstPart = updateMatrixFirstPart(qnnArch, unitaries, storedStates, l, j, x) secondPart = updateMatrixSecondPart(qnnArch, unita...
def _infer_single_node_init(cfg: DistributedTrainingConfig): assert (cfg.distributed_world_size <= torch.cuda.device_count()), f'world size is {cfg.distributed_world_size} but have {torch.cuda.device_count()} available devices' port = random.randint(10000, 20000) cfg.distributed_init_method = 'tcp://localho...
class FinalBlock(nn.Module): def __init__(self, input_dim, hidden_units=[], hidden_activations=None, dropout_rates=[], batch_norm=True, residual_type='sum'): super(FinalBlock, self).__init__() if (type(dropout_rates) != list): dropout_rates = ([dropout_rates] * len(hidden_units)) ...
(nopython=True) def create_indices(episode_ends: np.ndarray, sequence_length: int, episode_mask: np.ndarray, pad_before: int=0, pad_after: int=0, debug: bool=True) -> np.ndarray: (episode_mask.shape == episode_ends.shape) pad_before = min(max(pad_before, 0), (sequence_length - 1)) pad_after = min(max(pad_af...
def specify_shape(x: Union[(np.ndarray, Number, Variable)], shape: Union[(ShapeValueType, list[ShapeValueType], tuple[(ShapeValueType, ...)])]): if (not isinstance(shape, (tuple, list))): shape = (shape,) if ((len(shape) == 1) and (shape[0] is not None)): shape_vector = ptb.as_tensor_variable(sh...
.fast def test_slit_energy_conservation(verbose=True, plot=True, close_plots=True, *args, **kwargs): from radis.test.utils import getTestFile _clean(plot, close_plots) if verbose: print('\n>>> _test_slit_energy_conservation\n') s = calculated_spectrum(*np.loadtxt(getTestFile('calc_N2C_spectrum_T...
def get_sde_loss_fn(sde, model, train, reduce_mean=True, continuous=True, likelihood_weighting=True, eps=1e-05): reduce_op = (jnp.mean if reduce_mean else (lambda *args, **kwargs: (0.5 * jnp.sum(*args, **kwargs)))) def loss_fn(rng, params, states, batch): score_fn = mutils.get_score_fn(sde, model, param...
class SystemIrreducibilityAnalysis(cmp.OrderableByPhi): def __init__(self, phi=None, ces=None, partitioned_ces=None, subsystem=None, cut_subsystem=None): self.phi = phi self.ces = ces self.partitioned_ces = partitioned_ces self.subsystem = subsystem self.cut_subsystem = cut_s...
class _BertWordPieceTokenizer(AbstractTokenizer): def __init__(self, vocab_file, lower_case=True): if lower_case: name = 'BERT Lower Case' else: name = 'BERT Upper Case' super().__init__(name) self.tokenizer = FullBertTokenizer(vocab_file, do_lower_case=lower_...
class TestHook(): def test_unknown(self, isolation): metadata = ProjectMetadata(str(isolation), PluginManager(), {'project': {'name': 'foo'}, 'tool': {'hatch': {'metadata': {'hooks': {'foo': {}}}}}}) with pytest.raises(ValueError, match='Unknown metadata hook: foo'): _ = metadata.core ...
_model def test_ic_expression_with_one_parameter(): Monomer('A') Parameter('k1', 1) Expression('e1', k1) Rule('A_deg', (A() >> None), k1) Initial(A(), e1) generate_equations(model) t = np.linspace(0, 1000, 100) sol = Solver(model, t, use_analytic_jacobian=True) sol.run()
def get_extensions(): ext_dirs = ((cwd / package_name) / 'cpp_exts') ext_modules = [] rans_lib_dir = (cwd / 'third_party/ryg_rans') rans_ext_dir = (ext_dirs / 'rans') extra_compile_args = ['-std=c++17'] if os.getenv('DEBUG_BUILD', None): extra_compile_args += ['-O0', '-g', '-UNDEBUG'] ...
class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__init__() def init_weights(self, init_type='normal', gain=0.02, bias_value=0.0, target_op=None): def init_func(m): classname = m.__class__.__name__ if (target_op is not None): if (...
def onresource(unit, *args): def split(lst, limit): root_lenght = 200 filepath = None lenght = 0 bucket = [] for item in lst: if filepath: lenght += ((root_lenght + len(filepath)) + len(item)) if ((lenght > limit) and bucket): ...
class DistanceCondition(_EntityTriggerType): def __init__(self, value, rule, position, alongroute=True, freespace=True, distance_type=RelativeDistanceType.longitudinal, coordinate_system=CoordinateSystem.road, routing_algorithm=None): self.value = value self.alongroute = convert_bool(alongroute) ...
def vk_request_one_param_pool(vk_session, method, key, values, default_values=None): result = {} errors = {} if (default_values is None): default_values = {} for i in range(0, len(values), 25): current_values = values[i:(i + 25)] response_raw = vk_one_param(vk_session, method, cu...
class Distribution(metaclass=abc.ABCMeta): def read_text(self, filename): def locate_file(self, path): def from_name(cls, name: str): if (not name): raise ValueError('A distribution name is required.') try: return next(cls.discover(name=name)) except StopItera...
def _derive_metrics(df: pd.DataFrame) -> pd.DataFrame: logger.info('Deriving metrics...') df['workflow_number'] = df.apply((lambda row: _get_workflow_number_from_name(row['name'])), axis=1) def _calculate_difference(row: pd.Series, start_column: str, end_column: str) -> Optional[int]: start_date = r...
class LocalScoreClass(object): def __init__(self, data: Any, local_score_fun: Callable[([Any, int, List[int], Any], float)], parameters=None): self.data = data self.local_score_fun = local_score_fun self.parameters = parameters self.score_cache = {} if (self.local_score_fun =...
def pad(x: Tensor, p: int=(2 ** (4 + 3))) -> Tuple[(Tensor, Tuple[(int, ...)])]: (h, w) = (x.size(2), x.size(3)) new_h = ((((h + p) - 1) // p) * p) new_w = ((((w + p) - 1) // p) * p) padding_left = ((new_w - w) // 2) padding_right = ((new_w - w) - padding_left) padding_top = ((new_h - h) // 2) ...
class DAM_Module(nn.Module): def __init__(self, in_dim): super(DAM_Module, self).__init__() self.chanel_in = in_dim self.gamma = nn.Parameter(torch.zeros(1)) self.softmax = nn.Softmax(dim=(- 1)) def forward(self, x): (m_batchsize, N, C, height, width) = x.size() p...
.end_to_end() .parametrize(('depends_on', 'produces'), [("'in.txt'", "'out.txt'"), ("Path('in.txt')", "Path('out.txt')")]) def test_collect_file_with_relative_path(tmp_path, depends_on, produces): source = f''' import pytask from pathlib import Path .depends_on({depends_on}) .produces({produces}) ...
class ServerWatch(pypilotValue): def __init__(self, values): super(ServerWatch, self).__init__(values, 'watch') def set(self, msg, connection): (name, data) = msg.rstrip().split('=', 1) watches = pyjson.loads(data) values = self.server_values.values for name in watches: ...
class F17_LogVolData(F15_LogVolData): removedKeywords = F15_LogVolData.removedKeywords removedAttrs = F15_LogVolData.removedAttrs def __init__(self, *args, **kwargs): F15_LogVolData.__init__(self, *args, **kwargs) self.resize = kwargs.get('resize', False) def _getArgsAsStr(self): ...
class AsciiContainer(Container): widget_layout_map = None def __init__(self, *args, **kwargs): Container.__init__(self, *args, **kwargs) self.css_position = 'relative' def set_from_asciiart(self, asciipattern, gap_horizontal=0, gap_vertical=0): pattern_rows = asciipattern.split('\n')...
def genee_loop_chunk(args, chunk_window_starts, chunk_window_stops, abs_chunk_start, chunk_max_window_start, epsilon_effect): (betas, ld) = args rows = list() for ti in range(len(chunk_window_starts)): window_start = chunk_window_starts[ti] window_stop = chunk_window_stops[ti] rows.a...
class AdaptiveRelativeAttn(nn.Module): def __init__(self, model_size, num_heads, factor_size, dropout=0.0, adaptive_type='shared'): super().__init__() self.model_size = model_size self.num_heads = num_heads self.dropout = dropout self.head_dim = (model_size // num_heads) ...
_module() class ResNet(BaseModule): arch_settings = {18: (BasicBlock, (2, 2, 2, 2)), 34: (BasicBlock, (3, 4, 6, 3)), 50: (Bottleneck, (3, 4, 6, 3)), 101: (Bottleneck, (3, 4, 23, 3)), 152: (Bottleneck, (3, 8, 36, 3))} def __init__(self, depth, in_channels=3, stem_channels=64, base_channels=64, num_stages=4, stri...
def parse_mmit_splits(): def line_to_map(x): video = osp.splitext(x[0])[0] labels = [int(digit) for digit in x[1:]] return (video, labels) csv_reader = csv.reader(open('data/mmit/annotations/trainingSet.csv')) train_list = [line_to_map(x) for x in csv_reader] csv_reader = csv.rea...
class Solution(object): def sortedSquares(self, A): pos = 0 while ((pos < len(A)) and (A[pos] < 0)): pos += 1 npos = (pos - 1) res = [] while ((pos < len(A)) and (npos >= 0)): if ((A[npos] ** 2) < (A[pos] ** 2)): res.append((A[npos] ** ...
def test_r2plus1d(): config = get_recognizer_cfg('r2plus1d/r2plus1d_r34_8x8x1_180e_kinetics400_rgb.py') config.model['backbone']['pretrained2d'] = False config.model['backbone']['pretrained'] = None config.model['backbone']['norm_cfg'] = dict(type='BN3d') recognizer = build_recognizer(config.model) ...