code
stringlengths
281
23.7M
def test_conc_dock() -> None: a = Mult(Charclass('A'), ONE) b = Mult(Charclass('B'), ONE) x = Mult(Charclass('X'), ONE) x_twice = Mult(Charclass('X'), Multiplier(Bound(2), Bound(2))) yplus = Mult(Charclass('y'), PLUS) z = Mult(Charclass('Z'), ONE) assert (Conc(a, z).dock(Conc(z)) == Conc(a))...
class LogTestCase(unittest.TestCase): def setUp(self): self.out = StringIO() self.tracker = ClassTracker(stream=self.out) def output(self): return self.out.getvalue() def tearDown(self): self.tracker.stop_periodic_snapshots() self.tracker.clear() def test_dump(sel...
def _maybe_compute_stride_kjt(keys: List[str], stride: Optional[int], lengths: Optional[torch.Tensor], offsets: Optional[torch.Tensor]) -> int: if (stride is None): if (len(keys) == 0): stride = 0 elif ((offsets is not None) and (offsets.numel() > 0)): stride = ((offsets.nume...
def make_xml(filename, path, box_list, labels, w, h, d): doc = xml.dom.minidom.Document() root = doc.createElement('annotation') doc.appendChild(root) foldername = doc.createElement('folder') foldername.appendChild(doc.createTextNode('JPEGImages')) root.appendChild(foldername) nodeFilename =...
def collect_stats(model, data_loader, num_batches): for (name, module) in model.named_modules(): if isinstance(module, quant_nn.TensorQuantizer): if (module._calibrator is not None): module.disable_quant() module.enable_calib() else: mo...
def validate_report(arg): file_choices = ['annotate', 'html', 'xml', 'json', 'lcov'] term_choices = ['term', 'term-missing'] term_modifier_choices = ['skip-covered'] all_choices = (term_choices + file_choices) values = arg.split(':', 1) report_type = values[0] if (report_type not in (all_cho...
class Base64BinaryField(TextField): def db_value(self, value): if (value is None): return None return base64.b64encode(value).decode('ascii') def python_value(self, value): if (value is None): return None return base64.b64decode(value.encode('ascii'))
class Cleanup(SquirrelCommand): def make_subparser(self, subparsers): headline = 'Remove leftover volatile data entries.' return subparsers.add_parser('cleanup', help=headline, description=headline) def run(self, parser, args): s = sq.Squirrel() db = s.get_database() n_re...
class Effect6062(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Light Drone Operation')), 'shieldCapacity', ship.getModifiedItemAttr('shipBonusGC2'), skill='Gallente Cruiser', **kwargs)
class FakeFile(): def __init__(self, name, mode): self.mode = mode self.name = name self.data = BytesIO() self.size = 0 def __enter__(self): return self def __exit__(self, *args): self.close() def read(self, length=(- 1)): if (length == (- 1)): ...
class sepCEMA(): def __init__(self, num_params, mu_init=None, sigma_init=0.001, pop_size=256, parents=None, elitism=False, antithetic=False): self.num_params = num_params if (mu_init is None): self.mu = np.zeros(self.num_params) else: self.mu = np.array(mu_init) ...
def validate_config_section(config, section): notifications = (config.get('notifications') or {}) if (section == 'email'): email_config = (notifications.get('email') or {}) validate(email_config, EMAIL_CONFIG_SCHEMA) elif (section == 'slack'): slack_config = (notifications.get('slack...
def load_NarrativeQA(cache_dir): f = pd.read_csv('datasets/NarrativeQA_LLMs.csv') q = f['Question'].tolist() a_human = f['answers'].tolist() a_human = [_.split(';')[0] for _ in a_human] mgt_text_list = [] for detectLLM in ['ChatGPT', 'ChatGLM', 'Dolly', 'ChatGPT-turbo', 'GPT4', 'StableLM']: ...
class GdbContinue(sublime_plugin.WindowCommand): def run(self): global gdb_cursor_position gdb_cursor_position = 0 update_view_markers() resume() def is_enabled(self): return (is_running() and (gdb_run_status != 'running')) def is_visible(self): return is_runn...
def test_special_generics(): assert_normalize(tuple, tuple, [nt_zero(Any), ...]) assert_normalize(Tuple, tuple, [nt_zero(Any), ...]) if HAS_STD_CLASSES_GENERICS: assert_normalize(tuple[int], tuple, [nt_zero(int)]) assert_normalize(Tuple[int], tuple, [nt_zero(int)]) if HAS_STD_CLASSES_GENERIC...
class DudenWord(): wordcloud_parts_of_speech = ['substantive', 'verben', 'adjektive'] def __init__(self, soup): self.soup = soup def __repr__(self): return '{} ({})'.format(self.title, self.part_of_speech) def title(self): return self.soup.h1.get_text().replace('\xad', '').strip(...
class RRDBNet(nn.Module): def __init__(self, in_nc, out_nc, nf, nb, gc=32, upscale=4, norm_type=None, act_type='leakyrelu', mode='CNA', upsample_mode='upconv'): super(RRDBNet, self).__init__() n_upscale = int(math.log(upscale, 2)) if (upscale == 3): n_upscale = 1 fea_conv...
def evaluate_command(cmd, solver): if (cmd.name == smtcmd.SET_INFO): return solver.set_info(cmd.args[0], cmd.args[1]) if (cmd.name == smtcmd.SET_OPTION): opt = cmd.args[0] if (opt[0] == ':'): opt = opt[1:] return solver.set_option(opt, cmd.args[1]) elif (cmd.name ...
class PoolFromConfigTests(unittest.TestCase): def test_empty_config(self): with self.assertRaises(ConfigurationError): pool_from_config({}) def test_basic_url(self): pool = pool_from_config({'memcache.endpoint': 'localhost:1234'}) self.assertEqual(pool.server[0], 'localhost')...
def test_multitask_gather(): ann_info = dict(image_size=np.array([256, 256]), heatmap_size=np.array([64, 64]), num_joints=17, joint_weights=np.ones((17, 1), dtype=np.float32), use_different_joint_weights=False) results = dict(joints_3d=np.zeros([17, 3]), joints_3d_visible=np.ones([17, 3]), ann_info=ann_info) ...
_dataframe_method _alias(column='column_name') def convert_unix_date(df: pd.DataFrame, column_name: Hashable) -> pd.DataFrame: try: df[column_name] = pd.to_datetime(df[column_name], unit='s') except OutOfBoundsDatetime: df[column_name] = pd.to_datetime(df[column_name], unit='ms') return df
class StringMixin(object): __schema_type__ = 'string' def __init__(self, *args, **kwargs): self.min_length = kwargs.pop('min_length', None) self.max_length = kwargs.pop('max_length', None) self.pattern = kwargs.pop('pattern', None) super(StringMixin, self).__init__(*args, **kwarg...
def build_norm_layer(cfg, num_features, postfix=''): if (not isinstance(cfg, dict)): raise TypeError('cfg must be a dict') if ('type' not in cfg): raise KeyError('the cfg dict must contain the key "type"') cfg_ = cfg.copy() layer_type = cfg_.pop('type') if (layer_type not in NORM_LAY...
(os.path.exists(DEFAULT_REPO), 'Tatoeba directory does not exist.') class TatoebaConversionTester(unittest.TestCase): _property def resolver(self): tmp_dir = tempfile.mkdtemp() return TatoebaConverter(save_dir=tmp_dir) def test_resolver(self): self.resolver.convert_models(['heb-eng']...
class FontConfig(): def __init__(self): self._fontconfig = self._load_fontconfig_library() self._search_cache = OrderedDict() self._cache_size = 20 def dispose(self): while (len(self._search_cache) > 0): self._search_cache.popitem().dispose() self._fontconfig....
class LayerOutput(): def __init__(self, session: tf.compat.v1.Session, starting_op_names: List[str], output_op_names: List[str], dir_path: str): self.session = session (self.activation_tensor_names, self.activation_tensors) = LayerOutput.get_activation_tensor_info(session, starting_op_names, output_...
def benchmark(mapping, start_pt, run_num): topo = TopoGraphGen(mapping, max_raycast_dist=1.5) topo.test_detect_collisions(start_pt) topo.node_expansion(start_pt, False) s = time.time() topo.node_expansion_benchmark(start_pt, False, run_num=run_num) dt = (time.time() - s) print(f'avg node exp...
def KUGW(mf, freq_int='ac', frozen=None): if (freq_int.lower() == 'ac'): return kugw_ac.KUGWAC(mf, frozen) elif (freq_int.lower() == 'cd'): raise RuntimeError('GWCD does not support UHF or UKS methods.') else: raise RuntimeError(("GW frequency integration method %s not recognized. Wi...
class VPG(BatchPolopt, Serializable): def __init__(self, env, policy, baseline, optimizer=None, optimizer_args=None, **kwargs): Serializable.quick_init(self, locals()) if (optimizer is None): default_args = dict(batch_size=None, max_epochs=1) if (optimizer_args is None): ...
def daily_analyze_urls(days=30, min_visits=100): dt_cutoff = (timezone.now() - datetime.timedelta(days=days)) analyzed_urls = AnalyzedUrl.objects.filter(last_analyzed_date__lt=dt_cutoff, visits_since_last_analyzed__gte=min_visits).select_related() log.debug('URLs to analyze: %s', analyzed_urls.count()) ...
class Effect5331(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): for layer in ('shieldCapacity', 'armorHP', 'hp'): fit.drones.filteredItemBoost((lambda drone: drone.item.requiresSkill('Drones')), layer, ship.getModifiedItemAttr('shipBonusABC2'), skil...
def lr0_goto(I, x): g = _lr_goto_cache.get((id(I), x), None) if g: return g s = _lr_goto_cache.get(x, None) if (not s): s = {} _lr_goto_cache[x] = s gs = [] for p in I: n = p.lr_next if (n and (n.lrbefore == x)): s1 = s.get(id(n), None) ...
def send_validation(strategy, backend, code, partial_token): url = '{}?verification_code={}&partial_token={}'.format(reverse('social:complete', args=(backend.name,)), code.code, partial_token) url = strategy.request.build_absolute_uri(url) send_mail('Validate your account', f'Validate your account {url}', s...
class StyleGAN2Model(BaseModel): def __init__(self, opt): super(StyleGAN2Model, self).__init__(opt) self.net_g = define_network(deepcopy(opt['network_g'])) self.net_g = self.model_to_device(self.net_g) self.print_network(self.net_g) load_path = self.opt['path'].get('pretrain_...
def test__getting_started__example_multinode_constraints(): from bioptim.examples.getting_started import example_multinode_constraints as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) ocp_module.prepare_ocp(biorbd_model_path=(bioptim_folder + '/models/cube.bioMod'), phase_dynamics=PhaseDy...
class MetadataTest(unittest.TestCase): def make_temp(self): global tempdir if tempdir.lstat(): tempdir.delete() tempdir.mkdir() def testQuote(self): filenames = [b'foo', b'.', b'hello\nthere', b'\\', b'\\\\\\', b'h\no\t\x87\n', b' '] for filename in filenames:...
class JSONFormatter(logging.Formatter): def __init__(self): pass def format(self, record): event = {'timestamp': self.getTimestamp(record.created), 'message': record.getMessage(), 'level': record.levelname, 'logger': record.name} event_data = getattr(record, 'event_data', None) i...
def require_gdal_version(version, param=None, values=None, is_max_version=False, reason=''): if (values is not None): if (param is None): raise ValueError('require_gdal_version: param must be provided with values') if (not isinstance(values, (tuple, list, set))): raise ValueE...
def _find_nodes_to(state: EnvironmentState, node: Node, relations: List[Relation]): nodes = [] for src_node in AnyNode().enumerate(state): for r in relations: nl = state.get_nodes_from(src_node, r) if (node in nl): nodes.append(src_node) return nodes
def contains(shape, other): if (not hasattr(shape, GEO_INTERFACE_ATTR)): raise TypeError((SHAPE_TYPE_ERR % shape)) if (not hasattr(other, GEO_INTERFACE_ATTR)): raise TypeError((SHAPE_TYPE_ERR % shape)) o = geom.shape(shape) o2 = geom.shape(other) return o.contains(o2)
def task_02(self): if 0: self._subscriber_base.subscribe() while (self._subscriber_base_points is None): pass self._subscriber_base.unsubscribe() obj = safepicking.pybullet.create_bin(X=0.3, Y=0.3, Z=0.11, color=(0.7, 0.7, 0.7, 1)) safepicking.pybullet.set_pose(obj, ((0.,...
('pyinaturalist.v1.observations.get_observation') ('pyinaturalist.v1.observations.put') def test_update_observation__with_photo_ids(mock_put, mock_get_observation): mock_get_observation.return_value = {'photos': [{'id': 1234}]} update_observation(1234, access_token='token', photo_ids=5678) payload = mock_pu...
def read_kaldi_datadir(dir): if os.path.isfile(os.path.join(dir, 'segments')): logger.info("The data directory '{}' seems to use a 'segments' file. This script does not yet support a 'segments' file. You'll need to use utils/data/extract_wav_segments_data_dir.sh to convert the data dir so it does not use a ...
class TimeSignal(VBObject): def VBBJECT_TYPE(self): return 'TimeSignal' def __init__(self, path=None, sampling_rate=None): VBObject.__init__(self, path=path) if sampling_rate: self.sampling_rate = sampling_rate def initializeBlank(self): VBObject.initializeBlank(s...
def _validate_netloc(value: str, skip_ipv6_addr: bool, skip_ipv4_addr: bool, may_have_port: bool, simple_host: bool, rfc_1034: bool, rfc_2782: bool): if ((not value) or (value.count('') > 1)): return False if (value.count('') < 1): return hostname((value if (_confirm_ipv6_skip(value, skip_ipv6_a...
_dimension def test_triangulation_of_standard_simplex(dim): t = Triangulation(_make_standard_simplex(dim)) expected_simplex = tuple(range((dim + 1))) assert (t.simplices == {expected_simplex}) _check_triangulation_is_valid(t) assert np.isclose(t.volume(expected_simplex), _standard_simplex_volume(dim...
def create_data(client: Client, args, name='balanced-df') -> Tuple[(int, dask.dataframe.DataFrame)]: chunksize = (args.partition_size // np.float64().nbytes) workers = list(client.scheduler_info()['workers'].keys()) assert (len(workers) > 0) dist = args.partition_distribution if (dist is None): ...
def main(): parser = argparse.ArgumentParser(description='PyTorch Lightning DDP') parser.add_argument('--epochs', default=1, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('-b', '--batch_size', default=128, type=int, metavar='N') parser.add_argument('--learning_rate', d...
class RNet(nn.Module): def __init__(self): super(RNet, self).__init__() self.features = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3, 28, 3, 1)), ('prelu1', nn.PReLU(28)), ('pool1', nn.MaxPool2d(3, 2, ceil_mode=True)), ('conv2', nn.Conv2d(28, 48, 3, 1)), ('prelu2', nn.PReLU(48)), ('pool2', nn.Ma...
def differentiable_graph_to_smiles_purely_randomwalk(origin_smiles, differentiable_graph, leaf_extend_idx_pair, leaf_nonleaf_lst, topk=3, epsilon=0.7): leaf2nonleaf = {leaf: nonleaf for (leaf, nonleaf) in leaf_nonleaf_lst} leaf2extend = {leaf: extend for (leaf, extend) in leaf_extend_idx_pair} new_smiles_se...
class QPE(QuantumAlgorithm, MinimumEigensolver): def __init__(self, operator: Optional[Union[(OperatorBase, LegacyBaseOperator)]]=None, state_in: Optional[Union[(InitialState, QuantumCircuit)]]=None, iqft: Optional[QuantumCircuit]=None, num_time_slices: int=1, num_ancillae: int=1, expansion_mode: str='trotter', exp...
('satpy.multiscene._multiscene.get_enhanced_image') def test_save_mp4(smg, tmp_path): from satpy import MultiScene area = _create_test_area() scenes = _create_test_scenes(area=area) smg.side_effect = _fake_get_enhanced_image scenes[1]['ds3'] = _create_test_dataset('ds3') for ds_id in ['ds1', 'ds...
class IndexV2TestSpec(object): def __init__(self, index_name, method_name, repo_name, scope=None, **kwargs): self.index_name = index_name self.repo_name = repo_name self.method_name = method_name default_scope = ('push,pull' if ((method_name != 'GET') and (method_name != 'HEAD')) els...
.parametrize('lhs,rhs,result', [(1, 1, True), (1, 1.1, True), (1.1, 1, False), (1.0, 1.0, True), ('abc', 'def', True), ('abc', '', False), ([], [1], True), ((1, 2), (2, 3), True), ((1, 0), (1,), False), (True, True, True), (True, False, False), (False, 1, True), ((1 + 0j), (2 + 0j), util.Uninferable), ((+ 0.0), (- 0.0)...
class _BasePrompt(QWidget): KEY_MODE = usertypes.KeyMode.prompt def __init__(self, question, parent=None): super().__init__(parent) self.question = question self._vbox = QVBoxLayout(self) self._vbox.setSpacing(15) self._key_grid = None def __repr__(self): retu...
class AttrVI_ATTR_SEND_END_EN(BooleanAttribute): resources = [(constants.InterfaceType.asrl, 'INSTR'), (constants.InterfaceType.gpib, 'INSTR'), (constants.InterfaceType.gpib, 'INTFC'), (constants.InterfaceType.tcpip, 'INSTR'), (constants.InterfaceType.tcpip, 'SOCKET'), (constants.InterfaceType.usb, 'INSTR'), (const...
def test_creating_new_catalog(): cf = OSC.CatalogFile() cf.create_catalog('my_catalog.xml', 'VehicleCatalog', 'My first vehicle catalog', 'Mandolin') bb = OSC.BoundingBox(2, 5, 1.8, 2.0, 0, 0.9) fa = OSC.Axle(0., 0.8, 1.68, 2.98, 0.4) ba = OSC.Axle(0., 0.8, 1.68, 0, 0.4) white_veh = OSC.Vehicle(...
class Evaluator(object): def __init__(self, args, num_gpus): self.args = args self.num_gpus = num_gpus self.device = torch.device(args.device) val_dataset = CSValSet(args.data, os.path.join(os.getcwd(), '../dataset/list/cityscapes/val.lst'), crop_size=(1024, 2048)) val_sample...
def call_main(cfg: FairseqConfig, main, **kwargs): if (cfg.distributed_training.distributed_init_method is None): infer_init_method(cfg.distributed_training) if (cfg.distributed_training.distributed_init_method is not None): if (not cfg.distributed_training.distributed_no_spawn): sta...
class GlBuffer(): def __init__(self, target=gl.GL_ARRAY_BUFFER, usage=gl.GL_STATIC_DRAW): self.id_ = gl.glGenBuffers(1) self.target_ = target self.usage_ = usage def assign(self, array): gl.glBindBuffer(self.target_, self.id_) gl.glBufferData(self.target_, array, self.usa...
class Encoder(nn.Module): def __init__(self, normalize=False): super(Encoder, self).__init__() self.f = nn.Sequential(nn.Conv2d(in_channels=1, out_channels=128, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1...
.parametrize('membership_role', membership_roles) def test_project_join_user_error(db, client, membership_role): client.login(username='user', password='user') project = Project.objects.get(id=1) user = get_user_model().objects.get(username='user') invite = Invite(project=project, user=get_user_model()....
class SnliProcessor(DataProcessor): def get_train_examples(self, data_dir): return self._create_examples(pd.read_csv(os.path.join(data_dir, 'train.csv'), sep='\t', header=None, keep_default_na=False).values.tolist(), 'train') def get_dev_examples(self, data_dir): return self._create_examples(pd....
def verify_opt(opt): assert (opt.nz >= opt.infogan_nz) assert ((opt.infogan_nz == 0) or (opt.infogan_lambda > 0)) assert ((len(opt.layers_to_reg) == 0) or (min(opt.layers_to_reg) >= 1)) assert ((opt.epsilon > 0) or (opt.hp_lambda == 0)) assert ((opt.num_rademacher_samples >= 2) or (opt.hp_lambda == ...
def main(): args = parser.parse_args() with open(args.config_file) as f: config_template = Template(f.read()) args.out_dir.mkdir(parents=True, exist_ok=True) print('Writing to directory', args.out_dir) for (scene, split) in scenes: config = config_template.substitute(scene=scene, spl...
class TestShowFixtures(): def test_funcarg_compat(self, pytester: Pytester) -> None: config = pytester.parseconfigure('--funcargs') assert config.option.showfixtures def test_show_help(self, pytester: Pytester) -> None: result = pytester.runpytest('--fixtures', '--help') assert (...
class AsyncQdrantClient(AsyncQdrantFastembedMixin): def __init__(self, location: Optional[str]=None, url: Optional[str]=None, port: Optional[int]=6333, grpc_port: int=6334, prefer_grpc: bool=False, Optional[bool]=None, api_key: Optional[str]=None, prefix: Optional[str]=None, timeout: Optional[float]=None, host: Op...
class KTI1(DataElementGroup): iban = DataElementField(type='an', max_length=34, required=False, _d='IBAN') bic = DataElementField(type='an', max_length=11, required=False, _d='BIC') account_number = DataElementField(type='id', required=False, _d='Konto-/Depotnummer') subaccount_number = DataElementField...
class Mixed_7a(nn.Module): def __init__(self): super(Mixed_7a, self).__init__() self.branch0 = nn.Sequential(BasicConv2d(1088, 256, kernel_size=1, stride=1), BasicConv2d(256, 384, kernel_size=3, stride=2)) self.branch1 = nn.Sequential(BasicConv2d(1088, 256, kernel_size=1, stride=1), BasicCon...
.parametrize('example, error_msg', [('\n [project]\n name = "myproj"\n version = "1.2"\n requires = [\'pywin32; platform_system=="Windows"\' ]\n ', 'configuration error: .project. must not contain ..requires.. properties')]) def test_invalid_example(tmp_path, examp...
class AoA_Refiner_Layer(nn.Module): def __init__(self, size, self_attn, feed_forward, dropout): super(AoA_Refiner_Layer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.use_ff = 0 self.batch_info = [] self.att_layer_idx = 0 if...
_test def test_optimizer_get_updates_legacy_interface(): for optimizer_cls in [keras.optimizers.RMSprop, keras.optimizers.SGD, keras.optimizers.Adadelta, keras.optimizers.Adam, keras.optimizers.Adagrad, keras.optimizers.Nadam, keras.optimizers.Adamax]: optimizer = optimizer_cls() param = keras.backe...
class SuffixImporter(): scheme = 'suffix' suffix = None path_entry = None def trigger_url(cls): if (cls.suffix is None): raise ValueError(('%s.suffix is not set' % cls.__name__)) return ('suffix:%s' % cls.suffix) def register(cls): sys.path_hooks.append(cls) ...
def test_interactive_with_git_dependencies_with_reference(tester: CommandTester, repo: TestRepository) -> None: repo.add_package(get_package('pendulum', '2.0.0')) repo.add_package(get_package('pytest', '3.6.0')) inputs = ['my-package', '1.2.3', 'This is a description', 'n', 'MIT', '~2.7 || ^3.6', '', 'git+ ...
def creatMultiItemUserAdj(dataset, cv): (trainMat, _, _, trainMat_time, _) = loadData(dataset, cv) ratingClass = np.unique(trainMat.data).size (userNum, itemNum) = trainMat.shape multi_adj = sp.lil_matrix(((ratingClass * itemNum), userNum), dtype=np.int) uidList = trainMat.tocoo().row iidList = ...
def main(): opt = parser.parse_args() opt.cuda = (opt.gpu > (- 1)) if opt.cuda: torch.cuda.set_device(opt.gpu) opt.n_best = opt.beam_size if (opt.output == 'stdout'): outF = sys.stdout else: outF = open(opt.output, 'w') (pred_score_total, pred_words_total, gold_score_...
() ('name', default=None, nargs=(- 1)) _options _options ('--submit/--no-submit') def apply_stage(name, metadir, accept_metadir, controller, ctrlopt, modelsetup, modelopt, backend, local, verbosity, submit): handle_common_options(verbosity) ys = handle_connection_options(metadir, accept_metadir, controller, ctr...
def test_used_with_session_scope(testdir: Any) -> None: testdir.makeini('\n [pytest]\n asyncio_mode=auto\n ') testdir.makepyfile('\n import pytest\n import random\n\n def get_random_number():\n return random.randint(0, 1)\n\n (autouse=True, scope="sess...
class EEGSupervisedPretrainLoader(torch.utils.data.Dataset): def __init__(self, tuev_data, chb_mit_data, iiic_data, tuab_data): (tuev_root, tuev_files) = tuev_data self.tuev_root = tuev_root self.tuev_files = tuev_files self.tuev_size = len(self.tuev_files) (chb_mit_root, chb...
def train(model, data, target, optimizer, coreset_theta): model.train() optimizer.zero_grad() output = model(data) acc1 = mean_accuracy(output, target) loss = torch.sum(((F.binary_cross_entropy_with_logits(output, target, reduction='none') * coreset_theta) / coreset_theta.sum())) loss.backward()...
def test_cf_rotated_latlon__grid(): crs = CRS.from_cf(dict(grid_mapping_name='rotated_latitude_longitude', grid_north_pole_latitude=32.5, grid_north_pole_longitude=1.0, north_pole_grid_longitude=170.0)) with pytest.warns(UserWarning): proj_dict = crs.to_dict() assert (proj_dict == {'proj': 'ob_tran'...
class _Cached(): def __init__(self, func, count): self.func = func self.cache = [] self.count = count def __call__(self, *args, **kwds): key = (args, kwds) for (cached_key, cached_result) in self.cache: if (cached_key == key): return cached_res...
class BroadcastUDPClient(Client): def __init__(self, bcastaddr, prog, vers): self.pmap = BroadcastUDPPortMapperClient(bcastaddr) self.pmap.set_reply_handler(self.my_reply_handler) self.prog = prog self.vers = vers self.user_reply_handler = None self.addpackers() d...
class VNet(nn.Module): def __init__(self, classes_num=2): classes = classes_num super(VNet, self).__init__() self.in_block = VNetInBlock(1, 32, 1) self.down_block1 = VNetDownBlock(32, 32, 2) self.down_block2 = VNetDownBlock(32, 64, 3) self.down_block3 = VNetDownBlock(...
((types.Array(types.float64, 1, 'C', readonly=True), types.int32, types.float64), nopython=True) def _numba_sampen(sequence, order, r): size = sequence.size numerator = 0 denominator = 0 for offset in range(1, (size - order)): n_numerator = int((abs((sequence[order] - sequence[(order + offset)])...
class Solution(): def fizzBuzz(self, n: int) -> List[str]: res = [] for i in range(1, (n + 1)): if (((i % 3) == 0) and ((i % 5) == 0)): res.append('FizzBuzz') elif ((i % 3) == 0): res.append('Fizz') elif ((i % 5) == 0): ...
class PyCoreScopesTest(unittest.TestCase): def setUp(self): super().setUp() self.project = testutils.sample_project() self.pycore = self.project.pycore def tearDown(self): testutils.remove_project(self.project) super().tearDown() def test_simple_scope(self): c...
def true_or_false(t: Type) -> ProperType: t = get_proper_type(t) if isinstance(t, UnionType): new_items = [true_or_false(item) for item in t.items] return make_simplified_union(new_items, line=t.line, column=t.column) new_t = copy_type(t) new_t.can_be_true = new_t.can_be_true_default() ...
def fit_svm(features, y, MAX_SAMPLES=10000): nb_classes = np.unique(y, return_counts=True)[1].shape[0] train_size = features.shape[0] svm = SVC(C=np.inf, gamma='scale') if (((train_size // nb_classes) < 5) or (train_size < 50)): return svm.fit(features, y) else: grid_search = GridSea...
def get_rtlir_dtype(obj): try: assert (not isinstance(obj, list)), 'array datatype object should be a field of some struct!' if isinstance(obj, (dsl.Signal, dsl.Const)): Type = obj._dsl.Type assert isinstance(Type, type) if issubclass(Type, Bits): ...
class DiscourseTransformer(Transformer): def forward(self, batch, target_mask=None, streaming=False, zero_encoder=False, mirror=False, streaming_state=None, nce=False, factorize=True, **kwargs): if ((self.switchout > 0) and self.training): batch.switchout(self.switchout, self.src_vocab_size, sel...
def reset_version_parts(version: Version, **kwargs: Any) -> None: internal_version = version._version parts: dict[(str, Any)] = {} ordered_part_names = ('epoch', 'release', 'pre', 'post', 'dev', 'local') reset = False for part_name in ordered_part_names: if reset: parts[part_name...
_specialize _canonicalize _rewriter([Subtensor]) def local_subtensor_inc_subtensor(fgraph, node): if isinstance(node.op, Subtensor): x = node.inputs[0] if ((not x.owner) or (not isinstance(x.owner.op, IncSubtensor))): return if (not x.owner.op.set_instead_of_inc): ret...
_ordering class Scope(Enum): Function: _ScopeName = 'function' Class: _ScopeName = 'class' Module: _ScopeName = 'module' Package: _ScopeName = 'package' Session: _ScopeName = 'session' def next_lower(self) -> 'Scope': index = _SCOPE_INDICES[self] if (index == 0): rais...
class Command(BaseCommand): columns = ('id', 'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login') def add_arguments(self, parser): parser.add_argument('since', type=(lambda s: pytz.utc.localize(datetime.strptime(s, '%Y-%m-%d'))), help='Date since the users have been inactive (for...
class TestSetSelectionOwner(EndianTest): def setUp(self): self.req_args_0 = {'selection': , 'time': , 'window': } self.req_bin_0 = b'\x16\x00\x04\x00\xaf4\\xfa\x88a\x9a\x10\xdf\x16' def testPackRequest0(self): bin = request.SetSelectionOwner._request.to_binary(*(), **self.req_args_0) ...
def test_slice_inference_in_for_loops_not_working() -> None: ast_nodes = extract_node('\n from unknown import Unknown\n for a, *b in something:\n b #\n for a, *b in Unknown:\n b #\n for a, *b in (1):\n b #\n ') for node in ast_nodes: inferred = next(node.infer()) ...
def parse(): parser = argparse.ArgumentParser(description='variational autoencoder') parser.add_argument('-model_dir', default='train_model', help='output model weight dir') parser.add_argument('-model_path', help='latest model path') parser.add_argument('-batch_size', default=96, type=int, help='batch ...
def check_valid(config): data_fn_splits = os.path.basename(config['data_path']).split('.')[0].split('_') if (len(data_fn_splits) > 1): clip_arch = data_fn_splits[(- 1)].upper() if (clip_arch[:3] == 'VIT'): assert ('' not in clip_arch), f'TODO: {clip_arch}' (_, model_type,...
def rename_key(key): if key.startswith('module.'): key = key[7:] if ('.downsample.' in key): return key.replace('downsample', 'skip') if key.startswith('entropy_bottleneck.'): if key.startswith('entropy_bottleneck._biases.'): return f'entropy_bottleneck._bias{key[(- 1)]}'...