code
stringlengths
281
23.7M
def initialize_model_poisson(train_x, train_obj, train_con, train_yvar, state_dict=None, method='variational'): if (method == 'variational'): model_obj = get_var_model(train_x, train_obj, train_yvar, is_poisson=True) model_con = get_var_model(train_x, train_con, train_yvar, is_poisson=False) ...
class Effect6326(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Missile Launcher Operation')), 'thermalDamage', src.getModifiedItemAttr('shipBonusCD1'), skill='Caldari Destroyer', **kwargs)
def create_build(repository): new_token = model.token.create_access_token(repository, 'write', 'build-worker') repo = ('ci.devtable.com:5000/%s/%s' % (repository.namespace_user.username, repository.name)) job_config = {'repository': repo, 'docker_tags': ['latest'], 'build_subdir': '', 'trigger_metadata': {'...
def make_module_translation_map(names: list[str]) -> dict[(str, str)]: num_instances: dict[(str, int)] = {} for name in names: for suffix in candidate_suffixes(name): num_instances[suffix] = (num_instances.get(suffix, 0) + 1) result = {} for name in names: for suffix in candi...
def evaluate(dataloader, model, confusion, config, args): model.evaluate_mode() logging.error('VALIDATION') for (i, batch) in enumerate(tqdm(dataloader)): (seq_images, targets, _) = batch if (seq_images == None): continue seq_images = seq_images.cuda() cuda_target...
class SystemVerilogLexer(RegexLexer): name = 'systemverilog' aliases = ['systemverilog', 'sv'] filenames = ['*.sv', '*.svh'] mimetypes = ['text/x-systemverilog'] url = ' version_added = '1.5' _ws = '(?:\\s|//.*?\\n|/[*].*?[*]/)+' tokens = {'root': [('^(\\s*)(`define)', bygroups(Whitespac...
.parametrize('src', [lazy_fixture('swath_def_2d_numpy'), lazy_fixture('swath_def_2d_dask'), lazy_fixture('swath_def_2d_xarray_numpy'), lazy_fixture('swath_def_2d_xarray_dask')]) .parametrize('dst', [lazy_fixture('area_def_lcc_conus_1km')]) def test_resampler(src, dst): rs = FakeResampler(src, dst) some_data = n...
def rewrite_metadata(): gso_dir = 'data/google_object_dataset' glob_dump = 'data/gso_glob.npy' gso_meta_path = 'cos_eor/scripts/dump/gso_dump.npy' gso_metadata = {} if os.path.exists(glob_dump): paths = list(np.load(glob_dump, allow_pickle=True)) else: paths = glob.glob((gso_dir ...
def test_simple_function_with_surrounding_statements() -> None: src = '\n x = 10\n def func(x: int) -> None:\n print(x + 1)\n print(x)\n ' cfgs = build_cfgs(src) assert (len(cfgs) == 2) keys = list(cfgs) expected_blocks_module = [['x = 10', '\ndef func(x: int) -> None:\n print(...
def test_sqliteio_read_updates_progress(tmpfile, view): worker = MagicMock(canceled=False) io = SQLiteIO(tmpfile, view.scene, create_new=True, worker=worker) io.create_schema_on_new() io.ex('INSERT INTO items (type, x, y, z, scale, data) VALUES (?, ?, ?, ?, ?, ?) ', ('pixmap', 0, 0, 0, 1, json.dumps({'f...
def parse_args(): parser = argparse.ArgumentParser(description='Generate training and val set of BID ') parser.add_argument('root_path', help='Root dir path of BID') parser.add_argument('--nproc', default=1, type=int, help='Number of processes') parser.add_argument('--val-ratio', help='Split ratio for v...
def G_wgan(G, D, opt, training_set, minibatch_size): latents = tf.random_normal(([minibatch_size] + G.input_shapes[0][1:])) labels = training_set.get_random_labels_tf(minibatch_size) fake_images_out = G.get_output_for(latents, labels, is_training=True) fake_scores_out = fp32(D.get_output_for(fake_images...
def get_dataloader_sample(dataset='imagenet', batch_size=128, num_workers=8, is_sample=False, k=4096): if (dataset == 'imagenet'): data_folder = get_data_folder() else: raise NotImplementedError('dataset not supported: {}'.format(dataset)) normalize = transforms.Normalize(mean=[0.485, 0.456,...
def test_latest_ref_counts(): source = Stream() _ = source.latest() ref1 = RefCounter() source.emit(1, metadata=[{'ref': ref1}]) assert (ref1.count == 1) ref2 = RefCounter() source.emit(2, metadata=[{'ref': ref2}]) assert (ref1.count == 0) assert (ref2.count == 1)
def calculate_stats_from_dataset(): device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) parser = argparse.ArgumentParser() parser.add_argument('--num_sample', type=int, default=50000) parser.add_argument('--batch_size', type=int, default=64) parser.add_argument('--size', type=int...
def time_frequency_stitching(min_switch_ind, final_i_index, time_offset, i_time, i_omega, m_time, m_omega): assert (type(min_switch_ind) == int), 'min_switch_ind should be an int.' assert (type(final_i_index) == int), 'final_i_index should be an int.' assert (type(time_offset) == float), 'time_offset should...
def test_ls_none(data, runner): inputfile = str(data.join('RGB.byte.tif')) result = runner.invoke(cli, ['overview', inputfile, '--ls']) assert (result.exit_code == 0) expected = "Overview factors:\n Band 1: None (method: 'unknown')\n Band 2: None (method: 'unknown')\n Band 3: None (method: 'unknown')...
class SetMentions(ScrimsButton): def __init__(self, ctx: Context, letter: str): super().__init__(emoji=ri(letter)) self.ctx = ctx async def callback(self, interaction: Interaction): (await interaction.response.defer()) m = (await self.ctx.simple('How many mentions are required fo...
def get_config(): config = get_default_configs() training = config.training training.sde = 'vesde' training.continuous = False step_size = 3.3e-06 n_steps_each = 5 ckpt_id = 210000 final_only = True noise_removal = False sampling = config.sampling sampling.method = 'pc' s...
.requires_user_validation def test_pause_sound(event_loop): source = synthesis.WhiteNoise(60.0) player = Player() player.queue(source) player.play() event_loop.run_event_loop(1.0) player.pause() event_loop.ask_question('Did you hear white noise for 1 second and is it now silent?', screenshot...
class TestPSS(): def test_calculate_max_pss_salt_length(self): with pytest.raises(TypeError): padding.calculate_max_pss_salt_length(object(), hashes.SHA256()) def test_invalid_salt_length_not_integer(self): with pytest.raises(TypeError): padding.PSS(mgf=padding.MGF1(hashe...
class TestPostgenerationCalledOnce(): (_name='collector') class CollectorFactory(factory.Factory): class Meta(): model = dict foo = factory.PostGeneration((lambda *args, **kwargs: 42)) def _after_postgeneration(cls, obj: dict[(str, Any)], create: bool, results: (dict[(str, An...
def upgrade(op, tables, tester): op.create_table('logentry3', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('kind_id', sa.Integer(), nullable=False), sa.Column('account_id', sa.Integer(), nullable=False), sa.Column('performer_id', sa.Integer(), nullable=True), sa.Column('repository_id', sa.Integer(), ...
def test(): try: spi = SPI(1, baudrate=, sck=Pin(14), mosi=Pin(13)) display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17)) display.clear() logo = BouncingSprite('images/Python41x49.raw', 41, 49, 240, 320, 1, display) while True: timer = ticks_us() ...
def aretry(exception_cls, max_tries=10, sleep=0.05): assert (max_tries > 0), ('max_tries (%d) should be a positive integer' % max_tries) def decorator(fn): () (fn) def wrapper(*args, **kwargs): for i in range(max_tries): try: ret = (yield f...
def generator(z, y): s = FLAGS.output_size (s2, s4, s8, s16) = (int((s / 2)), int((s / 4)), int((s / 8)), int((s / 16))) gf_dim = 64 h0 = tf.nn.relu(tf.reshape(linear(z, (((gf_dim * 8) * s16) * s16), 'g_h0_lin'), [(- 1), s16, s16, (gf_dim * 8)])) h1 = tf.nn.relu(deconv2d(h0, [FLAGS.batch_size, s8, s...
def tune_model_weights(): parser = generate.get_parser_with_args() parser = add_tune_args(parser) args = options.parse_args_and_arch(parser) n_models = len(args.path.split(CHECKPOINT_PATHS_DELIMITER)) print(n_models) print(args.weight_lower_bound) print(args.weight_upper_bound) print(arg...
def _addmm_flop_jit(inputs: Tuple[torch.Tensor], outputs: Tuple[Any]) -> Number: input_shapes = [v.shape for v in inputs[1:3]] assert (len(input_shapes[0]) == 2), input_shapes[0] assert (len(input_shapes[1]) == 2), input_shapes[1] (batch_size, input_dim) = input_shapes[0] output_dim = input_shapes[1...
class NotificationDevice(XlibSelectDevice): def __init__(self): (self._sync_file_read, self._sync_file_write) = os.pipe() self._event = threading.Event() def fileno(self): return self._sync_file_read def set(self): self._event.set() os.write(self._sync_file_write, b'1...
.linux def test_webengine_download_suffix(request, quteproc_new, tmp_path): if (not request.config.webengine): pytest.skip() download_dir = (tmp_path / 'downloads') download_dir.mkdir() (tmp_path / 'user-dirs.dirs').write_text('XDG_DOWNLOAD_DIR={}'.format(download_dir)) env = {'XDG_CONFIG_HO...
class Params(): gpu_ewc = '4' gpu_rewc = '3' data_size = 224 batch_size = 32 nb_cl = 50 nb_groups = 4 nb_val = 0 epochs = 50 num_samples = 5 lr_init = 0.001 lr_strat = [40, 80] lr_factor = 5.0 wght_decay = 1e-05 ratio = 100.0 eval_single = True save_path =...
class ResNet(object): def __init__(self, args, mode): self.relu_leakiness = 0.1 self.optimizer = 'mom' self.use_bottleneck = False images = tf.placeholder(name='input/images', dtype=tf.float32, shape=(None, 32, 32, 3)) labels = tf.placeholder(name='input/labels', dtype=tf.flo...
class LinearSubSampler(LayerSubSampler): def verify_layers(self, orig_layer: torch.nn.Module, pruned_layer: torch.nn.Module): assert isinstance(orig_layer, torch.nn.Linear) assert isinstance(pruned_layer, torch.nn.Linear) def get_number_of_batches(self, data_loader: Iterator, orig_layer: torch.n...
('enqueue', args=1) def _enqueue(app, value): playlist = app.window.playlist library = app.library if (value in library): songs = [library[value]] elif os.path.isfile(value): songs = [library.add_filename(os.path.realpath(value))] else: songs = library.query(arg2text(value)) ...
def usage(): program = os.path.basename(sys.argv[0]) print('Usage: ', program, '[-s] [<file>]') print('Options:\n <file> ... a file containing METAR reports to parse\n -q ....... run "quietly" - just report parsing error.\n -s ....... run silently. (no output)\n -p ....... run with profiling tur...
class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu1 = nn.LeakyReLU(0.1, inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=strid...
def transform_super_expr(builder: IRBuilder, o: SuperExpr) -> Value: sup_val = builder.load_module_attr_by_fullname('builtins.super', o.line) if o.call.args: args = [builder.accept(arg) for arg in o.call.args] else: assert (o.info is not None) typ = builder.load_native_type_object(o....
class InitWeights_He(object): def __init__(self, neg_slope: float=0.01): self.neg_slope = neg_slope def __call__(self, module): if (isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d)): mod...
def main(_): tf.logging.set_verbosity(tf.logging.INFO) if ((not FLAGS.do_train) and (not FLAGS.do_eval)): raise ValueError('At least one of `do_train` or `do_eval` must be True.') bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) tf.gfile.MakeDirs(FLAGS.output_dir) inp...
def test_call_graph(): (graph, _) = Adjoint(TestBloqWithCallGraph()).call_graph() edge_strs = {f'{caller} -> {callee}' for (caller, callee) in graph.edges} assert (edge_strs == {'Adjoint(subbloq=TestBloqWithCallGraph()) -> Adjoint(subbloq=TestAtom())', 'Adjoint(subbloq=TestBloqWithCallGraph()) -> Adjoint(su...
class ScanningLoader(TestLoader): def __init__(self): TestLoader.__init__(self) self._visited = set() def loadTestsFromModule(self, module, pattern=None): if (module in self._visited): return None self._visited.add(module) tests = [] tests.append(TestL...
class TestSARComposites(unittest.TestCase): def test_sar_ice(self): import dask.array as da import numpy as np import xarray as xr from satpy.composites.sar import SARIce rows = 2 cols = 2 comp = SARIce('sar_ice', prerequisites=('hh', 'hv'), standard_name='sar...
def train_model(model, model_test, criterion, optimizer, scheduler, num_epochs=25): since = time.time() warm_up = 0.1 warm_iteration = (round((dataset_sizes['satellite'] / opt.batchsize)) * opt.warm_epoch) for epoch in range((num_epochs - start_epoch)): epoch = (epoch + start_epoch) prin...
(frozen=True) class PackedSequencePlus(): ps = attr.ib() lengths = attr.ib() sort_to_orig = attr.ib(converter=np.array) orig_to_sort = attr.ib(converter=np.array) def descending(self, attribute, value): for (x, y) in zip(value, value[1:]): if (not (x >= y)): raise...
.django_db def test_converts_one_user(user_factory): user = user_factory() endpoint = convert_user_to_endpoint(user) assert (endpoint.id == str(user.id)) assert (endpoint.name == user.name) assert (endpoint.full_name == user.full_name) assert (endpoint.is_staff == user.is_staff) assert (endp...
def test__getting_started__example_variable_scaling(): from bioptim.examples.getting_started import example_variable_scaling 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=(1 / 10), n_shoot...
def allbadtonan(function): def f(data, axis=None, keepdims=None): if (keepdims is None): result = function(data, axis=axis) else: result = function(data, axis=axis, keepdims=keepdims) if ((LooseVersion(np.__version__) >= LooseVersion('1.9.0')) and hasattr(result, '__l...
(('%s.visualize_utils.plt' % __name__)) def test_show_img_boundary(mock_plt): img = np.random.rand(10, 10) boundary = [0, 0, 1, 0, 1, 1, 0, 1] with pytest.raises(AssertionError): visualize_utils.show_img_boundary([], boundary) with pytest.raises(AssertionError): visualize_utils.show_img_...
def generate_NUS_cross_val_split_files(root, split_num=5): raw_files = sorted(glob.glob(os.path.join(root, 'RAW/*.*'))) raw_processed_files = sorted(glob.glob(os.path.join(root, 'Raw_Processed/*.*'))) jpg_files = sorted(glob.glob(os.path.join(root, 'JPG/*.*'))) paired_files = list(zip(raw_files, raw_pro...
class TestPotential(unittest.TestCase): def create_test_molecule(): stretch = partial(Molecule.absolute_stretching, kwargs={'atom_pair': (1, 0)}) m = Molecule(geometry=[['H', [0.0, 0.0, 0.0]], ['D', [0.0, 0.0, 1.0]]], degrees_of_freedom=[stretch], masses=[1.6735328e-27, 3.444946e-27]) return...
def solar_cell_solver(solar_cell: SolarCell, task: str, user_options: Union[(Dict, State, None)]=None): if (type(user_options) in [State, dict]): options = merge_dicts(default_options, user_options) else: options = merge_dicts(default_options) prepare_solar_cell(solar_cell, options) opti...
class EmbeddingExtractor(object): def extract_sentbert(self, caption_file: str, output: str, dev: bool=True, zh: bool=False): from sentence_transformers import SentenceTransformer lang2model = {'zh': 'distiluse-base-multilingual-cased', 'en': 'bert-base-nli-mean-tokens'} lang = ('zh' if zh e...
class TestSpiderDev108(unittest.TestCase): (ONE_TEST_TIMEOUT) def test_spider_dev(self): split_name = 'dev' i_query = 108 db_id = get_db_id(split_name, i_query) (rdf_graph, schema) = get_graph_and_schema(split_name, db_id) sql_query = get_sql_query(split_name, i_query) ...
class CFB8(ModeWithInitializationVector): name = 'CFB8' def __init__(self, initialization_vector: bytes): utils._check_byteslike('initialization_vector', initialization_vector) self._initialization_vector = initialization_vector def initialization_vector(self) -> bytes: return self._...
class EpsilonGreedy(BaseExploration): def __init__(self, exploration_steps, epsilon): super().__init__(exploration_steps, epsilon) self.epsilon = epsilon['end'] def select_action(self, q_values, step_count): if ((np.random.rand() < self.epsilon) or (step_count <= self.exploration_steps))...
class PendulumEnv(gym.Env): metadata = {'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': 30} def __init__(self): self.max_speed = 8 self.max_torque = 2.0 self.dt = 0.05 self.viewer = None high = np.array([1.0, 1.0, self.max_speed]) self.action_sp...
class BaseCodec(nn.Module): def get_tokens(self, x, **kwargs): raise NotImplementedError def get_number_of_tokens(self): raise NotImplementedError def encode(self, img): raise NotImplementedError def decode(self, img_seq): raise NotImplementedError def forward(self, *...
class Server(): def __init__(self, port=50055, ssl_context=None): self.port = port self._ssl_context = ssl_context self.services = {} self._connection_count = 0 self._exception_count = 0 def add_service(self, service=None, context_manager=None, setup_fn=None, teardown_fn=...
def discriminator(image, y=None, reuse=False, for_G=False): if reuse: tf.get_variable_scope().reuse_variables() df_dim = 64 h0 = lrelu(conv2d(image, df_dim, name='d_h0_conv')) h1 = lrelu(conv2d(h0, (df_dim * 2), name='d_h1_conv')) h2 = lrelu(conv2d(h1, (df_dim * 4), name='d_h2_conv')) h3...
def tags_and_versions(tags: Iterable[Tag], translator: VersionTranslator) -> list[tuple[(Tag, Version)]]: ts_and_vs: list[tuple[(Tag, Version)]] = [] for tag in tags: try: version = translator.from_tag(tag.name) except (NotImplementedError, InvalidVersion) as e: log.warni...
.parametrize('marker, expected', [('python_version >= "3.6" and python_version < "4.0"', '>=3.6,<4.0'), ('sys_platform == "linux"', '*'), ('python_version >= "3.9" or sys_platform == "linux"', '*'), ('python_version >= "3.9" and sys_platform == "linux"', '>=3.9')]) def test_marker_properly_sets_python_constraint(marker...
def get_output_data(layer: torch.nn.Module, model: torch.nn.Module, images_in_one_batch: torch.Tensor) -> np.ndarray: def _hook_to_collect_output_data(module, _, out_data): out_data = utils.to_numpy(out_data) orig_layer_out_data.append(out_data) raise StopForwardException hook_handles = ...
class GenerateThread2Agent(GenerateThread): def __init__(self, rally_count: int, model1_path: str, is_model1_shuttleNet: bool, model1_shuttleNet_player: int, model2_path: str, is_model2_shuttleNet: bool, model2_shuttleNet_player: int, output_filename: str, parent=None): super().__init__(output_filename, par...
def new_focal_loss(logits, targets, alpha: float, gamma: float, normalizer, label_smoothing: float=0.01): pred_prob = logits.sigmoid() targets = targets.to(logits.dtype) onem_targets = (1.0 - targets) p_t = ((targets * pred_prob) + (onem_targets * (1.0 - pred_prob))) alpha_factor = ((targets * alpha...
def try_expanding_sum_type_to_union(typ: Type, target_fullname: str) -> ProperType: typ = get_proper_type(typ) if isinstance(typ, UnionType): items = [try_expanding_sum_type_to_union(item, target_fullname) for item in typ.relevant_items()] return make_simplified_union(items, contract_literals=Fa...
class ConfigHandler(Generic[Target]): section_prefix: str aliases: Dict[(str, str)] = {} def __init__(self, target_obj: Target, options: AllCommandOptions, ignore_option_errors, ensure_discovered: expand.EnsurePackagesDiscovered): self.ignore_option_errors = ignore_option_errors self.target_...
def get_data(lmdb_path, name, model_path): env = lmdb.open(lmdb_path, map_size=, max_dbs=64) align_db = env.open_db('align'.encode()) txn = env.begin(write=False) align_bin = txn.get(str(0).encode(), db=align_db) with open('../data/wav2lip_train/{}.mp4'.format(name), 'wb') as f: f.write(alig...
def community_detection(embeddings, threshold=0.75, min_community_size=10, init_max_size=1000): cos_scores = cos_sim(embeddings, embeddings) (top_k_values, _) = cos_scores.topk(k=min_community_size, largest=True) extracted_communities = [] for i in range(len(top_k_values)): if (top_k_values[i][(...
class DataLoader(): def __init__(self, id_transformer_group: IDTransformerGroup, dataloader, *, data_info: Dict[(int, str)]=None, paths: List[str]=None, num_prefetch=0): self._id_transformer_group = id_transformer_group if (data_info is not None): for (_, path) in data_info.items(): ...
def _switch_admin(sa: ServerApp, session: MultiplayerSession, membership: MultiplayerMembership): session_id = session.id verify_has_admin(sa, session_id, None, allow_when_no_admins=True) num_admins = MultiplayerMembership.select().where((MultiplayerMembership.session == session_id), is_boolean(MultiplayerM...
class TridentConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, trident_dilations=(1, 2, 3), test_branch_idx=1, bias=False): super(TridentConv, self).__init__() self.num_branch = len(trident_dilations) self.with_bias = bias self.test_branch_idx = te...
class Migration(migrations.Migration): dependencies = [('hotels', '0001_initial')] operations = [migrations.SeparateDatabaseAndState(database_operations=[migrations.AlterField(model_name='hotelroomreservation', name='user', field=models.ForeignKey('users.User', db_constraint=False, db_index=True, null=False, on...
class FIDInceptionE_1(models.inception.InceptionE): def __init__(self, in_channels): super(FIDInceptionE_1, self).__init__(in_channels) def forward(self, x): branch1x1 = self.branch1x1(x) branch3x3 = self.branch3x3_1(x) branch3x3 = [self.branch3x3_2a(branch3x3), self.branch3x3_2b...
class TradingCentres(): onedaydelta = datetime.timedelta(days=1) def __init__(self): self._centres = {} def __len__(self): return len(self._centres) def add(self, tc): self._centres[tc.code] = tc def _isbizday(self, dte): for c in self._centres.values(): i...
def call_gpt(prompt, model='code-davinci-002', stop=None, temperature=0.0, top_p=1.0, max_tokens=128, majority_at=None): num_completions = (majority_at if (majority_at is not None) else 1) num_completions_batch_size = 5 completions = [] for i in range((20 * ((num_completions // num_completions_batch_siz...
class StationSection(TableSection): keyword = b'STATION' table_setup = dict(header={None: b'Net Sta Type Latitude Longitude Coord Sys Elev On Date Off Date', 'GSE2.0': b'Sta Type Latitude Longitude Elev On Date Off Date'}, attribute='stations', cls=Station) stations = List.T(Sta...
class SpacedDiffusion(GaussianDiffusion): def __init__(self, use_timesteps, **kwargs): self.use_timesteps = set(use_timesteps) self.timestep_map = [] self.original_num_steps = len(kwargs['betas']) base_diffusion = GaussianDiffusion(**kwargs) last_alpha_cumprod = 1.0 n...
(config_path='config', config_name='voting_cls') def main(args): if (args.seed is None): args.seed = np.random.randint(1, 10000) torch.manual_seed(args.seed) np.random.seed(args.seed) torch.cuda.manual_seed_all(args.seed) torch.cuda.manual_seed(args.seed) torch.set_printoptions(10) t...
def plant(): import obspy obspy.Trace.to_pyrocko_trace = to_pyrocko_trace obspy.Trace.snuffle = snuffle obspy.Trace.fiddle = fiddle obspy.Stream.to_pyrocko_traces = to_pyrocko_traces obspy.Stream.snuffle = snuffle obspy.Stream.fiddle = fiddle obspy.core.event.Catalog.to_pyrocko_events = ...
_test def test_sequential_fit_generator(): ((x_train, y_train), (x_test, y_test)) = _get_test_data() def data_generator(train): if train: max_batch_index = (len(x_train) // batch_size) else: max_batch_index = (len(x_test) // batch_size) i = 0 while 1: ...
def derivatives_in_paraboloidal_coordinates(): coords = (u, v, phi) = symbols('u v phi', real=True) (par3d, er, eth, ephi) = Ga.build('e_u e_v e_phi', X=[((u * v) * cos(phi)), ((u * v) * sin(phi)), (((u ** 2) - (v ** 2)) / 2)], coords=coords, norm=True) grad = par3d.grad f = par3d.mv('f', 'scalar', f=Tr...
def test(): import gym import mani_skill.env env_name = 'OpenCabinetDoor-v0' env = gym.make(env_name) osc_interface = OperationalSpaceControlInterface(env_name) env.set_env_mode(obs_mode='state', reward_type='sparse') print(env.observation_space) print(env.action_space) for level_idx...
class SparseConv2d(SparseConvolution): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, indice_key=None): super(SparseConv2d, self).__init__(2, in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, indice_key=indice_k...
def _get_value_for_attr(obj, cls, orig_cls, sig_key, sig, meta_hints, attr_getters, **kwargs): if (obj and (sig_key in obj)): result = (sig_key, _get_value_from_obj(obj, cls, sig, sig_key, meta_hints, **kwargs)) elif (sig_key in attr_getters): attr_getter = attr_getters.pop(sig_key) resu...
class TestMiTempBtPoller(unittest.TestCase): TEST_MAC = '11:22:33:44:55:66' def test_format_bytes(self): self.assertEqual('AA BB 00', MiTempBtPoller._format_bytes([170, 187, 0])) def test_read_battery(self): poller = MiTempBtPoller(self.TEST_MAC, MockBackend) backend = self._get_back...
class OtherTests(unittest.TestCase): def setUp(self): self.proxy = Proxy() self.proxy._proxyfd = MockFd() def tearDown(self): UnmockClassMethods(Proxy) UnmockClassMethods(Server) def testProcessInputNonProxyPort(self): fd = MockFd(fd=111) MockClassMethod(Serve...
def generate_packets() -> DNSOutgoing: out = DNSOutgoing((const._FLAGS_QR_RESPONSE | const._FLAGS_AA)) address = socket.inet_pton(socket.AF_INET, '192.168.208.5') additionals = [{'name': 'HASS Bridge ZJWH FF5137._hap._tcp.local.', 'address': address, 'port': 51832, 'text': b'\x13md=HASS Bridge ZJWH\x06pv=1....
def embedding_layers(inputs, model_name, embedding_size=512, dropout_keep_prob=None, is_training=False, weight_decay=4e-05, scope=None): with tf.variable_scope('projection'): arg_scope = nets_factory.arg_scopes_map[model_name](weight_decay=weight_decay) with slim.arg_scope(arg_scope): wi...
def _box2cs(box, image_size): (x, y, w, h) = box[:4] aspect_ratio = ((1.0 * image_size[0]) / image_size[1]) center = np.zeros(2, dtype=np.float32) center[0] = (x + (w * 0.5)) center[1] = (y + (h * 0.5)) if (w > (aspect_ratio * h)): h = ((w * 1.0) / aspect_ratio) elif (w < (aspect_rat...
class Model(ModelBase): def __init__(self, *args, **kwargs): logger.debug('Initializing %s: (args: %s, kwargs: %s', self.__class__.__name__, args, kwargs) self.configfile = kwargs.get('configfile', None) if ('input_shape' not in kwargs): kwargs['input_shape'] = (64, 64, 3) ...
class CAGEAlgorithm(): def __init__(self, number_of_epochs=300): self.model = None self.number_of_epochs = number_of_epochs def run_experiments(self, data, experiments): results = [] for experiment in experiments: (description, train_objs, test_objs) = experiment ...
class ReplayMemory(object): def __init__(self, capacity): self.capacity = capacity self.memory = [] self.position = 0 def push(self, *args): if (len(self.memory) < self.capacity): self.memory.append(None) self.memory[self.position] = Transition(*args) ...
def getArgInt(name, args, min, max, main=True): if main: try: arg = next(args) except: doError((name + ': no argument supplied'), True) else: arg = args try: val = int(arg) except: doError((name + ': non-integer value given'), True) if ...
def check_ddp_consistency(module, ignore_regex=None): assert isinstance(module, torch.nn.Module) for (name, tensor) in named_params_and_buffers(module): if ('running' in name): continue fullname = ((type(module).__name__ + '.') + name) if ((ignore_regex is not None) and re.fu...
(max_runs=10) _with(Learner1D, Learner2D, LearnerND, AverageLearner, AverageLearner1D, SequenceLearner, with_all_loss_functions=False) def test_balancing_learner(learner_type, f, learner_kwargs): learners = [learner_type(generate_random_parametrization(f), **learner_kwargs) for i in range(4)] learner = Balancin...
def enum_attach(ctr_mol, nei_node, amap, singletons): (nei_mol, nei_idx) = (nei_node.mol, nei_node.nid) att_confs = [] black_list = [atom_idx for (nei_id, atom_idx, _) in amap if (nei_id in singletons)] ctr_atoms = [atom for atom in ctr_mol.GetAtoms() if (atom.GetIdx() not in black_list)] ctr_bonds ...
def state_dict_all_gather_keys(state_dict: Dict[(str, Union[(torch.Tensor, ShardedTensor)])], pg: ProcessGroup) -> List[str]: names = list(state_dict.keys()) all_names = ([None] * dist.get_world_size(pg)) dist.all_gather_object(all_names, names, pg) deduped_names = set() for local_names in all_names...
def test(net, config, master_bar, mode='test'): net.eval() num_nodes = config.num_nodes num_neighbors = config.num_neighbors batch_size = config.batch_size batches_per_epoch = config.batches_per_epoch beam_size = config.beam_size val_filepath = config.val_filepath val_target_filepath = c...
def _calculate_parquet_column_size(type_params: PartialParquetParameters, columns: List[str]): column_size = 0.0 for rg in type_params.row_groups_to_download: columns_found = 0 row_group_meta = type_params.pq_metadata.row_group(rg) for col in range(row_group_meta.num_columns): ...
class Effect11945(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Capital Projectile Turret')), 'trackingSpeed', src.getModifiedItemAttr('shipBonusTitanG1'), skill='Gallente Dreadnought', **kwargs...