code
stringlengths
281
23.7M
def main(): scene = SceneManager.AddScene('Scene') scene.gameObjects[1].GetComponent(Light).type = LightType.Point scene.mainCamera.transform.position = Vector3(0, 3, (- 10)) lookAt = scene.mainCamera.AddComponent(LookAt) cube = GameObject('Cube') renderer = cube.AddComponent(MeshRenderer) r...
_start_docstrings('The bare RegNet model outputting raw features without any specific head on top.', REGNET_START_DOCSTRING) class TFRegNetModel(TFRegNetPreTrainedModel): def __init__(self, config: RegNetConfig, *inputs, **kwargs): super().__init__(config, *inputs, **kwargs) self.regnet = TFRegNetMa...
class ForIterable(ForGenerator): def need_cleanup(self) -> bool: return True def init(self, expr_reg: Value, target_type: RType) -> None: builder = self.builder iter_reg = builder.call_c(iter_op, [expr_reg], self.line) builder.maybe_spill(expr_reg) self.iter_target = buil...
def main(): parser = ArgumentParser() parser.add_argument('-c', '--config', type=Path, required=True) parser.add_argument('-o', '--output_folder', type=Path, required=True) parser.add_argument('-n', '--num_seqs', type=int, required=True) parser.add_argument('-s', '--name_prefix', type=str, default='...
class OnnxSeq2SeqConfigWithPast(OnnxConfigWithPast): def outputs(self) -> Mapping[(str, Mapping[(int, str)])]: common_outputs = super(OnnxConfigWithPast, self).outputs for (name, axes_names) in common_outputs.items(): sequence_name = ('encoder_sequence' if ('encoder' in name) else 'decod...
def test_tracker_diverges(): box = np.array([0, 0, 10, 10]) mot = MultiObjectTracker(dt=0.1) mot.step([Detection(box=box)]) assert (len(mot.trackers) == 1) first_track_id = mot.active_tracks()[0].id assert_almost_equal(mot.trackers[0].model.dt, 0.1) assert (not mot.trackers[0].is_invalid()) ...
_fixtures(WebFixture) def test_dropdown_menu_with_header(web_fixture): sub_menu = DropdownMenu(web_fixture.view) my_header = H(web_fixture.view, 6, text='My header text') header = sub_menu.add_header(my_header) assert (header is my_header) [header] = sub_menu.html_representation.children assert ...
.parametrize(('line', 'expected_warnings'), [('Governance', set()), ('Packaging', set()), ('Typing', set()), ('Release', set()), ('Governance, Packaging', set()), ('Packaging, Typing', set()), ('Governance, Governance', {'duplicates'}), ('Release, Release', {'duplicates'}), ('Packaging, Packaging', {'duplicates'}), ('S...
class Solution(object): def generateParenthesis(self, n): if (n == 1): return ['()'] last_list = self.generateParenthesis((n - 1)) res = [] for t in last_list: curr = (t + ')') for index in range(len(curr)): if (curr[index] == ')'):...
.end_to_end() def test_collapsing_of_warnings(tmp_path, runner): source = '\n import warnings\n from pytask import task\n\n for i in range(6):\n\n \n def task_example():\n warnings.warn("Warning", category=UserWarning)\n ' tmp_path.joinpath('task_example.py').write_text(text...
(scope='session') def gitlab_runner(gl): container = 'gitlab-runner-test' runner_name = 'python-gitlab-runner' token = 'registration-token' url = ' docker_exec = ['docker', 'exec', container, 'gitlab-runner'] register = ['register', '--run-untagged', '--non-interactive', '--registration-token', ...
class PdfTextSearcher(pdfium_i.AutoCloseable): def __init__(self, raw, textpage): self.raw = raw self.textpage = textpage super().__init__(pdfium_c.FPDFText_FindClose) def parent(self): return self.textpage def _get_occurrence(self, find_func): ok = find_func(self) ...
class TrainLoopDLT(): def __init__(self, accelerator: Accelerator, model, diffusion: JointDiffusionScheduler, train_data, val_data, opt_conf, log_interval: int, save_interval: int, categories_num: int, device: str='cpu', resume_from_checkpoint: str=None): self.categories_num = categories_num self.tr...
def eval_with_funcs(predictors, nr_eval, get_player_fn): class Worker(StoppableThread, ShareSessionThread): def __init__(self, func, queue): super(Worker, self).__init__() self.func = func self.q = queue def run(self): with self.default_sess(): ...
def infer_tests_to_run(output_file, diff_with_last_commit=False, filters=None, json_output_file=None): modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit) print(f''' ### MODIFIED FILES ### {_print_list(modified_files)}''') impacted_modules_map = create_reverse_dependency_...
class RDKit(): def mol_to_file(rdkit_mol: Chem.Mol, file_name: str) -> None: file_path = Path(file_name) if (file_path.suffix == '.pdb'): return Chem.MolToPDBFile(rdkit_mol, file_name) elif ((file_path.suffix == '.sdf') or (file_path.suffix == '.mol')): return Chem.Mo...
class _XyzTileServiceNonEarth(_XyzTileService): def __call__(self, *args, **kwargs): _log.info(f"EOmaps: The WebMap service '{self.name}' shows images from a different celestrial body projected to an earth-based crs! Units used in scalebars, geod_crices etc. represent earth-based units!") super().__...
class SceneModel(QtCore.QObject): sigSceneModelChanged = QtCore.pyqtSignal(object) sigSceneChanged = QtCore.pyqtSignal() sigConfigChanged = QtCore.pyqtSignal() sigFrameChanged = QtCore.pyqtSignal() sigQuadtreeChanged = QtCore.pyqtSignal() _sigQuadtreeChanged = QtCore.pyqtSignal() sigQuadtree...
class Xpub(MasterPublicKeyMixin): def __init__(self, *, derivation_prefix: str=None, root_fingerprint: str=None): self.xpub = None self.xpub_receive = None self.xpub_change = None self._xpub_bip32_node = None self._derivation_prefix = derivation_prefix self._root_fing...
class SawyerDoorUnlockV1Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'lock_pos': obs[3:6], 'unused_info': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3}) action['d...
def test_commonpath() -> None: path = Path('/foo/bar/baz/path') subpath = (path / 'sampledir') assert (commonpath(path, subpath) == path) assert (commonpath(subpath, path) == path) assert (commonpath(Path((str(path) + 'suffix')), path) == path.parent) assert (commonpath(path, path.parent.parent)...
def test_entrypoint_injection(pytester, monkeypatch): (pytester.path / 'test_one.py').write_text('def test_one(): pass\n') class _FakeEntryPoint(): def __init__(self, name: str, obj: mock.Mock) -> None: self.name = name self._obj = obj def load(self) -> mock.Mock: ...
class Command(BaseCommand): def handle(self, *args, **options): if (len(args) != 2): raise CommandError('Usage: python manage.py fill_data <in_file> <out_file>') (in_file, out_file) = args ticket_nums = [line.rstrip('\n') for line in open(in_file).readlines()] fh = open(o...
.dask_deserialize.register(ProxyObject) .cuda.cuda_deserialize.register(ProxyObject) def obj_pxy_dask_deserialize(header, frames): args = pickle.loads(header['obj-pxy-detail']) if (args['subclass'] is None): subclass = ProxyObject else: subclass = pickle.loads(args['subclass']) pxy = Pro...
class Bruggeman(BaseModel): def __init__(self, param, component, options=None): super().__init__(param, component, options=options) def get_coupled_variables(self, variables): if (self.component == 'Electrolyte'): tor_dict = {} for domain in self.options.whole_cell_domain...
def reformat_to_coco(predictions: List[str], ground_truths: List[List[str]], ids: Union[(List[int], None)]=None) -> Tuple[(List[Dict[(str, Any)]], Dict[(str, Any)])]: if (ids is None): ids = range(len(predictions)) pred = [] ref = {'info': {'description': 'Clotho reference captions (2019)'}, 'audio ...
class VersionCommand(Command): name = 'version' description = 'Shows the version of the project or bumps it when a valid bump rule is provided.' arguments = [argument('version', 'The version number or the rule to update the version.', optional=True)] options = [option('short', 's', 'Output the version n...
class TestGetProvider(SetUpTest, TestCase): def test_get_provider_should_succeed(self): with open(self.qlr_file) as f: self.assertEqual(get_provider(f), 'wms') def test_get_provider_should_return_none(self): tf = NamedTemporaryFile(mode='w+t', suffix='.qlr') tf.write('<!DOCTY...
def eth_nodes_configuration(blockchain_number_of_nodes, blockchain_key_seed, port_generator, blockchain_type, blockchain_extra_config) -> List[EthNodeDescription]: eth_nodes = [] for position in range(blockchain_number_of_nodes): key = keccak(blockchain_key_seed.format(position).encode()) eth_no...
class TestStat(unittest.TestCase): def test_silent_file(self): expected = {'Samples read': 627456, 'Length (seconds)': 14.228027, 'Scaled by': .0, 'Maximum amplitude': 0.010895, 'Minimum amplitude': (- 0.004883), 'Midline amplitude': 0.003006, 'Mean norm': 0.000137, 'Mean amplitude': (- 6.2e-05), 'RMS...
def test_cancel_merge_when_pipeline_succeeds(project, merge_request_with_pipeline, wait_for_sidekiq): wait_for_sidekiq(timeout=60) merge_request_with_pipeline.merge(merge_when_pipeline_succeeds=True) wait_for_sidekiq(timeout=60) mr = project.mergerequests.get(merge_request_with_pipeline.iid) assert ...
class F_RandomProj(nn.Module): def __init__(self, backbone, loops_type=None, model_path=None, im_res=256, cout=64, expand=True, proj_type=2, **kwargs): super().__init__() self.proj_type = proj_type self.backbone = backbone self.loops_type = loops_type self.cout = cout ...
def _remove_dup_initializers_from_model(model, model_without_ext, ind_to_replace): inits_with_data = list(model.graph.initializer) inits = list(model_without_ext.graph.initializer) for (i, ref_i) in ind_to_replace: assert (inits_with_data[i].name == inits[i].name) assert (inits_with_data[ref...
def l2_afa_schema(settings=None): settings = (settings or {}) npix = settings.get('num_pixels', 120) nacc = settings.get('num_accumulations', 20) return {'providers': settings.get('providers', {}), 'variable_path': settings.get('variable_path', ''), 'dimensions': accumulation_dimensions(nacc, npix), 'va...
def rtn_fwrite(se: 'SymbolicExecutor', pstate: 'ProcessState'): logger.debug('fwrite hooked') arg0 = pstate.get_argument_value(0) arg1 = pstate.get_argument_value(1) arg2 = pstate.get_argument_value(2) arg3 = pstate.get_argument_value(3) size = (arg1 * arg2) data = pstate.memory.read(arg0, s...
def _test(): import torch pretrained = False models = [(rir_cifar10, 10), (rir_cifar100, 100), (rir_svhn, 10)] for (model, num_classes) in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_...
.parametrize('input_type', [(lambda x: x[0]), tuple, list]) def test_run_model_from_effective_irradiance(sapm_dc_snl_ac_system, location, weather, total_irrad, input_type): data = weather.copy() data[['poa_global', 'poa_diffuse', 'poa_direct']] = total_irrad data['effective_irradiance'] = data['poa_global']...
class SawyerFaucetOpenEnvV2(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, (- 0.15)) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.05), 0.8, 0.0) obj_high = (0.05, 0.85, 0.0) self._handle_length = 0.175 self._target_radius = 0.07 super().__init__(sel...
def get_config(args, logger=None): if args.resume: cfg_path = os.path.join(args.experiment_path, 'config.yaml') if (not os.path.exists(cfg_path)): print_log('Failed to resume', logger=logger) raise FileNotFoundError() print_log(f'Resume yaml from {cfg_path}', logger=l...
class RedundantAssignmentChecker(BaseChecker): name = 'redundant_assignment' msgs = {'E9959': ('This assignment statement is redundant; You can remove it from the program.', 'redundant-assignment', 'This assignment statement is redundant; You can remove it from the program.')} def __init__(self, linter=None...
def sphinx_built_file(test_dir, test_file): os.chdir('tests/{0}'.format(test_dir)) try: app = Sphinx(srcdir='.', confdir='.', outdir='_build/text', doctreedir='_build/.doctrees', buildername='html', verbosity=1) app.build(force_all=True) with io.open(test_file, encoding='utf-8') as fin: ...
class DataTrainingArguments(): data_dir: str = field(metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'}) labels: Optional[str] = field(default=None, metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'}) ...
def singleton(cls): (cls) def wrapper_singleton(*args, **kwargs): if (not wrapper_singleton.instance): try: wrapper_singleton.instance = cls(*args, **kwargs) except TypeError: wrapper_singleton.instance = data(cls)(*args, **kwargs) return w...
def besselFilter(data, cutoff, order=1, dt=None, btype='low', bidir=True): try: import scipy.signal except ImportError: raise Exception('besselFilter() requires the package scipy.signal.') if (dt is None): try: tvals = data.xvals('Time') dt = ((tvals[(- 1)] - ...
class TestAtmosphere(): def test_standard_atmosphere(self): a = Atmosphere() assert (a.temperature == 293.15) assert (a.pressure == 101.325) assert (a.relative_humidity == 0.0) assert (abs((a.soundspeed - 343.2)) < 1e-09) assert (abs((a.saturation_pressure - 2.)) < 1e...
def cnn_decoder(lstm1_out, lstm2_out, lstm3_out, lstm4_out): d_filter4 = tensor_variable([2, 2, 128, 256], 'd_filter4') dec4 = cnn_decoder_layer(lstm4_out, d_filter4, [1, 8, 8, 128], (1, 2, 2, 1)) dec4_concat = tf.concat([dec4, lstm3_out], axis=3) d_filter3 = tensor_variable([2, 2, 64, 256], 'd_filter3'...
_model def caformer_b36_in21k(pretrained=False, **kwargs): model = MetaFormer(depths=[3, 12, 18, 3], dims=[128, 256, 512, 768], token_mixers=[SepConv, SepConv, Attention, Attention], head_fn=MlpHead, **kwargs) model.default_cfg = default_cfgs['caformer_b36_in21k'] if pretrained: state_dict = torch.h...
class TestHome(): def test_default(self): actual = pystiche.home() desired = path.expanduser(path.join('~', '.cache', 'pystiche')) assert (actual == desired) def test_env(self): tmp_dir = tempfile.mkdtemp() pystiche_home = os.getenv('PYSTICHE_HOME') os.environ['PY...
_BBOX_CODERS.register_module() class CSLCoder(BaseBBoxCoder): def __init__(self, angle_version, omega=1, window='gaussian', radius=6): super().__init__() self.angle_version = angle_version assert (angle_version in ['oc', 'le90', 'le135']) assert (window in ['gaussian', 'triangle', 'r...
class JuliaLexer(RegexLexer): name = 'Julia' url = ' aliases = ['julia', 'jl'] filenames = ['*.jl'] mimetypes = ['text/x-julia', 'application/x-julia'] version_added = '1.6' tokens = {'root': [('\\n', Whitespace), ('[^\\S\\n]+', Whitespace), ('#=', Comment.Multiline, 'blockcomment'), ('#.*$'...
def test_commented_extension(monkeypatch): config = {'comment': ['--option'], 'ignore': []} monkeypatch.setattr(interactive, 'get_config', (lambda x: config[x])) parser = ArgumentParser() fake_extension = Mock(flag='--option') action = parser.add_argument('--option', dest='extensions', action='appen...
def print_cuda_usage(): print('Memory Allocated:', (torch.cuda.memory_allocated() / (1024 * 1024))) print('Max Memory Allocated:', (torch.cuda.max_memory_allocated() / (1024 * 1024))) print('Memory Cached:', (torch.cuda.memory_cached() / (1024 * 1024))) print('Max Memory Cached:', (torch.cuda.max_memory...
class CifarPairTransform(): def __init__(self, train_transform=True, pair_transform=True): if (train_transform is True): self.transform = transforms.Compose([transforms.RandomResizedCrop(32), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomApply([transforms.ColorJitter(0.4, 0.4, 0.4, 0....
.skipif((not is_py310_plus), reason='3.10+ union syntax') (simple_typed_classes(defaults=False)) def test_310_optional_field_roundtrip(cl_and_vals): converter = Converter() (cl, vals, kwargs) = cl_and_vals class C(): a: (cl | None) inst = C(a=cl(*vals, **kwargs)) assert (inst == converter.st...
def a2c_train_step(agent, abstractor, loader, opt, grad_fn, gamma=0.99, reward_fn=compute_rouge_l, stop_reward_fn=compute_rouge_n(n=1), stop_coeff=1.0): opt.zero_grad() indices = [] probs = [] baselines = [] ext_sents = [] (art_batch, abs_batch) = next(loader) for raw_arts in art_batch: ...
def test_nested_start_rc(): checker = StackEndRC([AnyRequestChecker(), StackEndRC([create_request_checker(bool), create_request_checker(int), create_request_checker(str)]), create_request_checker(bool)]) checker.check_request(create_mediator(LocatedRequest(loc_map=LocMap(TypeHintLoc(bool))), LocatedRequest(loc_...
.parametrize(**test_case_table) def test_2port(test_params, cmdline_opts): msgs0 = test_params.msg_func(4096) msgs1 = test_params.msg_func(8192) run_sim(TestHarness(MagicMemoryRTL, 2, ([(req_cls, resp_cls)] * 2), [msgs0[::2], msgs1[::2]], [msgs0[1::2], msgs1[1::2]], test_params.stall, test_params.extra_lat,...
def run_louvain_multilayer(intralayer_graph, interlayer_graph, layer_vec, weight='weight', resolution=1.0, omega=1.0, nruns=1): logging.debug('Shuffling node ids') t = time() mu = (np.sum(intralayer_graph.es[weight]) + interlayer_graph.ecount()) use_RBCweighted = hasattr(louvain, 'RBConfigurationVertexP...
def test_solvers(): cnf = CNF(from_clauses=[[1, 2, 3], [(- 1), 2], [(- 2)]]) for name in solvers: with Solver(name=name, bootstrap_with=cnf) as solver: assert solver.solve(), 'wrong outcome by {0}'.format(name) assert (solver.get_model() == [(- 1), (- 2), 3]), 'wrong model by {0}...
class EigenstateResult(AlgorithmResult): def eigenenergies(self) -> Optional[np.ndarray]: return self.get('eigenenergies') def eigenenergies(self, value: np.ndarray) -> None: self.data['eigenenergies'] = value def eigenstates(self) -> Optional[List[Union[(str, dict, Result, list, np.ndarray,...
class SawyerBoxCloseEnv(SawyerXYZEnv): def __init__(self): liftThresh = 0.12 goal_low = ((- 0.1), 0.85, 0.1329) goal_high = (0.1, 0.95, 0.1331) hand_low = ((- 0.5), 0.4, 0.05) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.05), 0.55, 0.02) obj_high = (0.05, 0.6, 0....
class DataCollator(): pad_id: int max_length: int = 4096 def __call__(self, batch): batch = self.collate_fn(batch) batch = jax.tree_util.tree_map(shard, batch) return batch def collate_fn(self, features): (input_ids, attention_mask) = self.fetch_inputs(features['input_ids...
def test_receive_order_paid_of_period_outside_current_one(requests_mock): user = UserFactory(email='') with time_machine.travel('2023-12-16 01:04:50Z', tick=False): requests_mock.get(f'{settings.PRETIX_API}organizers/test-organizer/events/local-conf-test/orders/9YKZK/', json=ORDER_DATA_WITH_MEMBERSHIP) ...
class NonLocal2D(nn.Module): def __init__(self, in_channels, reduction=2, use_scale=True, conv_cfg=None, norm_cfg=None, mode='embedded_gaussian'): super(NonLocal2D, self).__init__() self.in_channels = in_channels self.reduction = reduction self.use_scale = use_scale self.inte...
def check_imports(filename): with open(filename, 'r', encoding='utf-8') as f: content = f.read() imports = re.findall('^\\s*import\\s+(\\S+)\\s*$', content, flags=re.MULTILINE) imports += re.findall('^\\s*from\\s+(\\S+)\\s+import', content, flags=re.MULTILINE) imports = [imp.split('.')[0] for im...
(Gst, 'GStreamer missing') class TGStreamerSink(TestCase): def test_simple(self): sinks = ['gconfaudiosink', 'alsasink'] for n in filter(Gst.ElementFactory.find, sinks): (obj, name) = gstreamer_sink(n) self.assertTrue(obj) self.assertEqual(name, n) def test_in...
def main(args, override_args=None): utils.import_user_module(args) assert ((args.max_tokens is not None) or (args.batch_size is not None)), 'Must specify batch size either with --max-tokens or --batch-size' use_fp16 = args.fp16 use_cuda = (torch.cuda.is_available() and (not args.cpu)) if use_cuda: ...
class TestHeaderInclusion(unittest.TestCase): def test_primitives_included_in_header(self) -> None: base_dir = os.path.join(os.path.dirname(__file__), '..', 'lib-rt') with open(os.path.join(base_dir, 'CPy.h')) as f: header = f.read() with open(os.path.join(base_dir, 'pythonsuppor...
class TextEncoder(tf.keras.Model): def __init__(self, strategy, trainable=False): self.strategy = strategy with self.strategy.scope(): super(TextEncoder, self).__init__() self.encoder = hub.KerasLayer(' trainable=trainable) def __call__(self, inp): with self.strat...
def structure(t, fieldproc=unescape): d = {} if (t[0] is not None): d['scheme'] = t[0] if (t[1] is not None): uphp = split_netloc(t[1], fieldproc=fieldproc) if (uphp[0] is not None): d['user'] = uphp[0] if (uphp[1] is not None): d['password'] = uphp[1]...
def get_config(path: str) -> Dict[(str, RepositoryConfig)]: realpath = os.path.realpath(os.path.expanduser(path)) parser = configparser.RawConfigParser() try: with open(realpath) as f: parser.read_file(f) logger.info(f'Using configuration from {realpath}') except FileNotF...
def _datetime_offset_inst(obj: str, pattern: str) -> datetime: (dat_str, tim_str) = obj.split('T') (splitter, factor) = (('+', 1) if ('+' in tim_str) else ('-', (- 1))) (naive_tim_str, offset) = tim_str.split(splitter) naive_dattim_str = '{}T{}'.format(dat_str, naive_tim_str) dattim_obj = datetime.s...
def create_model(model_name: str, pretrained: Optional[str]=None, precision: str='fp32', device: Union[(str, torch.device)]='cpu', jit: bool=False, force_quick_gelu: bool=False, force_custom_clip: bool=False, force_patch_dropout: Optional[float]=None, pretrained_image: str='', pretrained_text: str='', pretrained_hf: bo...
def train_epoch(gpu, train_loader, model, base_optimizer, epoch, args, lr_scheduler=None, grad_rho_scheduler=None, grad_norm_rho_scheduler=None, optimizer=None): losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') Lr = AverageMeter('Lr', ':.4e') progress = ProgressMeter(len(train_load...
_required def plugin_update(request, package_name): plugin = get_object_or_404(Plugin, package_name=package_name) if (not check_plugin_access(request.user, plugin)): return render(request, 'plugins/plugin_permission_deny.html', {}) if (request.method == 'POST'): form = PluginForm(request.POS...
def get_examples(path, sub_sample_train=3000, sub_sample_eval=256): with open(path) as f: raw_dataset = json.load(f) positive_examples = raw_dataset['Positive Examples'] negative_examples = raw_dataset['Negative Examples'] all_examples = raw_dataset['Instances'] n = len(all_examples) eva...
class CustomJsonFormatter(jsonlogger.JsonFormatter): service_name = '' tracer = '' def add_fields(self, log_record, record, message_dict): super().add_fields(log_record, record, message_dict) if (not log_record.get('timestamp')): now = datetime.datetime.utcnow().strftime('%Y-%m-%...
def parse_extension_item_param(header: str, pos: int, header_name: str) -> Tuple[(ExtensionParameter, int)]: (name, pos) = parse_token(header, pos, header_name) pos = parse_OWS(header, pos) value: Optional[str] = None if (peek_ahead(header, pos) == '='): pos = parse_OWS(header, (pos + 1)) ...
def init_visualization(argument): if isinstance(argument, Eigenstates): eigenstates = argument return init_eigenstate_visualization(eigenstates) elif isinstance(argument, TimeSimulation): simulation = argument return init_timesimulation_visualization(simulation)
class InstrumentDumpFetch(): def __init__(self): self.conn = redis.StrictRedis(host='localhost', port=6379) def data_dump(self, symbol, instrument_data): self.conn.set(symbol, json.dumps(instrument_data)) def symbol_data(self, symbol): try: contract_detail = json.loads(se...
def get_dataset(data_args: argparse.Namespace, processor: Union[(Union[(PyGameTextRenderer, PangoCairoTextRenderer)], PreTrainedTokenizerFast)], modality: Modality, split: Split, config: PretrainedConfig): if (modality == Modality.IMAGE): transforms = get_transforms(do_resize=True, size=(processor.pixels_pe...
def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None: typ.is_abstract = False typ.abstract_attributes = [] if typ.typeddict_type: return concrete: set[str] = set() abstract: list[tuple[(str, int)]] = [] abstract_in_this_class: list[str] = [] ...
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, environ, blotter, benchmark_spec): bundle_data = bundles.load(bundle, environ, bundle_...
class UVCCSD(UVCC): def __init__(self, num_modals: (list[int] | None)=None, qubit_mapper: (QubitMapper | None)=None, *, reps: int=1, initial_state: (QuantumCircuit | None)=None) -> None: super().__init__(num_modals=num_modals, excitations='sd', qubit_mapper=qubit_mapper, reps=reps, initial_state=initial_sta...
def finite_loss(ival: Interval, loss: float, x_scale: float) -> tuple[(float, Interval)]: if (math.isinf(loss) or math.isnan(loss)): loss = ((ival[1] - ival[0]) / x_scale) if (len(ival) == 3): loss /= ival[2] round_fac = .0 loss = (int(((loss * round_fac) + 0.5)) / round_fac) ...
class TestVehicleRouting(QiskitOptimizationTestCase): def setUp(self): super().setUp() random.seed(600) low = 0 high = 100 pos = {i: (random.randint(low, high), random.randint(low, high)) for i in range(4)} self.graph = nx.random_geometric_graph(4, (np.hypot((high - l...
_canonicalize _specialize _rewriter([AdvancedSubtensor1]) def local_adv_sub1_adv_inc_sub1(fgraph, node): if (not isinstance(node.op, AdvancedSubtensor1)): return inp = node.inputs[0] if ((not inp.owner) or (not isinstance(inp.owner.op, AdvancedIncSubtensor1))): return idx = node.inputs[1...
def test_apply_along_last_axis(): _along_last_axis def f(x): assert (x.ndim == 1) return (x[:(len(x) // 2)] + np.arange((len(x) // 2))) for shape in [(10,), (2, 10), (2, 2, 10)]: x = np.ones(shape) y = f(x) xshape = x.shape yshape = y.shape assert (len...
def data_collator(features): if (not isinstance(features[0], dict)): features = [vars(f) for f in features] first = features[0] batch = {} if (('label' in first) and (first['label'] is not None)): label = (first['label'].item() if isinstance(first['label'], torch.Tensor) else first['labe...
class ConvOps(BaseOp): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, transposed=False, depthwised=False, dropout_rate=0, ops_order='weight_norm_act'): super().__init__(in_channels, out_channels, dropout_rate, ops_order) self.depthwised = depthwised paddin...
_bool('is_required_a') def test_extra_extract(debug_ctx, debug_trail, trail_select, is_required_a, acc_schema): dumper_getter = make_dumper_getter(shape=shape(TestField('a', acc_schema.accessor_maker('a', is_required=is_required_a)), TestField('b', acc_schema.accessor_maker('b', is_required=True))), name_layout=Out...
class HIKOM4(FinTS3Segment): bank_identifier = DataElementGroupField(type=BankIdentifier, _d='Kreditinstitutskennung') default_language = CodeField(enum=Language2, max_length=3, _d='Standardsprache') communication_parameters = DataElementGroupField(type=CommunicationParameter2, min_count=1, max_count=9, _d=...
def loadData(datasetStr): DIR = os.path.join(os.getcwd(), 'dataset', datasetStr) log(DIR) with open((DIR + '/train.pkl'), 'rb') as fs: trainMat = pk.load(fs) with open((DIR + '/test_data.pkl'), 'rb') as fs: testData = pk.load(fs) with open((DIR + '/valid_data.pkl'), 'rb') as fs: ...
class Solution(object): def mostCommonWord(self, paragraph, banned): banned = set(banned) count = collections.Counter((word for word in re.split("[ !?',;.]", paragraph.lower()) if word)) return max((item for item in count.items() if (item[0] not in banned)), key=operator.itemgetter(1))[0]
_onnx class OnnxUtilsTestCaseV2(TestCase): _torch ('transformers.onnx.convert.is_torch_onnx_dict_inputs_support_available', return_value=False) def test_ensure_pytorch_version_ge_1_8_0(self, mock_is_torch_onnx_dict_inputs_support_available): self.assertRaises(AssertionError, export, None, None, None...
class Distance2EcmStrMaxGetter(SmoothPointGetter): _baseResolution = 50 _extraDepth = 2 ECM_ATTRS_GENERAL = ('scanGravimetricStrengthBonus', 'scanLadarStrengthBonus', 'scanMagnetometricStrengthBonus', 'scanRadarStrengthBonus') ECM_ATTRS_FIGHTERS = ('fighterAbilityECMStrengthGravimetric', 'fighterAbility...
def validate(gpu, val_loader, model, criterion, test=True, args=None): if test: batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') progress = ProgressMeter(len(val_loader), [batch_...
class AoA_Decoder_Core(nn.Module): def __init__(self, opt): super(AoA_Decoder_Core, self).__init__() self.drop_prob_lm = opt.drop_prob_lm self.d_model = opt.rnn_size self.use_multi_head = opt.use_multi_head self.multi_head_scale = opt.multi_head_scale self.use_ctx_dro...
def recurse_artifacts(artifacts: list, root) -> Iterable[Path]: for raw_artifact in artifacts: artifact = Path(raw_artifact) if (not artifact.is_absolute()): artifact = (root / artifact) if artifact.is_file(): (yield artifact) elif artifact.is_dir(): ...
def test_read_bsrn_logical_records_not_found(): (data, metadata) = read_bsrn((DATA_DIR / 'bsrn-lr0100-pay0616.dat'), logical_records=['0300', '0500']) assert data.empty assert ('uva_global' in data.columns) assert ('uvb_reflected_std' in data.columns) assert ('uva_global_max' in data.columns) as...