code
stringlengths
281
23.7M
def test_multiple_decorators(): _along_last_axis _type_conversion def half_vec(x): assert (x.ndim == 1) return x[:(len(x) // 2)] for shape in [(10,), (2, 10), (2, 2, 10)]: for dtype in [np.float32, np.float16, np.float64]: x = np.ones(shape, dtype=dtype) y...
def attach_object_to_vehicle(object_id: int, vehicle_id: int, offset_x: float, offset_y: float, offset_z: float, rotation_x: float, rotation_y: float, rotation_z: float) -> bool: return AttachObjectToVehicle(object_id, vehicle_id, offset_x, offset_y, offset_z, rotation_x, rotation_y, rotation_z)
class WeylQuantizationTest(unittest.TestCase): def test_weyl_empty(self): res = weyl_polynomial_quantization('') self.assertTrue((res == QuadOperator.zero())) def test_weyl_one_term(self): op = QuadOperator('q0') res = weyl_polynomial_quantization('q0') self.assertTrue((r...
def orth_reg(net, loss, cof=1): orth_loss = 0 for m in net.modules(): if isinstance(m, nn.Linear): w = m.weight dimension = w.size()[0] eye_ = Variable(torch.eye(dimension), requires_grad=False).cuda() diff = (torch.matmul(w, w.t()) - eye_) mas...
() def daily_update_placements(day=None): (start_date, end_date) = get_day(day) log.info('Updating PlacementImpressions for %s-%s', start_date, end_date) queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(date__gte=start_date, date__lt=end_date) for values in queryset.values('publisher', 'adve...
class RCC_APB1LPENR(IntEnum): TIM2LPEN = (1 << 0) TIM3LPEN = (1 << 1) TIM4LPEN = (1 << 2) TIM5LPEN = (1 << 3) WWDGLPEN = (1 << 11) SPI2LPEN = (1 << 14) SPI3LPEN = (1 << 15) USART2LPEN = (1 << 17) I2C1LPEN = (1 << 21) I2C2LPEN = (1 << 22) I2C3LPEN = (1 << 23) PWRLPEN = (1 ...
def build_v2_index_specs(): return [IndexV2TestSpec('v2.list_all_tags', 'GET', PUBLIC_REPO).request_status(200, 200, 200, 200, 200), IndexV2TestSpec('v2.list_all_tags', 'GET', PRIVATE_REPO).request_status(401, 401, 200, 401, 200), IndexV2TestSpec('v2.list_all_tags', 'GET', ORG_REPO).request_status(401, 401, 200, 40...
class ExitCommand(command.Command): obj = None def func(self): if self.obj.access(self.caller, 'traverse'): self.obj.at_traverse(self.caller, self.obj.destination) elif self.obj.db.err_traverse: self.caller.msg(self.obj.db.err_traverse) else: self.obj....
def load_data(args, dataset_name): data_loader = load_partition_data_FashionMNIST (train_data_num, test_data_num, train_data_global, test_data_global, train_data_local_num_dict, test_data_local_num_dict, train_data_local_dict, test_data_local_dict, class_num_train, class_num_test) = data_loader(args.dataset, ar...
def dicom_file_loader(accept_multiple_files: bool, stop_before_pixels: bool) -> Sequence['pydicom.Dataset']: (left_column, right_column) = st.columns(2) if accept_multiple_files: file_string = 'files' else: file_string = 'file' with left_column: st.write(f'## Upload DICOM {file_s...
class TrueWind(BaseWind): def __init__(self, client, boatimu): super(TrueWind, self).__init__(client, 'truewind', boatimu) def compute_true_wind_direction(water_speed, wind_speed, wind_direction): rd = math.radians(wind_direction) windv = ((wind_speed * math.sin(rd)), ((wind_speed * math...
def test_filewritejson_filewritejson_not_iterable_raises(): context = Context({'k1': 'v1', 'fileWriteJson': 1}) with pytest.raises(ContextError) as err_info: filewrite.run_step(context) assert (str(err_info.value) == "context['fileWriteJson'] must exist, be iterable and contain 'path' for pypyr.step...
def highwaynet(inputs, scope, depth): with tf.variable_scope(scope): H = tf.layers.dense(inputs, units=depth, activation=tf.nn.relu, name='H') T = tf.layers.dense(inputs, units=depth, activation=tf.nn.sigmoid, name='T', bias_initializer=tf.constant_initializer((- 1.0))) return ((H * T) + (in...
def test_clean_comment(): from frigate.gen import clean_comment assert (clean_comment('# hello world') == 'hello world') assert (clean_comment('hello world') == 'hello world') assert (clean_comment('## # ## ## hello world') == 'hello world') assert (clean_comment(' # hello world ') == 'hello world'...
def test_lambert_conformat_conic_1sp_operation(): aeaop = LambertConformalConic1SPConversion(latitude_natural_origin=1, longitude_natural_origin=2, false_easting=3, false_northing=4, scale_factor_natural_origin=0.5) assert (aeaop.name == 'unknown') assert (aeaop.method_name == 'Lambert Conic Conformal (1SP)...
class TornadoRoleTest(ProvyTestCase): def setUp(self): super(TornadoRoleTest, self).setUp() self.role = TornadoRole(prov=None, context={}) def installs_necessary_packages_to_provision(self): with self.using_stub(AptitudeRole) as aptitude, self.using_stub(PipRole) as pip: self...
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', use_xavier=True, stddev=0.001, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: (kernel_h, kernel_w) = kernel_size num_in_c...
('build') ('flavour') ('--logs', '-l', is_flag=True, help='Show build logs') def build(flavour: str, logs: bool) -> None: if (not run_checks(flavour)): return flavour_config = get_key_values_from_config(flavour) flavour_dockerfile = create_dockerfile(flavour_config['base'], flavour_config['install']...
class Cabinet(models.Model): idc = models.ForeignKey('IDC', related_name='cabinet', on_delete=models.CASCADE) cabinet_name = models.CharField(max_length=64, unique=True, verbose_name='') cabinet_memo = models.CharField(max_length=100, blank=True, null=True, verbose_name='') class Meta(): db_tabl...
def test_remove_world_from_session(server_app): session = {'worlds': [1234]} server_app.session = MagicMock() server_app.session.return_value.__enter__.return_value = session world = MagicMock() world.id = 1234 server_app.remove_world_from_session(world) assert (session == {'worlds': []})
def test_build_overviews_new_file(tmpdir, path_rgb_byte_tif): dst_file = str(tmpdir.join('test.tif')) with rasterio.open(path_rgb_byte_tif) as src: with rasterio.open(dst_file, 'w', **src.profile) as dst: dst.write(src.read()) overview_factors = [2, 4] dst.build_overv...
def main(): batch_size = 16 data_path = './data/nyu_depth_v2_labeled.mat' learning_rate = 0.0001 monentum = 0.9 weight_decay = 0.0005 num_epochs = 100 (train_lists, val_lists, test_lists) = load_split() print('Loading data...') train_loader = torch.utils.data.DataLoader(NyuDepthLoade...
def dump_dataclass(obj: Any): assert (dataclasses.is_dataclass(obj) and (not isinstance(obj, type))), 'dump_dataclass() requires an instance of a dataclass.' ret = {'_target_': _convert_target_to_string(type(obj))} for f in dataclasses.fields(obj): v = getattr(obj, f.name) if dataclasses.is_...
class _ConvNdMtl(Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias): super(_ConvNdMtl, self).__init__() if ((in_channels % groups) != 0): raise ValueError('in_channels must be divisible by groups') ...
def test_save_action_additional_extensions(default_file): existing_config(default_file) opts = dict(author='author', email='email', license='MPL-2.0', my_extension1_opt=5) extensions = [make_extension('MyExtension1'), make_extension('MyExtension2'), make_extension('MyExtension3', persist=False)] config....
class GeometryOptimizer(lib.StreamObject): def __init__(self, method): self.method = method self.callback = None self.params = {} self.converged = False self.max_cycle = 100 def cell(self): return self.method.cell def cell(self, x): self.method.cell = ...
class DistributedTest(TestCase): def _test_fullsync(rank, world_size, backend, q): dist.init_process_group(backend, rank=rank, world_size=world_size) data_length = 23 dp = IterableWrapper(list(range(data_length))).sharding_filter() torch.utils.data.graph_settings.apply_sharding(dp, w...
class Migration(migrations.Migration): dependencies = [('adserver', '0003_publisher-advertiser-adtype')] operations = [migrations.AddField(model_name='adimpression', name='publisher', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='adserver.Publisher')), migration...
def test_geoid_model_name(): wkt = 'COMPOUNDCRS["NAD83 / Pennsylvania South + NAVD88 height",\n PROJCRS["NAD83 / Pennsylvania South",\n BASEGEOGCRS["NAD83",\n DATUM["North American Datum 1983",\n ELLIPSOID["GRS 1980",6378137,298.,\n LENGTHUNIT["metre",1]]],\n ...
def test_state_wait_secretrequest_valid_amount_and_fee(): fee_amount = 5 setup = setup_initiator_tests(allocated_fee=fee_amount) state_change = ReceiveSecretRequest(payment_identifier=UNIT_TRANSFER_IDENTIFIER, amount=(setup.lock.amount - fee_amount), expiration=setup.lock.expiration, secrethash=setup.lock.s...
def test_struct_comparison2(): m = run_mod('\n #lang pycket\n (require racket/private/generic-interfaces)\n\n (struct lead (width height)\n #:methods\n gen:equal+hash\n [(define (equal-proc a b equal?-recur)\n ; compare a and b\n (and (equal?-recur (lead-width a) (lead-width ...
def test_Join_view(): vals = (set_test_value(pt.matrix(), rng.normal(size=(2, 2)).astype(config.floatX)), set_test_value(pt.matrix(), rng.normal(size=(2, 2)).astype(config.floatX))) g = ptb.Join(view=1)(1, *vals) g_fg = FunctionGraph(outputs=[g]) with pytest.raises(NotImplementedError): compare_...
def CheckForBadCharacters(filename, lines, error): for (linenum, line) in enumerate(lines): if (u'' in line): error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if ('\x00' in line): error(filename, linenum, 'read...
class Describe_ChunkParser(): def it_can_construct_from_a_stream(self, stream_, StreamReader_, stream_rdr_, _ChunkParser__init_): chunk_parser = _ChunkParser.from_stream(stream_) StreamReader_.assert_called_once_with(stream_, BIG_ENDIAN) _ChunkParser__init_.assert_called_once_with(ANY, strea...
def nooper(cls): def empty_func(*args, **kwargs): pass empty_methods = {m_name: empty_func for m_name in cls.__abstractmethods__} if (not empty_methods): raise NoopIsANoopException(('nooper implemented no abstract methods on %s' % cls)) return type(cls.__name__, (cls,), empty_methods)
def system_command_call(command, shell=True): if (shell and isinstance(command, list)): command = subprocess.list2cmdline(command) try: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell) (stdout, stderr) = process.communicate() if (pr...
def write_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file, verbose_logging, version_2_with_negative, null_score_diff_threshold): logger.info(('Writing predictions to: %s' % output_prediction_file...
def usersMap(theRequest): users = [] myUserCount = QgisUser.objects.all().count() myRandomUser = None myRandomUsers = QgisUser.objects.exclude(image='').order_by('?')[:1] if (myRandomUsers.count() > 0): myRandomUser = myRandomUsers[0] for user in QgisUser.objects.all(): users.app...
class Effect7097(BaseEffect): type = 'passive' def handler(fit, skill, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Precursor Weapon')), 'damageMultiplier', (skill.getModifiedItemAttr('damageMultiplierBonus') * skill.level), **kwargs)
class TestBotDescriptionWithoutRequest(TestBotDescriptionBase): def test_slot_behaviour(self, bot_description): for attr in bot_description.__slots__: assert (getattr(bot_description, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(bot_description)) == len(set(mr...
class HumanoidStandupEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): mujoco_env.MujocoEnv.__init__(self, 'humanoidstandup.xml', 5) utils.EzPickle.__init__(self) def _get_obs(self): data = self.model.data return np.concatenate([data.qpos.flat[2:], data.qvel.flat, da...
def test_view_node(caller, **kwargs): text = ('\n Your name is |g%s|n!\n\n click |lclook|lthere|le to trigger a look command under MXP.\n This node\'s option has no explicit key (nor the "_default" key\n set), and so gets assigned a number automatically. You can infact\n -always- use numbers (1...N) ...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, norm_layer=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self.inplanes = 64 self.groups = grou...
def uiGetFilePath(initial_path=None): try: if initial_path: output = subprocess.check_output('osascript -e \'set strPath to POSIX file "{}"\' -e \'set theDocument to choose file with prompt "Please select a document to process:" default location strPath\' -e \'set theDocument to (the POSIX path ...
class Login(LoginView): form_class = LoginForm template_name = 'dictionary/registration/login.html' def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me', False) session_timeout = ((86400 * 30) if remember_me else 86400) self.request.session.set_expiry(session...
def load_openai_model(name: str, precision: Optional[str]=None, device: Optional[Union[(str, torch.device)]]=None, jit: bool=True, cache_dir: Optional[str]=None): if (device is None): device = ('cuda' if torch.cuda.is_available() else 'cpu') if (precision is None): precision = ('fp32' if (device...
class TestVersion(unittest.TestCase): def test_version(self): version = pyppeteer.version self.assertTrue(isinstance(version, str)) self.assertEqual(version.count('.'), 2) def test_version_info(self): vinfo = pyppeteer.version_info self.assertEqual(len(vinfo), 3) ...
def async_wraps(cls: type[object], wrapped_cls: type[object], attr_name: str) -> t.Callable[([CallT], CallT)]: def decorator(func: CallT) -> CallT: func.__name__ = attr_name func.__qualname__ = '.'.join((cls.__qualname__, attr_name)) func.__doc__ = 'Like :meth:`~{}.{}.{}`, but async.\n\n ...
def get_solcast_historic(latitude, longitude, start, api_key, end=None, duration=None, map_variables=True, **kwargs): params = dict(latitude=latitude, longitude=longitude, start=start, end=end, duration=duration, api_key=api_key, format='json', **kwargs) data = _get_solcast(endpoint='historic/radiation_and_weat...
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): if (((class_info.last_line - class_info.starting_linenum) <= 24) or (linenum <= class_info.starting_linenum)): return matched = Match('\\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: prev_li...
class IDBH(tc.nn.Module): def __init__(self, version): super().__init__() if (version == 'cifar10-weak'): layers = [T.RandomHorizontalFlip(), CropShift(0, 11), ColorShape('color'), T.ToTensor(), T.RandomErasing(p=0.5)] elif (version == 'cifar10-strong'): layers = [T.R...
def build_dataset(is_train, args, infer_no_resize=False): transform = build_transform(is_train, args, infer_no_resize) if (args.data_set == 'CIFAR100'): dataset = datasets.CIFAR100(args.data_path, train=is_train, transform=transform, download=True) nb_classes = 100 elif (args.data_set == 'CI...
def test_should_show_fixtures_used_by_test(pytester: Pytester) -> None: pytester.makeconftest('\n import pytest\n \n def arg1():\n """arg1 from conftest"""\n \n def arg2():\n """arg2 from conftest"""\n ') p = pytester.makepyfile('\n import pytes...
def test_recompute_equilibrium(verbose=True, warnings=True, plot=True, *args, **kwargs): if plot: import matplotlib.pyplot as plt plt.ion() s1 = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.01.spec')) s1.rescale_path_length(100) assert s1.is_at_equilibrium() s1.update('emisscoe...
class ImageToWordModel(OnnxInferenceModel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def predict(self, image: np.ndarray): image = cv2.resize(image, self.input_shape[:2][::(- 1)]) image_pred = np.expand_dims(image, axis=0).astype(np.float32) preds = ...
class SubQueryLineageHolder(ColumnLineageMixin): def __init__(self) -> None: self.graph = nx.DiGraph() def __or__(self, other): self.graph = nx.compose(self.graph, other.graph) return self def _property_getter(self, prop) -> Set[Union[(SubQuery, Table)]]: return {t for (t, at...
def compute_checksum(filename, hashtype): file = os.fsdecode(filename) if (not exists(file)): return None buf = fsbsize(filename) if (hashtype in ('adler32', 'crc32')): hf = getattr(zlib, hashtype) last = 0 with open(file, mode='rb') as fp: for chunk in iter((...
def test_context(): with pm.Model(): pm.Normal('x') ctx = multiprocessing.get_context('spawn') with warnings.catch_warnings(): warnings.filterwarnings('ignore', '.*number of samples.*', UserWarning) pm.sample(tune=2, draws=2, chains=2, cores=2, mp_ctx=ctx)
def test_componentanimation(): vc = OSC.utils._VehicleComponent(OSC.VehicleComponentType.doorFrontLeft) vc2 = OSC.utils._VehicleComponent(OSC.VehicleComponentType.doorRearRight) udc = OSC.UserDefinedComponent('my_component') udc2 = OSC.UserDefinedComponent('my_component2') udc3 = OSC.UserDefinedComp...
def prime_factors(obj): visited = set((obj,)) ef = getattr(obj, '_e_factors', None) if (not ef): return fn = ef[0] e = getattr(obj, fn, None) if (e in visited): raise RecursiveFactor(obj, e) visited.add(e) (yield (fn, e)) while (e is not None): ef = getattr(ob...
class GroupPointTest(tf.test.TestCase): def test(self): pass def test_grad(self): with tf.device('/gpu:0'): points = tf.constant(np.random.random((1, 128, 16)).astype('float32')) print(points) xyz1 = tf.constant(np.random.random((1, 128, 3)).astype('float32'))...
def rand_reach(): vp = np.random.uniform(low=0, high=360) goal = np.concatenate([np.random.uniform(low=(- 1.1), high=(- 0.5), size=1), np.random.uniform(low=0.5, high=1.1, size=1)]).tolist() armcolor = getcolor() bgcolor = getcolor() while (np.linalg.norm((bgcolor - armcolor)) < 0.5): bgcolo...
class LR_Scheduler(object): def __init__(self, mode, base_lr, num_epochs, iters_per_epoch=0, lr_step=0, warmup_epochs=0): self.mode = mode print('Using {} LR Scheduler!'.format(self.mode)) self.lr = base_lr if (mode == 'step'): assert lr_step self.lr_step = lr_ste...
class _AttributeCollector(): def __init__(self, type): self.attributes = {} self.type = type def __call__(self, name, returned=None, function=None, argnames=['self'], check_existence=True, parent=None): try: builtin = getattr(self.type, name) except AttributeError: ...
class VSA_Module(nn.Module): def __init__(self, opt={}): super(VSA_Module, self).__init__() channel_size = opt['multiscale']['multiscale_input_channel'] out_channels = opt['multiscale']['multiscale_output_channel'] embed_dim = opt['embed']['embed_dim'] self.LF_conv = nn.Conv2...
def register_mot_instances(name, metadata, json_file, image_root): assert isinstance(name, str), name assert isinstance(json_file, (str, os.PathLike)), json_file assert isinstance(image_root, (str, os.PathLike)), image_root DatasetCatalog.register(name, (lambda : load_video_json(json_file, image_root, n...
def set_project(apps, schema_editor): Value = apps.get_model('projects', 'Value') Snapshot = apps.get_model('projects', 'Snapshot') for value in Value.objects.all(): value.project = value.snapshot.project value.snapshot = None value.save() for snapshot in Snapshot.objects.all(): ...
class CmdCancel(SubCommand): def add_arguments(self, subparser: argparse.ArgumentParser) -> None: subparser.add_argument('app_handle', type=str, help='torchx app handle (e.g. local://session-name/app-id)') def run(self, args: argparse.Namespace) -> None: app_handle = args.app_handle runn...
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0, sr_ratio=1, apply_transform=False): super().__init__() self.num_heads = num_heads head_dim = (dim // num_heads) self.scale = (qk_scale or (head_dim ** (- 0.5)...
.parametrize(('prefer_metroids', 'prefer_stronger_metroids', 'prefer_bosses', 'expected_max_slider'), [(True, False, False, 25), (False, True, False, 14), (False, False, True, 4), (True, True, False, 39), (True, False, True, 29), (False, True, True, 18), (True, True, True, 39)]) def test_preferred_dna(skip_qtbot, msr_g...
def load_tf_sess_variables_to_keras_single_gpu(path: 'str', compressed_ops: List['str']) -> tf.compat.v1.keras.Model: to_ignore = map(change_name_of_compressed_op, compressed_ops) class Model(tf.compat.v1.keras.Model): def __init__(self): super(Model, self).__init__() self.import...
def test_edit_file_with_spaces(base_app, request, monkeypatch): base_app.editor = 'fooedit' m = mock.MagicMock(name='Popen') monkeypatch.setattr('subprocess.Popen', m) test_dir = os.path.dirname(request.module.__file__) filename = os.path.join(test_dir, 'my commands.txt') run_cmd(base_app, 'edit...
def write_data(flag, image, text_only): def read_post(flag): stop_words = stopwordslist() pre_path = '../Data/weibo/tweets/' file_list = [(pre_path + 'test_nonrumor.txt'), (pre_path + 'test_rumor.txt'), (pre_path + 'train_nonrumor.txt'), (pre_path + 'train_rumor.txt')] if (flag == 't...
.parametrize('value, kwargs, result', (('5,6,7', {}, [5, 6, 7]), ('5.6.7', {'separator': '.'}, [5, 6, 7]), ('5,6,7', {'cast': str}, ['5', '6', '7']), ('X,Y,Z', {}, ['X', 'Y', 'Z']), ('X,Y,Z', {'cast': str}, ['X', 'Y', 'Z']), ('X.Y.Z', {'separator': '.'}, ['X', 'Y', 'Z']), ('0,5,7.1', {'cast': bool}, [False, True, True]...
class Table(QtWidgets.QTableView): supported_formats = {'CSV file (*.csv)': 'csv', 'Excel file (*.xlsx)': 'excel', 'HTML file (*.html *.htm)': 'html', 'JSON file (*.json)': 'json', 'LaTeX file (*.tex)': 'latex', 'Markdown file (*.md)': 'markdown', 'XML file (*.xml)': 'xml'} def __init__(self, refresh_time=0.2, ...
def prepare_batch_inputs_audio(batched_model_inputs, device, non_blocking=False): model_inputs = dict(src_txt=batched_model_inputs['query_feat'][0].to(device, non_blocking=non_blocking), src_txt_mask=batched_model_inputs['query_feat'][1].to(device, non_blocking=non_blocking), src_vid=batched_model_inputs['video_fea...
class RetrievalRecall(Metric[torch.Tensor]): def __init__(self: TRetrievalRecall, *, empty_target_action: Union[(Literal['neg'], Literal['pos'], Literal['skip'], Literal['err'])]='neg', k: Optional[int]=None, limit_k_to_size: bool=False, num_queries: int=1, avg: Optional[Union[(Literal['macro'], Literal['none'])]]=...
class DataSuite(): files: list[str] base_path = test_temp_dir data_prefix = test_data_prefix required_out_section = False native_sep = False test_name_suffix = '' def setup(self) -> None: def run_case(self, testcase: DataDrivenTestCase) -> None: raise NotImplementedError
.fast def test_all_slit_shapes(FWHM=0.4, verbose=True, plot=True, close_plots=True, *args, **kwargs): _clean(plot, close_plots) from radis.spectrum.spectrum import Spectrum from radis.test.utils import getTestFile s = Spectrum.from_txt(getTestFile('calc_N2C_spectrum_Trot1200_Tvib3000.txt'), quantity='ra...
def keras_sequential_conv_net(): model = tf.keras.Sequential([tf.keras.layers.Input(shape=(28, 28, 3)), tf.keras.layers.Conv2D(4, kernel_size=3, activation=None), tf.keras.layers.BatchNormalization(), tf.keras.layers.Activation('relu'), tf.keras.layers.AvgPool2D(), tf.keras.layers.Dense(10)]) return model
class L2Step(AttackerStep): def project(self, x): diff = (x - self.orig_input) diff = diff.renorm(p=2, dim=0, maxnorm=self.eps) return (self.orig_input + diff) def make_step(self, g): g_norm = ch.norm(g.view(g.shape[0], (- 1)), dim=1).view((- 1), 1, 1, 1) scaled_g = (g / ...
class SawyerDoorCloseEnv(SawyerDoorEnv): def __init__(self): super().__init__() self.init_config = {'obj_init_angle': 0.3, 'obj_init_pos': np.array([0.1, 0.95, 0.1], dtype=np.float32), 'hand_init_pos': np.array([0, 0.6, 0.2], dtype=np.float32)} self.goal = np.array([0.2, 0.8, 0.15]) ...
def test_plot_area_def_w_swath_def(create_test_swath): swath_def = _gen_swath_def_numpy(create_test_swath) with mock.patch('matplotlib.pyplot.savefig') as mock_savefig: plot_area_def(swath_def, fmt='svg') mock_savefig.assert_called_with(ANY, format='svg', bbox_inches='tight')
def _path_tree_for_react_dnd_treeview(tree: list, id_to_path_dict: dict, path: str, parent: int, highlighted_files: list=[]) -> list: for item in os.listdir(path): if item.startswith('.'): continue item_path = os.path.join(path, item) droppable = os.path.isdir(item_path) ...
.parametrize('repo, commit_parser, translator, commit_messages,prerelease, expected_new_version', xdist_sort_hack([(lazy_fixture(repo_fixture_name), lazy_fixture(parser_fixture_name), translator, commit_messages, prerelease, expected_new_version) for ((repo_fixture_name, parser_fixture_name, translator), values) in {('...
class AnyExpressionsReporter(AbstractReporter): def __init__(self, reports: Reports, output_dir: str) -> None: super().__init__(reports, output_dir) self.counts: dict[(str, tuple[(int, int)])] = {} self.any_types_counter: dict[(str, collections.Counter[int])] = {} def on_file(self, tree:...
def construct_pred_set(predicted_args, cur_event, context_words, doc, args): trigger_start = cur_event['trigger']['start'] trigger_end = cur_event['trigger']['end'] predicted_set = set() lowercased_context_words = [w.lower() for w in context_words] lowercased_doc = (nlp(' '.join(lowercased_context_w...
class TestWeightSvdPruning(unittest.TestCase): def test_prune_layer(self): model = mnist_model.Net() input_shape = (1, 1, 28, 28) dummy_input = create_rand_tensors_given_shapes(input_shape, get_device(model)) orig_layer_db = LayerDatabase(model, dummy_input) comp_layer_db = c...
def test_eigen_transform_ket(): N = 5 a = qutip.destroy(N) op = (((a * a.dag()) + a) + a.dag()) eigenT = _EigenBasisTransform(qutip.QobjEvo(op)) op_diag = qutip.qdiags(eigenT.eigenvalues(0), [0]) state = qutip.coherent(N, 1.1) expected = (op state).full() computed = eigenT.from_eigbasis...
def test_atlas_glyps(): assert isinstance(global_atlas, GlyphAtlas) atlas = GlyphAtlas() gs = 50 array_id = id(atlas._array) assert (atlas.get_index_from_hash('0') is None) i0 = atlas.store_region_with_hash('0', glyphgen(gs)) assert isinstance(i0, int) (atlas.get_index_from_hash('0') == ...
def eval_video_single(cfg, models, device, test_loader, interp, fixed_test_size, verbose): if (cfg.SOURCE == 'Viper'): palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 190, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, 220, 20, 60, 0, 0, 142, 0, 0, 70, 0, 60, 100, 0, 0, 2...
def test_emit_warning_when_event_loop_fixture_is_redefined(pytester: Pytester): pytester.makepyfile(dedent(' import asyncio\n import pytest\n\n \n def event_loop():\n loop = asyncio.new_event_loop()\n yield loop\n loop.close()\...
class Plugin(KeepKeyPlugin, QtPlugin): icon_paired = 'keepkey.png' icon_unpaired = 'keepkey_unpaired.png' def create_handler(self, window): return QtHandler(window, self.pin_matrix_widget_class(), self.device) def pin_matrix_widget_class(self): from keepkeylib.qt.pinmatrix import PinMatr...
def configInputQueue(): def captureInput(iqueue): while True: c = getch() if ((c == '\x03') or (c == '\x04')): log.debug('Break received (\\x{0:02X})'.format(ord(c))) iqueue.put(c) break log.debug("Input Char '{}' received"....
class KeywordImpression(BaseImpression): keyword = models.CharField(_('Keyword'), max_length=1000) publisher = models.ForeignKey(Publisher, related_name='keyword_impressions', on_delete=models.PROTECT) advertisement = models.ForeignKey(Advertisement, related_name='keyword_impressions', on_delete=models.PROT...
class HotelRoom(): id: str name: str = strawberry.field(resolver=make_localized_resolver('name')) description: str = strawberry.field(resolver=make_localized_resolver('description')) price: str is_sold_out: bool capacity_left: int def available_bed_layouts(self) -> List[BedLayout]: r...
def test_quantsim_export_quantizer_args(): if (version.parse(tf.version.VERSION) >= version.parse('2.00')): model = dense_functional() rand_inp = np.random.randn(100, 5) qsim = QuantizationSimModel(model, quant_scheme=QuantScheme.post_training_tf_enhanced, default_param_bw=16, default_output...
.parametrize('use_enemy_attribute_randomizer', [False, True]) def test_on_preset_changed(skip_qtbot, preset_manager, use_enemy_attribute_randomizer): base = preset_manager.default_preset_for_game(RandovaniaGame.METROID_PRIME).get_preset() preset = dataclasses.replace(base, uuid=uuid.UUID('b41fde84-1f57-4b79-8cd...
def register_model(name, dataclass=None): def register_model_cls(cls): if (name in MODEL_REGISTRY): raise ValueError('Cannot register duplicate model ({})'.format(name)) if (not issubclass(cls, BaseFairseqModel)): raise ValueError('Model ({}: {}) must extend BaseFairseqModel'...
class dist_info(Command): description = 'DO NOT CALL DIRECTLY, INTERNAL ONLY: create .dist-info directory' user_options = [('output-dir=', 'o', 'directory inside of which the .dist-info will becreated (default: top of the source tree)'), ('tag-date', 'd', 'Add date stamp (e.g. ) to version number'), ('tag-build...