code
stringlengths
281
23.7M
def fidelity_circuit(network: Union[(Network_DQNN, Network_QAOA)], state_pair: List[np.ndarray], draw_circ: bool=False) -> QuantumCircuit: (circ, q_reg, c_reg) = init_quantum_circuit(((2 * network.num_qubits) + network.auxillary_qubits), ((2 * network.num_qubits) if (network.fid_meas_method == 'destructive_swap') e...
def cuttree(node, nettree, levl): for i in node.snode: i.pnode.remove(node) for i in node.pnode: i.snode.remove(node) if (node.snode != []): cuttree(node.snode[0], nettree, (levl + 1)) print(((str(levl) + ':') + str(nettree[levl][0].position))) nettree[levl].remove(node)
def verify_logs(directory, filename, mtype, meid): path = '/' file_path = ((directory + path) + filename) f = open(file_path, 'r') for l in f: if (meid is not None): if ((l.find(mtype) > 0) and (l.find(meid) > 0)): return True elif (l.find(mtype) > 0): ...
def register_to_config(init): (init) def inner_init(self, *args, **kwargs): init_kwargs = {k: v for (k, v) in kwargs.items() if (not k.startswith('_'))} init(self, *args, **init_kwargs) if (not isinstance(self, ConfigMixin)): raise RuntimeError(f'`_for_config` was applied to ...
class ObjectEntry(Entry): location: str serializer: str obj_type: str replicated: bool def __init__(self, location: str, serializer: str, obj_type: str, replicated: bool) -> None: super().__init__(type='object') self.location = location self.serializer = serializer se...
def dataloader_didemo_test(args, tokenizer, subset='test'): didemo_testset = DiDeMo_DataLoader(subset=subset, data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames, frame_order=args.eval_frame_o...
def _add_install(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None: p = subparsers.add_parser('install', help='Install a package', formatter_class=LineWrapRawTextHelpFormatter, description=INSTALL_DESCRIPTION, parents=[shared_parser]) p.add_argument('package_spec', help='pa...
class Seq2seqTrainerTester(TestCasePlus): _torch def test_finetune_bert2bert(self): bert2bert = EncoderDecoderModel.from_encoder_decoder_pretrained('prajjwal1/bert-tiny', 'prajjwal1/bert-tiny') tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') bert2bert.config.vocab_size = b...
def console_entry() -> None: try: main() sys.stdout.flush() sys.stderr.flush() except BrokenPipeError: devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) sys.exit(2) except KeyboardInterrupt: (_, options) = process_options...
def same_domain(url1: QUrl, url2: QUrl) -> bool: ensure_valid(url1) ensure_valid(url2) if (url1.scheme() != url2.scheme()): return False if (url1.port() != url2.port()): return False assert machinery.IS_QT5, machinery.INFO suffix1 = url1.topLevelDomain() suffix2 = url2.topLev...
def train_callback(batch_idx, outer_loss, list_out, stats): list_acc = [x[0] for x in list_out] list_ce = [x[1] for x in list_out] acc = np.mean(list_acc) ce = np.mean(list_ce) stats.step(np.array([(acc * len(list_acc)), (ce * len(list_acc))]), n_step=len(list_acc)) msg = ('train batch acc: %.2f...
def _train(params: Dict, dtrain: RayDMatrix, *args, evals=(), ray_params: RayParams, cpus_per_actor: int, gpus_per_actor: int, _training_state: _TrainingState, **kwargs) -> Tuple[(xgb.Booster, Dict, Dict)]: from xgboost_ray.elastic import _get_actor_alive_status, _maybe_schedule_new_actors, _update_scheduled_actor_...
def _as_scalar(res, dtype=None): if (dtype is None): dtype = config.floatX if all(((s == 1) for s in res.type.shape)): while (res.owner and isinstance(res.owner.op, DimShuffle)): res = res.owner.inputs[0] if (res.type.ndim > 0): rval = res.dimshuffle() els...
class BFSCluster(Function): def forward(ctx, semantic_label, ball_query_idxs, start_len, threshold): N = start_len.size(0) assert semantic_label.is_contiguous() assert ball_query_idxs.is_contiguous() assert start_len.is_contiguous() cluster_idxs = semantic_label.new() ...
class TestDiskUsageCollector(CollectorTestCase): def setUp(self): config = get_collector_config('DiskUsageCollector', {'interval': 10, 'sector_size': '512', 'byte_unit': 'kilobyte'}) self.collector = DiskUsageCollector(config, None) def test_config(self): self.assertFalse(self.collector....
def test_get_program_id_3(): circuit = cirq.Circuit(cirq.H(cirq.LineQubit(0))) circuit.program_id = 'my_fancy_var_1/my_fancy_var_2/my_fancy_var_3/my_fancy_var_4/my_fancy_var_5/my_fancy_var_6' assert (len(circuit.program_id) > 64) prog_id = _get_program_id(circuit) assert isinstance(prog_id, str) ...
class AbstractImageSequence(): def get_texture_sequence(self): raise NotImplementedError('abstract') def get_animation(self, period, loop=True): return Animation.from_image_sequence(self, period, loop) def __getitem__(self, slice): raise NotImplementedError('abstract') def __seti...
class GettextLexer(RegexLexer): name = 'Gettext Catalog' aliases = ['pot', 'po'] filenames = ['*.pot', '*.po'] mimetypes = ['application/x-gettext', 'text/x-gettext', 'text/gettext'] url = ' version_added = '0.9' tokens = {'root': [('^#,\\s.*?$', Keyword.Type), ('^#:\\s.*?$', Keyword.Declara...
def main(): filenames = ParseArguments(sys.argv[1:]) remove_filenames = ['include/caffe/3rdparty/hungarian.h', 'src/caffe/3rdparty/hungarian.cpp'] for remove_filename in remove_filenames: if (remove_filename in filenames): filenames.remove(remove_filename) sys.stderr = codecs.StreamR...
class AttrVI_ATTR_MEM_BASE(RangeAttribute): resources = [(constants.InterfaceType.vxi, 'INSTR'), (constants.InterfaceType.vxi, 'SERVANT')] py_name = '' visa_name = 'VI_ATTR_MEM_BASE' visa_type = ('ViBusAddress64' if constants.is_64bits else 'ViUInt32') default = NotAvailable (read, write, local)...
def _cast_to_dtype(data, dtype): dt = _format_dtype(dtype) try: data = np.array(data, dtype=dt) except ValueError as err: try: print('Cant cast data to specific dtype. Trying row by row:') for r in range(len(data)): try: np.array(da...
def test__getting_started__pendulum(): from bioptim.examples.getting_started import pendulum as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/pendulum.bioMod'), final_time=3, n_shooting=100, phase_dynamics=PhaseDynamics.S...
def _execute_compaction_round(source_partition_locator: PartitionLocator, destination_partition_locator: PartitionLocator, primary_keys: Set[str], compaction_artifact_s3_bucket: str, last_stream_position_to_compact: int, hash_bucket_count: Optional[int], sort_keys: List[SortKey], records_per_compacted_file: int, input_...
def read_detections(path, drop_detection_prob: float=0.0, add_detection_noise: float=0.0): path = os.path.expanduser(path) logger.debug(f'reading detections from {path}') if (not os.path.isfile(path)): raise ValueError('file does not exist') df = pd.read_csv(path, names=COL_NAMES) max_frame ...
def download_city(path): _CITY_DOWNLOAD_URLS = [('gtFine_trainvaltest.zip', '99f532cb1af174f5fcc4c5bc8feea8c66246ddbc'), ('leftImg8bit_trainvaltest.zip', '2c0b77ce9933cc635adda307fbba5566f5d9d404')] download_dir = os.path.join(path, 'downloads') mkdir(download_dir) for (filename, checksum) in _CITY_DOWN...
class Scoresheet(BaseScoresheet): def __getitem__(self, key): return BaseScoresheet.__getitem__(self, Pair(key)) def __setitem__(self, key, val): BaseScoresheet.__setitem__(self, Pair(key), float(val)) def __delitem__(self, key): return dict.__delitem__(self, Pair(key)) def proce...
class Tooltip(MacroElement): _template = Template('\n {% macro script(this, kwargs) %}\n {{ this._parent.get_name() }}.bindTooltip(\n `<div{% if this.style %} style={{ this.style|tojson }}{% endif %}>\n {{ this.text }}\n </div>`,\n ...
def test_geodesic_gradient_descent(metric, data_x, data_y, high_rank_x, high_rank_y): if metric.test_high_rank_data: (x, y) = (high_rank_x, high_rank_y) else: (x, y) = (data_x, data_y) (p_x, p_y) = (metric.neural_data_to_point(x), metric.neural_data_to_point(y)) frac = np.random.rand(1)[...
def calculate_fid_given_paths(paths, batch_size, size, length, dims, device): for p in paths: if (not os.path.exists(p)): raise RuntimeError(('Invalid path: %s' % p)) model = nn.DataParallel(resnet101(sample_duration=16).cuda()) model.load_state_dict(torch.load('resnext-101-kinetics.pth'...
_metaclass(Singleton) class IATSPI(object): LIB = 'libatspi' DEFAULT_LIB_NAME = 'libatspi.so' def __get_roles(self): control_types = [] get_role_name = self.atspi.atspi_role_get_name get_role_name.argtypes = [c_int] get_role_name.restype = c_char_p for i in range(ATSP...
def create_logger(root_output_path, cfg, image_set): if (not os.path.exists(root_output_path)): os.makedirs(root_output_path) assert os.path.exists(root_output_path), '{} does not exist'.format(root_output_path) cfg_name = os.path.basename(cfg).split('.')[0] config_output_path = os.path.join(roo...
def solar_position_numba(unixtime, lat, lon, elev, pressure, temp, delta_t, atmos_refract, numthreads, sst=False, esd=False): loc_args = np.array([lat, lon, elev, pressure, temp, delta_t, atmos_refract, sst, esd]) ulength = unixtime.shape[0] if sst: dims = 3 elif esd: dims = 1 else: ...
class TestLoad(BaseTestLoading): def test_load_hvu_label(self): hvu_label_example1 = copy.deepcopy(self.hvu_label_example1) hvu_label_example2 = copy.deepcopy(self.hvu_label_example2) categories = hvu_label_example1['categories'] category_nums = hvu_label_example1['category_nums'] ...
class NormalizePathTest(TestCase): def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/') self.root_name = self.filesystem.root_dir_name def test_empty_path_should_get_normalized_to_root_path(self): self.assertEqual(self.root_name, self.filesystem.absnormpa...
class VNet(MetaModule): def __init__(self, input, hidden1, output): super(VNet, self).__init__() self.linear1 = MetaLinear(input, hidden1) self.relu = nn.ReLU(inplace=True) self.linear2 = MetaLinear(hidden1, output) def forward(self, x): x = self.linear1(x) x = se...
class TestProjectExplicit(): .parametrize('file_name', ['pyproject.toml', 'setup.py']) def test_found_project_flag(self, hatch, temp_dir, config_file, helpers, file_name): project_file = (temp_dir / file_name) project_file.touch() project = 'foo' config_file.model.projects = {pro...
class MaxOrderCount(TradingControl): def __init__(self, on_error, max_count): super(MaxOrderCount, self).__init__(on_error, max_count=max_count) self.orders_placed = 0 self.max_count = max_count self.current_date = None def validate(self, asset, amount, portfolio, algo_datetime, ...
def get_args(): parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description='Symbolizes OP-TEE abort dumps or function graphs', epilog=epilog) parser.add_argument('-d', '--dir', action='append', nargs='+', help='Search for ELF file in DIR. tee.elf is needed to decode a TEE...
class TBMagicTurnHandler(DefaultScript): def at_script_creation(self): self.key = 'Combat Turn Handler' self.interval = 5 self.persistent = True self.db.fighters = [] for thing in self.obj.contents: if thing.db.hp: self.db.fighters.append(thing) ...
class PedestrianMotionType(metaclass=_EnumMeta): standing = _OscEnum('PedestrianMotionType', 'standing', min_minor_version=2) sitting = _OscEnum('PedestrianMotionType', 'sitting', min_minor_version=2) lying = _OscEnum('PedestrianMotionType', 'lying', min_minor_version=2) squatting = _OscEnum('Pedestrian...
def should_do_markup(file: TextIO) -> bool: if (os.environ.get('PY_COLORS') == '1'): return True if (os.environ.get('PY_COLORS') == '0'): return False if os.environ.get('NO_COLOR'): return False if os.environ.get('FORCE_COLOR'): return True return (hasattr(file, 'isat...
class Config(): STATUS_SONGLESS = ('no_song_text', '') PAT_PLAYING = ('playing_pattern', ' <~artist~title> ') PAT_PAUSED = ('paused_pattern', ('<~artist~title> [%s]' % _('paused'))) HOST = ('host', 'localhost') PORT = ('port', 1883) USERNAME = ('username', '') PASSWORD = ('password', '') ...
def agg(raw_items): from collections import OrderedDict agged = OrderedDict() for raw_item in raw_items: prefix = raw_item.split('_')[0] value = '_'.join(raw_item.split('_')[1:]) if (not (prefix in agged.keys())): agged[prefix] = [] agged[prefix].append(value) ...
class RepeatFactorTrainingSampler(Sampler): def __init__(self, repeat_factors, *, shuffle=True, seed=None): self._shuffle = shuffle if (seed is None): seed = comm.shared_random_seed() self._seed = int(seed) self._rank = comm.get_rank() self._world_size = comm.get_...
class Effect11516(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Shield Operation')), 'shieldBonus', ship.getModifiedItemAttr('shipBonusMC'), skill='Minmatar Cruiser', **kwargs)
class HerbertConverter(Converter): def converted(self) -> Tokenizer: tokenizer_info_str = '#version:' token_suffix = '</w>' vocab = self.original_tokenizer.encoder merges = list(self.original_tokenizer.bpe_ranks.keys()) if (tokenizer_info_str in merges[0][0]): mer...
class Vasicek(SPEulerMaruyama): def __init__(self, theta=1.0, mu=3.0, sigma=0.5, initial=1.0, T=1.0, rng=None): super().__init__(T=T, rng=rng) self.theta = theta self.mu = mu self.sigma = sigma self.initial = initial self.n = 1.0 self.dt = ((1.0 * self.T) / se...
class Foo_shamt_list_wrap(Component): def construct(s, nbits=1): s.in_ = InPort(nbits) s.out = [OutPort(nbits) for _ in range(5)] s.inner = [Foo_shamt(i) for i in range(5)] for i in range(5): s.inner[i].in_ //= s.in_ s.inner[i].out //= s.out[i] def line_tr...
class MaxPool2dSame(nn.MaxPool2d): def __init__(self, kernel_size: int, stride=None, padding=0, dilation=1, ceil_mode=False, count_include_pad=True): kernel_size = tuple(repeat(kernel_size, 2)) stride = tuple(repeat(stride, 2)) dilation = tuple(repeat(dilation, 2)) super(MaxPool2dSam...
def compute_intermediate_statistics(smiles, n_jobs=1, device='cpu', batch_size=512, pool=None): close_pool = False if (pool is None): if (n_jobs != 1): pool = Pool(n_jobs) close_pool = True else: pool = 1 statistics = {} mols = mapper(pool)(get_mol, sm...
.needs_connection def test_calc_hitran_spectrum(verbose=True, plot=False, *args, **kwargs): from radis import test_spectrum s = test_spectrum(databank=('hitran', 'full'), name='full range', verbose=verbose) s2 = test_spectrum(databank=('hitran', 'range'), name='partial range', verbose=verbose) if plot: ...
class TypeGuardTests(BaseTestCase): def test_basics(self): TypeGuard[int] self.assertEqual(TypeGuard[int], TypeGuard[int]) def foo(arg) -> TypeGuard[int]: ... self.assertEqual(gth(foo), {'return': TypeGuard[int]}) def test_repr(self): if hasattr(typing, 'TypeG...
class BytesViewTest(unittest.TestCase): def test(self): with self.assertRaises(TypeError): bytesview(text_type('foobar')) data = b'ABCDEF' view = bytesview(data) self.assertEqual(len(view), 16) self.assertEqual(view[:], data) self.assertIsInstance(view[:],...
_rewriter(tracks=[Scan]) def transform_scan_values(fgraph: FunctionGraph, node: Apply) -> Optional[list[Apply]]: rv_map_feature: Optional[PreserveRVMappings] = getattr(fgraph, 'preserve_rv_mappings', None) values_to_transforms: Optional[TransformValuesMapping] = getattr(fgraph, 'values_to_transforms', None) ...
def to_tpb_grouped_weighted_pauli_operator(operator: Union[(WeightedPauliOperator, TPBGroupedWeightedPauliOperator, MatrixOperator)], grouping_func: Callable, **kwargs: int) -> TPBGroupedWeightedPauliOperator: if (operator.__class__ == WeightedPauliOperator): return grouping_func(operator, **kwargs) eli...
class ModelWithReusedNodes(nn.Module): def __init__(self): super(ModelWithReusedNodes, self).__init__() self.conv1 = nn.Conv2d(3, 8, kernel_size=2, stride=2, padding=2, bias=False) self.bn1 = nn.BatchNorm2d(8) self.relu1 = nn.ReLU(inplace=True) self.relu2 = nn.ReLU(inplace=Tr...
class EntitySummary(Base, Timestamp): __tablename__ = 'stats_entity_summaries' __table_args__ = (UniqueConstraint('name', 'year', 'month', name='uniq_key'),) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.String(128), nullable=False) count = sa.Column(sa.Integer...
('pypyr.moduleloader.get_module') (Step, 'invoke_step') def test_run_pipeline_steps_complex_with_run_99_true(mock_invoke_step, mock_get_module): step = Step({'name': 'step1', 'run': 99}) context = get_test_context() original_len = len(context) with patch_logger('pypyr.dsl', logging.DEBUG) as mock_logger...
def test_kinesis_logs_producers(logs_model, mock_elasticsearch, mock_db_model, kinesis_logs_producer_config): mock_elasticsearch.template = Mock(return_value=DEFAULT_TEMPLATE_RESPONSE) producer_config = kinesis_logs_producer_config with patch('botocore.endpoint.EndpointCreator.create_endpoint'), patch('boto...
class SitExecutor(ActionExecutor): _MAX_OCCUPANCIES = {'couch': 4, 'bed': 4, 'chair': 1, 'loveseat': 2, 'sofa': 4, 'toilet': 1, 'pianobench': 2, 'bench': 2} def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False): current_line = script[0] ...
def execute_terraform(args: Optional[Sequence[str]]=None, cwd: Optional[Union[(Path, str)]]=None, env: Optional[dict]=None, capture: bool=False, verbose: Optional[bool]=None) -> CompletedProcess: if (args is None): args = (['terraform'] + sys.argv[1:]) else: args = (['teraform'] + list(args)) ...
class ParameterAddAction(_ActionType): def __init__(self, parameter_ref, value): self.parameter_ref = parameter_ref self.value = convert_float(value) def __eq__(self, other): if isinstance(other, ParameterAddAction): if ((self.get_attributes() == other.get_attributes()) and (...
def test_geojson_find_identifier(): def _create(*properties): return {'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'properties': item} for item in properties]} def _assert_id_got_added(data): _geojson = GeoJson(data) assert (_geojson.find_identifier() == 'feature.id') ...
def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=1, dry_run=0): from distutils._modified import newer from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE if (not os.path.isfile(src)): raise DistutilsFileError(("can't copy '%s': doesn't exist or not a regular ...
class CrossEntropyLoss(nn.Module): def __init__(self, num_classes, epsilon=0.1, use_gpu=True, label_smooth=True): super(CrossEntropyLoss, self).__init__() self.num_classes = num_classes self.epsilon = (epsilon if label_smooth else 0) self.use_gpu = use_gpu self.logsoftmax = n...
def estimate_mu_sigma(cam_data, cam_data_length, cam_r, cam_base_ctr, dsp_budget, volume, dsp_l, cam_v, algo_one_para, algo): cam_mu = {} cam_sigma = {} para = algo_one_para[algo] for cam in cam_data: data = cam_data[cam] length = cam_data_length[cam] profit_margins = [] ...
class SolventPsi4(SolventBase): program: Literal['psi4'] = 'psi4' units: Literal[('au', 'angstrom')] = Field(..., description='The units used in the input options atomic units are used by default.') codata: Literal[(1998, 2002, 2006, 2010)] = Field(2010, description='The set of fundamental physical constant...
class ThriftTraceHeaderTests(GeventPatchedTestCase): def test_user_agent(self): class Handler(TestService.Iface): def example(self, context): return True handler = Handler() server_span_observer = mock.Mock(spec=ServerSpanObserver) with serve_thrift(handle...
def merge_meshes(meshes: List[trimesh.Trimesh]): (n, vs, fs) = (0, [], []) for mesh in meshes: (v, f) = (mesh.vertices, mesh.faces) vs.append(v) fs.append((f + n)) n = (n + v.shape[0]) if n: return trimesh.Trimesh(np.vstack(vs), np.vstack(fs)) else: return...
def render_lines(lines, font, color, lw, lh, lh_offset): surface = pygame.Surface((lw, ((lh + lh_offset) * len(lines))), flags=pygame.SRCALPHA) y_offset = 0 for line in lines: font_surface = font.render(line, True, color) surface.blit(font_surface, (0, y_offset)) y_offset += (lh + lh...
def check(a): if (a == '0'): return 6 elif (a == '1'): return 2 elif (a == '2'): return 5 elif (a == '3'): return 5 elif (a == '4'): return 4 elif (a == '5'): return 5 elif (a == '6'): return 6 elif (a == '7'): return 3 ...
def test_channelstate_filters(): test_state = factories.make_chain_state(number_of_channels=5) chain_state = test_state.chain_state token_network_registry_address = test_state.token_network_registry_address token_address = test_state.token_address (channel_open, channel_closing, channel_closed, chan...
def test_saturation_describing_function(satsys): satfcn = saturation_class() amprange = np.linspace(0, 10, 100) df_anal = [satfcn.describing_function(a) for a in amprange] df_fcn = ct.describing_function(saturation, amprange) np.testing.assert_almost_equal(df_fcn, df_anal, decimal=3) df_fcn = ct...
def main(): args = parse_args() assert (len(args.scores) == len(args.coefficients)) score_list = args.scores score_list = [load(f) for f in score_list] if args.apply_softmax: def apply_softmax(scores): return [softmax(score) for score in scores] score_list = [apply_softma...
def train(args, accelerator, model, tokenizer, train_dataloader, optimizer, lr_scheduler, eval_dataloader=None): total_batch_size = ((args.per_device_train_batch_size * accelerator.num_processes) * args.gradient_accumulation_steps) logger.info('***** Running training *****') logger.info(' Num examples = %d...
(frozen=True, order=True) class KeyInfo(): key: Qt.Key modifiers: _ModifierType = Qt.KeyboardModifier.NoModifier def __post_init__(self) -> None: if machinery.IS_QT5: modifier_classes = (Qt.KeyboardModifier, Qt.KeyboardModifiers) elif machinery.IS_QT6: modifier_classe...
class MatchStmt(Statement): __slots__ = ('subject', 'patterns', 'guards', 'bodies') __match_args__ = ('subject', 'patterns', 'guards', 'bodies') subject: Expression patterns: list[Pattern] guards: list[(Expression | None)] bodies: list[Block] def __init__(self, subject: Expression, patterns:...
def score_target_hypo(args, a, b, c, lenpen, target_outfile, hypo_outfile, write_hypos, normalize): print('lenpen', lenpen, 'weight1', a, 'weight2', b, 'weight3', c) (gen_output_lst, bitext1_lst, bitext2_lst, lm_res_lst) = load_score_files(args) dict = dictionary.Dictionary() scorer = bleu.Scorer(dict.p...
class ChineseCLIPProcessor(ProcessorMixin): attributes = ['image_processor', 'tokenizer'] image_processor_class = 'ChineseCLIPImageProcessor' tokenizer_class = ('BertTokenizer', 'BertTokenizerFast') def __init__(self, image_processor=None, tokenizer=None, **kwargs): if ('feature_extractor' in kw...
class TableWidgetItem(QtWidgets.QTableWidgetItem): def __init__(self, val, index, format=None): QtWidgets.QTableWidgetItem.__init__(self, '') self._blockValueChange = False self._format = None self._defaultFormat = '%0.3g' self.sortMode = 'value' self.index = index ...
class MixedConv2d(nn.ModuleDict): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding='', dilation=1, depthwise=False, **kwargs): super(MixedConv2d, self).__init__() kernel_size = (kernel_size if isinstance(kernel_size, list) else [kernel_size]) num_groups = len(ke...
def centroid_and_bbox_from_coords(coords): if isinstance(coords, pd.Series): coords = coords.to_list()[0] elif isinstance(coords, pd.DataFrame): coords = list(zip(coords.X, coords.Y)) xs = [xys[0] for xys in coords] ys = [xys[1] for xys in coords] xc = (sum(xs) / len(xs)) yc = (s...
class ModelSingleTagFieldInvalidTest(TagTestManager, TransactionTestCase): manage_models = [test_models.SingleTagFieldModel] def test_invalid_to_model(self): with self.assertRaises(ValueError) as cm: class FailModel_invalid_to(models.Model): to_model = tag_models.SingleTagFie...
class TabBar(QtWidgets.QTabBar): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setDrawBase(False) self.setExpanding(False) self.setElideMode(Qt.ElideRight) def tabSizeHint(self, index): size = QtWidgets.QTabBar.tabSizeHint(self, index) ...
class TagReader(): label2id_map = {'<START>': 0} def read_inst(cls, file, is_labeled, number, opinion_offset): insts = [] inputs = [] outputs = [] f = open(file, 'r', encoding='utf-8') if (not is_labeled): opinion_offset = 10000 for line in f: ...
def run_procedure(): global frenum global begin_time global end_time global flag read_file() min_sigma() store_into_vec() begin_time = time.perf_counter() dealingfirstlevel(freArr) global f_level if ((flag == 1) or (flag == 4)): f_level = 1 gen_candidate(f_lev...
class UploadedFile(): def __init__(self, filename, contents, mime_type): assert isinstance(contents, bytes) self.contents = contents self.filename = filename self.mime_type = mime_type def size(self): return len(self.contents) def open(self): with io.BytesIO(s...
def run_data_migration(apps, schema_editor): Catalog = apps.get_model('questions', 'Catalog') Section = apps.get_model('questions', 'Section') QuestionSet = apps.get_model('questions', 'QuestionSet') Question = apps.get_model('questions', 'Question') set_null_to_blank(Catalog.objects.all(), ['uri', ...
def _interpolate(name, dim, interpolate_mode): def symbolic_fn(g, input, output_size, *args): (scales, align_corners) = sym_help._get_interpolate_attributes(g, interpolate_mode, args) align_corners = sym_help._maybe_get_scalar(align_corners) transformation_mode = ('asymmetric' if (interpolat...
class XlibWindow(BaseWindow): _x_display = None _x_screen_id = None _x_ic = None _window = None _override_redirect = False _x = 0 _y = 0 _mouse_exclusive_client = None _mouse_buttons = ([False] * 6) _active = True _applied_mouse_exclusive = False _applied_keyboard_exclusi...
def all_gather_list(data, group=None, max_size=16384): if (group is None): group = get_global_group() rank = get_rank(group=group) world_size = get_world_size(group=group) buffer_size = (max_size * world_size) if ((not hasattr(all_gather_list, '_buffer')) or (all_gather_list._buffer.numel() ...
class TabbedBrowserStub(QObject): def __init__(self, parent=None): super().__init__(parent) self.widget = TabWidgetStub() self.is_shutting_down = False self.loaded_url = None self.cur_url = None self.undo_stack = None def on_tab_close_requested(self, idx): ...
class TripletsNet6c(VGGNet): def __init__(self, config): super(TripletsNet6c, self).__init__() self.trunk = ClusterNet6cTrunk(config) self.head = TripletsNet6cHead(config) self._initialize_weights() def forward(self, x, kmeans_use_features=False): x = self.trunk(x) ...
class MultiTree(): def __init__(self, value, parent): self.parent = parent self.value = value self.children = [] def add_children(self, children): self.children.append(children) def add_value(self, values: str, ac, separators: str='-'): value = values.split(separators...
def _check_structure_field(name: str, dtype_tuple: Tuple[(np.dtype, int)], target: 'Structure', type_per_name_with_wildcard: Dict[(str, type)]) -> bool: dtype = dtype_tuple[0] target_type_name = target.get_type(name) target_type_shape_match = re.search(_REGEX_FIELD_SHAPE, target_type_name) actual_type =...
class DataTrainingArguments(): dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}...
def test_realloc_3_1_5_4_6(): allocator = RegionAllocator(1000) regions = [] for i in range(10): regions.append(allocator.alloc(3)) for region in regions: allocator.realloc(region, 1) for region in regions: allocator.realloc(region, 5) for region in regions: alloc...
def prototype_view(proto, org_members): def prototype_user_view(user): return {'name': user.username, 'is_robot': user.robot, 'kind': 'user', 'is_org_member': (user.robot or (user.username in org_members)), 'avatar': avatar.get_data_for_user(user)} if proto.delegate_user: delegate_view = prototy...
def is_torch_tpu_available(): if (not _torch_available): return False if (importlib.util.find_spec('torch_xla') is None): return False if (importlib.util.find_spec('torch_xla.core') is None): return False return (importlib.util.find_spec('torch_xla.core.xla_model') is not None)
def evaluate_one_dataset(LOG, dataloader, model, opt, save=True, give_return=True, epoch=0): start = time.time() image_paths = np.array(dataloader.dataset.image_list) with torch.no_grad(): (F1, NMI, recall_at_ks, feature_matrix_all) = aux.eval_metrics_one_dataset(model, dataloader, device=opt.device...