code
stringlengths
281
23.7M
class TemporalModulation(nn.Module): def __init__(self, in_channels, out_channels, downsample_scale=8): super().__init__() self.conv = ConvModule(in_channels, out_channels, (3, 1, 1), stride=(1, 1, 1), padding=(1, 0, 0), bias=False, groups=32, conv_cfg=dict(type='Conv3d'), act_cfg=None) self...
class Loss(ABC): def __call__(self, predict: np.ndarray, target: np.ndarray) -> np.ndarray: return self.evaluate(predict, target) def evaluate(self, predict: np.ndarray, target: np.ndarray) -> np.ndarray: raise NotImplementedError def _validate_shapes(predict: np.ndarray, target: np.ndarray)...
def get_sorted_s_r_embed_limit(s_hist, s, r, ent_embeds, limit): s_hist_len = to_device(torch.LongTensor(list(map(len, s_hist)))) (s_len, s_idx) = s_hist_len.sort(0, descending=True) num_non_zero = len(torch.nonzero(s_len)) s_len_non_zero = s_len[:num_non_zero] s_len_non_zero = torch.where((s_len_no...
def test_read_pinned_buffer(tmpdir): data_fname = tmpdir.join('test_read.sigmf-data') actual = cp.random.rand(100).astype(cp.complex64) actual.tofile(data_fname) binary = cusignal.read_bin(str(data_fname), dtype=cp.complex64) buffer = cusignal.get_pinned_mem(binary.shape, cp.complex64) expect = ...
def get_train_val_data(data_path, tokenizer, val_data_path=None, val_set_size=1, augment_times=1, load_pre_prompt_dataset=False, vqa=False, add_input_prompt=False, eval_only=False, eval_items=None): if eval_only: return (None, get_val_data(val_data_path, tokenizer, val_set_size, eval_items=eval_items)) ...
.parametrize('exc', [ValueError, SystemExit]) def test_wrapper_exception(exc: 'Type[BaseException]') -> None: out = [] (wrapper=True) def m1(): out.append('m1 init') try: result = (yield) except BaseException as e: assert isinstance(e, exc) raise ...
def create_palette_from_dict(conf): palette = QtGui.QPalette() for (key, value) in conf.items(): (group, role) = key.split(':') if hasattr(QtGui.QPalette.ColorGroup, group): palette.setColor(getattr(QtGui.QPalette.ColorGroup, group), getattr(QtGui.QPalette.ColorRole, role), QtGui.QCo...
class _CanAssignBasedContext(): can_assign_ctx: CanAssignContext visitor: Optional['NameCheckVisitor'] = None errors: List[str] = field(default_factory=list) def on_error(self, message: str, *, code: ErrorCode=ErrorCode.incompatible_call, node: Optional[ast.AST]=None, detail: Optional[str]=..., replacem...
def test_stream_create(stream): assert (stream.is_unconnected == True) assert (stream.is_creating == False) assert (stream.is_ready == False) assert (stream.is_failed == False) assert (stream.is_terminated == False) with stream.mainloop.lock: stream.delete() assert (stream.is_unconne...
class UnbroadcastLayer(Layer): def __init__(self, incoming, broadcast_layer, **kwargs): self.broadcast_layer = broadcast_layer assert (len(incoming.output_shape) == len(self.broadcast_layer.output_shape)) incoming = AwaitLayer(incoming, layer_to_await=broadcast_layer) super(Unbroadca...
class GeoBUGSTextIO(fileio.FileIO): FORMATS = ['geobugs_text'] MODES = ['r', 'w'] def __init__(self, *args, **kwargs): args = args[:2] fileio.FileIO.__init__(self, *args, **kwargs) self.file = open(self.dataPath, self.mode) def read(self, n=(- 1)): self._complain_ifclosed...
def test_hetero_tuple_validation(): c = Converter(detailed_validation=True) with pytest.raises(IterableValidationError) as exc: c.structure(['1', 2, 'a'], Tuple[(int, int, int)]) assert (repr(exc.value.exceptions[0]) == repr(ValueError("invalid literal for int() with base 10: 'a'"))) assert (exc...
def get_files(**kwargs): metadata_directory = kwargs.get('metadata_directory', '') files = [] for f in get_template_files(**kwargs): if (str(f.path) == 'LICENSE.txt'): files.append(File(Path(metadata_directory, 'licenses', f.path), f.contents)) if (f.path.parts[0] != kwargs['pack...
class MovieGenres(Enum): Action = '28' Adventure = '12' Animation = '16' Comedy = '35' Crime = '80' Documentary = '99' Drama = '18' Family = '10751' Fantasy = '14' History = '36' Horror = '27' Music = '10402' Mystery = '9648' Romance = '10749' Science = '878' ...
def commands_spotting_challenge_validated(specific_features_dir: str, feature_name: str, run_name: str=RUN_NAME, results_dir: str=RESULTS_DIR, models_dir: str=MODELS_DIR, labels_dir: str=LABELS_DIR, splits_dir: str=SPLITS_DIR, base_config_dir: str=BASE_CONFIG_DIR, memory_setup: str=MEMORY_SETUP) -> List[Command]: d...
class InceptionV3Aux(InceptionV3): def __init__(self, num_classes=1000, in_chans=3, drop_rate=0.0, global_pool='avg', aux_logits=True): super(InceptionV3Aux, self).__init__(num_classes, in_chans, drop_rate, global_pool, aux_logits) def forward_features(self, x): x = self.forward_preaux(x) ...
.skipif((not is_py310_plus), reason='3.10+ union syntax') def test_roundtrip_generic_with_union() -> None: c = Converter() class A(): a: int class B(): b: int class Outer(Generic[T]): member: T raw = c.unstructure(Outer(A(1)), unstructure_as=Outer[(A | B)]) assert (c.stru...
class UDPEndpoint(): ip: IPAddress port: int def as_python_sockaddr(self) -> (tuple[(str, int)] | tuple[(str, int, int, int)]): sockaddr: (tuple[(str, int)] | tuple[(str, int, int, int)]) = (self.ip.compressed, self.port) if isinstance(self.ip, ipaddress.IPv6Address): sockaddr +=...
class ModbusSlaveContext(ModbusBaseSlaveContext): def __init__(self, *_args, **kwargs): self.store = {} self.store['d'] = kwargs.get('di', ModbusSequentialDataBlock.create()) self.store['c'] = kwargs.get('co', ModbusSequentialDataBlock.create()) self.store['i'] = kwargs.get('ir', Mod...
def calculate_loss_for_nq(start_logits, start_labels, end_logits, end_labels, pooled_logits, pooler_labels): def cross_entropy(logits, labels, reduction=None): vocab_size = logits.shape[(- 1)] labels = (labels[(..., None)] == jnp.arange(vocab_size)[None]).astype('f4') logits = jax.nn.log_sof...
class TestJit(object): def test_add_dict(self): def add_dict(oper): rets = (oper['x'] + oper['y']) return {'result': rets} def add_dict_pyfunc(oper): rets = (oper['x'] + oper['y']) return {'result': rets} a = torch.rand((3, 4)) b = torc...
def test_RankInvariantChecker_remove_one_alternative(): dm = skc.datasets.load_simple_stock_selection() dmaker = RemoveAlternativeDMaker(TOPSIS(), ['AA'], 1) rrt1 = RankInvariantChecker(dmaker, random_state=42, allow_missing_alternatives=True) result = rrt1.evaluate(dm) (_, rank) = result.ranks[1] ...
def init_test_environ(): global _TEMP_DIR, _BUS_INFO, _VDISPLAY _TEMP_DIR = tempfile.mkdtemp(prefix=fsnative('QL-TEST-')) os.environ['XDG_CACHE_HOME'] = xdg_get_cache_home() os.environ['GST_REGISTRY_UPDATE'] = fsnative('no') if util.is_flatpak(): del os.environ['GST_REGISTRY_UPDATE'] hom...
class TestBitFlags(unittest.TestCase): def test_bitflags(self): from functools import reduce import numpy as np from satpy.readers.olci_nc import BitFlags flag_list = ['SEA_ICE', 'MEGLINT', 'HIGHGLINT', 'CASE2_S', 'CASE2_ANOM', 'HAZE_OVER_WATER', 'WHITECAPS', 'AC_FAIL', 'BPAC_ON', 'W...
def get_flat_faces(faces, visited): flat_edges = list({e for f in faces for e in f.edges if ((len(e.link_faces) > 1) and equal(e.calc_face_angle(), 0))}) flat_faces = [] for e in flat_edges: for f in e.link_faces: if (not visited.get(f, False)): visited[f] = True ...
def cnn(): datagen = ImageDataGenerator(rescale=(1.0 / 255)) train_generator = datagen.flow_from_directory(train_data_dir, target_size=(img_width, img_height), batch_size=batch_size, class_mode='binary') validation_generator = datagen.flow_from_directory(validation_data_dir, target_size=(img_width, img_heig...
class configuration(): def __init__(self): self.currentFile = '' self.currentLabelFile = '' self.currentCorrectionFile = '' self.csPath = '' self.city = '' self.cityName = '' self.gtType = '' self.split = '' self.labelPath = '' self.cor...
class Backforward(textbase.TextBase): def __init__(self, parent=None): super().__init__(parent) self.enabled = False def on_tab_cur_url_changed(self, tabs): tab = tabs.widget.currentWidget() if (tab is None): self.setText('') self.hide() return...
class DistortionDataset(data.Dataset): def __init__(self, distorted_image_dir, corrected_image_dir, transform): self.distorted_image_paths = [] self.corrected_image_paths = [] for fs in os.listdir(distorted_image_dir): self.distorted_image_paths.append(os.path.join(distorted_imag...
class TransactionMined(): from_address: Address data: Union[(SmartContractCall, ByteCode, EthTransfer)] eth_node: Optional[EthClient] extra_log_details: Dict[(str, Any)] startgas: int gas_price: int nonce: Nonce transaction_hash: TransactionHash receipt: TxReceipt chain_id: Chain...
def KD_loss(args, teacher_g, noise, fake_img, fake_img_list, percept_loss): fake_img_teacher_list = teacher_g(noise, return_rgb_list=True) fake_img_teacher = fake_img_teacher_list[(- 1)] fake_img_teacher.requires_grad = True if (args.kd_l1_mode == 'Output_Only'): kd_l1_loss = (args.kd_l1_lambda ...
def main(args): savefolder = args.savefolder device = args.device os.makedirs(savefolder, exist_ok=True) if (not torch.cuda.is_available()): print('CUDA is not available! use CPU instead') else: cudnn.benchmark = True torch.backends.cudnn.deterministic = False torch.b...
class Obelisk(TutorialObject): def at_object_creation(self): super().at_object_creation() self.db.tutorial_info = 'This object changes its desc randomly, and makes sure to remember which one you saw.' self.db.puzzle_descs = ['You see a normal stone slab'] self.locks.add('get:false()'...
def main(): parser = argparse.ArgumentParser(description='Process some stuff') parser.add_argument('-r', '--run', dest='model_to_run', nargs='+') parser.add_argument('-rhs', '--run_hotstart', dest='hotstart_model_to_run', nargs='+') parser.add_argument('-sp', '--start_pool', dest='start_pool', nargs='+'...
def test_fix_cmd_darwin(): export_file_content = '\nC++ geobase5::details::lookup_impl::*\nC++ geobase5::hardcoded_service\n' filename = write_temp_file(export_file_content) args = ['-Wl,--version-script={}'.format(filename)] assert (fix_cmd('DARWIN', args) == ['-Wl,-exported_symbol,__ZN8geobase57detail...
_model_architecture('transformer_lm', 'transformer_lm_gpt3_large') def transformer_lm_gpt3_large(args): args.decoder_layers = getattr(args, 'decoder_layers', 24) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1536) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) ...
def test_method_ports(): incr = IncrMethodPorts() incr.apply(DefaultPassGroup()) print('\n==== Schedule ====') for blk in incr._sched.update_schedule: if (not blk.__name__.startswith('s')): print(blk.__name__) print('\n==== Line trace ====') print(' buf1 buf2') incr....
('/list/view_domain', methods=['POST']) _wrapper_json def list_domain_name(): json_data = request.get_json(force=True) domain_name = json_data.get('domain_name', '').strip() server_rooms = json_data.get('server_rooms', []) isps = json_data.get('isps', []) select_cdn = json_data.get('select_cdn', Tru...
class SmtPrinter(TreeWalker): def __init__(self, stream, annotations=None): TreeWalker.__init__(self) self.stream = stream self.write = self.stream.write self.mgr = get_env().formula_manager self.annotations = annotations def printer(self, f): self.walk(f) def...
def compute_dense_reward(self, action, obs): handle_dist = np.linalg.norm((obs[:3] - obs[4:7])) window_diff = np.linalg.norm((obs[4:7] - self.env._get_pos_goal())) action_reg = np.linalg.norm(action) (w1, w2, w3) = (1.0, 1.0, 0.1) reward = ((((- w1) * handle_dist) - (w2 * window_diff)) - (w3 * actio...
def get_array_date(scn_data, utc_date=None): if (utc_date is None): try: utc_date = scn_data.attrs['start_time'] except KeyError: try: utc_date = scn_data.attrs['scheduled_time'] except KeyError: raise KeyError('Scene has no start_t...
def chat_member_administrator(): return ChatMemberAdministrator(CMDefaults.user, CMDefaults.can_be_edited, CMDefaults.is_anonymous, CMDefaults.can_manage_chat, CMDefaults.can_delete_messages, CMDefaults.can_manage_video_chats, CMDefaults.can_restrict_members, CMDefaults.can_promote_members, CMDefaults.can_change_in...
def run(config): config['resolution'] = utils.imsize_dict[config['dataset']] config['n_classes'] = utils.nclass_dict[config['dataset']] config['G_activation'] = utils.activation_dict[config['G_nl']] config['D_activation'] = utils.activation_dict[config['D_nl']] if config['resume']: print('Sk...
('time.sleep') def test_wait_until_true_invoke_inline(mock_time_sleep): mock = MagicMock() mock.side_effect = ['test string 1', 'test string 2', 'test string 3', 'expected value', 'test string 5'] def decorate_me(arg1, arg2): assert (arg1 == 'v1') assert (arg2 == 'v2') return (mock(a...
class DropBertModel(): def __init__(self, args, network, state_dict=None, num_train_step=(- 1)): self.args = args self.train_loss = AverageMeter() self.step = 0 self.updates = 0 self.network = network if (state_dict is not None): print('Load Model!') ...
class SawyerButtonPressTopdownWallEnvV2(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, 0.05) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.1), 0.8, 0.115) obj_high = (0.1, 0.9, 0.115) super().__init__(self.model_name, hand_low=hand_low, hand_high=hand_high) ...
class Solution(object): def largestDivisibleSubset(self, nums): ls = len(nums) S = {(- 1): set()} for num in sorted(nums): candicate = [] for key in S: if ((num % key) == 0): candicate.append(S[key]) S[num] = (max(candic...
class Vgg19(vgg19.Vgg19): def build(self, gray, train=False): start_time = time.time() print('build model started') net = dict() with tf.variable_scope('vgg19', reuse=tf.AUTO_REUSE): gray_scaled = ((gray + 0.5) * 255.0) bgr = tf.concat([(gray_scaled - VGG_MEAN...
def test_simple(): def foo(a: int, /, b: int, c: str='', *, d: int=0, e: str, **kwargs: int) -> int: pass assert (get_callable_shape(foo) == Shape(input=InputShape(fields=(InputField(id='a', type=int, default=NoDefault(), metadata=MappingProxyType({}), original=ANY, is_required=True), InputField(id='b',...
class Light_estimation(nn.Module): def __init__(self): super(Light_estimation, self).__init__() self.dense = models.densenet121(pretrained=True).features self.pool = nn.AvgPool2d(8) self.color1 = nn.Linear(1024, 512, bias=False) self.relu1 = nn.ReLU() self.color2 = nn...
def test_poetry_with_explicit_pypi_and_other(fixture_dir: FixtureDirGetter, with_simple_keyring: None) -> None: io = BufferedIO() poetry = Factory().create_poetry(fixture_dir('with_explicit_pypi_and_other'), io=io) assert (len(poetry.pool.repositories) == 1) assert (len(poetry.pool.all_repositories) == ...
class CustomErrorCodePlugin(Plugin): def get_function_hook(self, fullname: str) -> (Callable[([FunctionContext], Type)] | None): if fullname.endswith('.main'): return self.emit_error return None def emit_error(self, ctx: FunctionContext) -> Type: ctx.api.fail('Custom error', ...
def prune_completely_outside_window(boxlist, window, scope=None): with tf.name_scope(scope, 'PruneCompleteleyOutsideWindow'): (y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1) (win_y_min, win_x_min, win_y_max, win_x_max) = tf.unstack(window) coordinat...
class FireUnit(nn.Module): def __init__(self, in_channels, squeeze_channels, expand1x1_channels, expand3x3_channels, residual): super(FireUnit, self).__init__() self.residual = residual self.squeeze = FireConv(in_channels=in_channels, out_channels=squeeze_channels, kernel_size=1, padding=0) ...
def test_L1_bit_selection(): a = CaseConnectBitSelToOutComp.DUT() a.elaborate() a.apply(StructuralRTLIRGenL1Pass(gen_connections(a))) connections = a.get_metadata(StructuralRTLIRGenL1Pass.connections) comp = sexp.CurComp(a, 's') assert (connections == [(sexp.PartSelection(sexp.CurCompAttr(comp, ...
def tensor4(name: Optional[str]=None, *, dtype: Optional['DTypeLike']=None, shape: Optional[tuple[(ST, ST, ST, ST)]]=(None, None, None, None)) -> 'TensorVariable': if (dtype is None): dtype = config.floatX shape = _validate_static_shape(shape, ndim=4) type = TensorType(dtype, shape=shape) return...
class TransformerEncoderLayer(nn.Module): def __init__(self, args): super().__init__() self.embed_dim = args.encoder_embed_dim self.lstm_san = args.encoder_lstm_san if self.lstm_san: self.self_attn = nn.LSTM(input_size=self.embed_dim, hidden_size=self.embed_dim, bidirecti...
class TestChangeProperty(EndianTest): def setUp(self): self.req_args_0 = {'data': (8, b''), 'mode': 0, 'property': , 'type': , 'window': } self.req_bin_0 = b'\x12\x00\x00\x06\x1dRr|i1\xd3\xd5\x04\x1c\xdcQ\x08\x00\x00\x00\x00\x00\x00\x00' self.req_args_1 = {'data': (8, b'foo'), 'mode': 1, 'pr...
def test_base_history(base_app): run_cmd(base_app, 'help') run_cmd(base_app, 'shortcuts') (out, err) = run_cmd(base_app, 'history') expected = normalize('\n 1 help\n 2 shortcuts\n') assert (out == expected) (out, err) = run_cmd(base_app, 'history he') expected = normalize('\n 1 h...
def convert_urdf(file: Path, urdf_dir: Path, out_dir: Path): tree = ET.parse(file) root = tree.getroot() for mesh_node in root.findall('.//mesh'): obj_file = mesh_node.attrib['filename'] obj_file = str(Path(obj_file).with_suffix('.obj')) glb_file = str(Path(obj_file).with_suffix('.gl...
def _node_to_pattern(node): if hasattr(node.op, 'connection_pattern'): connection_pattern = node.op.connection_pattern(node) if (not isinstance(connection_pattern, list)): raise TypeError((('Op.connection_pattern should return ' + f'list of list of bool, but for Op={node.op}') + f'got {c...
def test_repeated_show(): mesh = gfx.Mesh(gfx.sphere_geometry(), gfx.MeshPhongMaterial()) camera = gfx.PerspectiveCamera() scene = gfx.Scene() scene.add(mesh, camera.add(gfx.DirectionalLight())) camera.show_object(scene) cam_width = camera.width scene_radius = scene.get_world_bounding_sphere...
_HEADS.register_module() class ResLayer(nn.Module): def __init__(self, depth, stage=3, stride=2, dilation=1, style='pytorch', norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, with_cp=False, dcn=None): super(ResLayer, self).__init__() self.norm_eval = norm_eval self.norm_cfg = no...
(suppress_health_check=[HealthCheck.function_scoped_fixture], deadline=timedelta(seconds=10)) (args=st.lists(st.integers(min_value=0, max_value=1), max_size=2)) .filterwarnings('ignore:.*:pytest.PytestUnraisableExceptionWarning') def test_as_completed(ray_context, args): args = sorted(args, reverse=True) expect...
.parametrize('setting,expect_value', [(None, None), ('1', False), ('0', False)]) def test_no_color_env_var(runner, monkeypatch, setting, expect_value, boxed_context, in_tmp_dir, tmp_path): if (setting is None): monkeypatch.delenv('NO_COLOR', raising=False) else: monkeypatch.setenv('NO_COLOR', se...
class AstroidIndexError(AstroidError): def __init__(self, message: str='', node: ((nodes.NodeNG | bases.Instance) | None)=None, index: (nodes.Subscript | None)=None, context: (InferenceContext | None)=None, **kws: Any) -> None: self.node = node self.index = index self.context = context ...
def run(kubeconfig_path, scenario, pre_action_output=''): if (scenario.endswith('.yaml') or scenario.endswith('.yml')): logging.error('Powerfulseal support has recently been removed. Please switch to using plugins instead.') elif scenario.endswith('.py'): action_output = runcommand.invoke(('pyth...
class CalendarWrapperTests(unittest.TestCase): NO_HOLIDAYS_IN_MONTH = 0 CALENDARBK_WIDTH_COEFF = 9 CALENDARBK_HEIGHT_OFFSET = 112 TITLEBK_WIDTH_COEFF = 2 TITLEBK_HEIGHT_COEFF = 26.67 def setUp(self): self.app = Application().start(os.path.join(mfc_samples_folder, u'CmnCtrl1.exe')) ...
('document.tables is a list containing three tables') def then_document_tables_is_a_list_containing_three_tables(context): document = context.document tables = document.tables assert isinstance(tables, list) assert (len(tables) == 3) for table in tables: assert isinstance(table, Table)
class VBObject(AObject): FEATURE_FUNCS = {} def __init__(self, path=None): AObject.__init__(self, path=path) def initializeBlank(self): AObject.initializeBlank(self) self.a_info.update({'VBObjectType': self.VBOBJECT_TYPE()}) self.features = AFuncDict(owner=self, name='feature...
def test_describe_evaluated_once(testdir): testdir.makepyfile('\n count = 0\n def describe_is_evaluated_only_once():\n global count\n count += 1\n def one():\n assert count == 1\n def two():\n assert count == 1\n def ...
class TabHistoryItem(): def __init__(self, url, title, *, original_url=None, active=False, user_data=None, last_visited=None): self.url = url if (original_url is None): self.original_url = url else: self.original_url = original_url self.title = title s...
class ConvolutionalBoxPredictorBuilderTest(tf.test.TestCase): def test_box_predictor_calls_conv_argscope_fn(self): conv_hyperparams_text_proto = '\n regularizer {\n l1_regularizer {\n weight: 0.0003\n }\n }\n initializer {\n truncated_normal_initializer {\n ...
def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False): import re if isinstance(root_dir_or_dirs, str): rootdirs = [osp.expanduser(root_dir_or_dirs)] else: rootdirs = [osp.expanduser(d) for d in root_dir_or_dirs] allresults = [] for rootdir in ro...
def test_call_super_creates_temp_invalid(pe_bio_teacher): pe_bio_teacher.teach_new_classes(['Computer Science', 'Video Production', 'Life Science']) assert (len(pe_bio_teacher.currently_teaching) == 3) assert (pe_bio_teacher.wage == (pe_bio_teacher.wage_per_class * len(pe_bio_teacher.currently_teaching)))
class FrameManager(EventEmitter): Events = SimpleNamespace(FrameAttached='frameattached', FrameNavigated='framenavigated', FrameDetached='framedetached', LifecycleEvent='lifecycleevent', FrameNavigatedWithinDocument='framenavigatedwithindocument') def __init__(self, client: CDPSession, frameTree: Dict, page: An...
class CIFAR_ResNet50_BiFPN(nn.Module): def __init__(self, num_classes=100): super(CIFAR_ResNet50_BiFPN, self).__init__() self.backbone = CIFAR_ResNet50(num_classes=num_classes) self.bifpn = BiFPNc(self.backbone.network_channels, num_classes, repeat=1, depth=([1] * 3), width=1) def forwar...
def dequantize(arr, min_val, max_val, levels, dtype=np.float64): if (not (isinstance(levels, int) and (levels > 1))): raise ValueError(f'levels must be a positive integer, but got {levels}') if (min_val >= max_val): raise ValueError(f'min_val ({min_val}) must be smaller than max_val ({max_val})'...
def get_rel_loc_tensor(lat1, lon1, lat, lon, zoom): scale = (1 << zoom) (ul_proj_x, ul_proj_y) = project_with_scale_tensor(lat1, lon1, scale) ul_tile_x = (ul_proj_x // 1) ul_tile_y = (ul_proj_y // 1) ul_pixel_x = (ul_tile_x * TILE_SIZE) ul_pixel_y = (ul_tile_y * TILE_SIZE) (br_proj_x, br_pro...
class ContainedInput(PrimitiveInput): is_contained = True def __init__(self, containing_input, choice, refresh_widget=None): self.choice = choice self.containing_input = containing_input super().__init__(containing_input.form, choice.field, registers_with_form=False, refresh_widget=refre...
def fixed_padding(inputs, kernel_size, rate): kernel_size_effective = (kernel_size + ((kernel_size - 1) * (rate - 1))) pad_total = (kernel_size_effective - 1) pad_beg = (pad_total // 2) pad_end = (pad_total - pad_beg) padded_inputs = F.pad(inputs, (pad_beg, pad_end, pad_beg, pad_end)) return pad...
def summary_eval(model, loader, dset): model.eval() with torch.no_grad(): loss_list = [] top1_list = [] iter = 0 prob = [] target = [] file_name = [] for batch_data in loader: (loss, info) = model(batch_data) loss_list.append(loss.c...
_kernel_api(params={'oidp': POINTER}) def hook__sysctl_register_oid(ql, address, params): oidp = sysctl_oid_t(ql, params['oidp']) oidp = oidp.loadFromMem() oid_name = ql.mem.string(oidp.oid_name.value) oid_parent = b'' for (symname, symb) in ql.loader.kernel_extrn_symbols_detail.items(): if ...
class Bottleneck2D(nn.Module): expansion = 2 def __init__(self, inplanes, planes, stride=1, resample=None): super(Bottleneck2D, self).__init__() self.bn1 = nn.BatchNorm2d(inplanes) self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1) self.bn2 = nn.BatchNorm2d(planes) s...
.parametrize('rv_op, dist_params, base_size, cdf_name, params_conv', [(ptr.beta, [set_test_value(pt.dvector(), np.array([1.0, 2.0], dtype=np.float64)), set_test_value(pt.dscalar(), np.array(1.0, dtype=np.float64))], (2,), 'beta', (lambda *args: args)), (ptr.cauchy, [set_test_value(pt.dvector(), np.array([1.0, 2.0], dty...
def copy_data_to_device(data: T, device: torch.device, *args: Any, **kwargs: Any) -> T: if (_is_named_tuple(data) and isinstance(data, tuple)): return type(data)(**copy_data_to_device(data._asdict(), device, *args, **kwargs)) elif isinstance(data, (list, tuple)): return type(data)((copy_data_to_...
def make_patched_web3_get_block(original_func: Callable[([BlockIdentifier, bool], BlockData)]) -> Callable[([BlockIdentifier, bool], BlockData)]: def patched_web3_get_block(block_identifier: BlockIdentifier, full_transactions: bool=False) -> BlockData: last_ex: Optional[Exception] = None for remaini...
class Migration(migrations.Migration): dependencies = [('help', '0001_initial')] operations = [migrations.AlterField(model_name='helpentry', name='db_tags', field=models.ManyToManyField(blank=True, help_text='tags on this object. Tags are simple string markers to identify, group and alias objects.', to='typecla...
def get_executable(name: str, prefix: PathLike=sys.prefix, include_path=True) -> Optional[str]: executable = shutil.which(name) if (include_path and executable): return executable candidates = list(Path(prefix).resolve().glob(f'*/{name}*')) if candidates: path = (f.parent for f in sorted...
_model() _legacy_interface(weights=('pretrained', ResNet34_Weights.IMAGENET1K_V1)) def resnet34(*, weights: Optional[ResNet34_Weights]=None, progress: bool=True, **kwargs: Any) -> ResNet: weights = ResNet34_Weights.verify(weights) return _resnet(BasicBlock, [3, 4, 6, 3], weights, progress, **kwargs)
def test_single_dihedral(tmpdir): with tmpdir.as_cwd(): mol = Ligand.from_file(get_data('ethane.sdf')) qc_spec = QCOptions(program='rdkit', method='uff', basis=None) local_ops = LocalResource(cores=1, memory=1) tdrive = TorsionDriver(n_workers=1, grid_spacing=60) t_scan = Tor...
.xfail(reason='list-like is converted to list.') def test_type_index(df_checks_output): with pytest.raises(TypeError): df_checks_output.pivot_wider(index={'geoid'}, names_from='variable') with pytest.raises(TypeError): df_checks_output.pivot_wider(index=('geoid', 'name'), names_from='variable')
class TestApp(): def test_create_and_delete_app(self): _name_create = 'appjust4testcreate' _uri_create = '' _args = {'name': _name_create, 'title': 'whatever', 'region': app_region} with Call(acc_client, 'create_app', _args) as r: assert (r[0] is not None) _ur...
class ImageModel(QAbstractTableModel): def __init__(self, parent=None): super(ImageModel, self).__init__(parent) self.modelImage = QImage() def setImage(self, image): self.beginResetModel() self.modelImage = QImage(image) self.endResetModel() def rowCount(self, parent...
class RandomForestWrapper(RandomForestClassifier): def __init__(self, sampler=None, n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, ...
def _get_socketname(basedir): if utils.is_windows: return _get_socketname_windows(basedir) parts_to_hash = [getpass.getuser()] if (basedir is not None): parts_to_hash.append(basedir) data_to_hash = '-'.join(parts_to_hash).encode('utf-8') md5 = hashlib.md5(data_to_hash).hexdigest() ...
def nested_field_condition_1() -> models.Condition: value = random_real_word() lt = random.randint(1, 10) return models.NestedCondition(nested=models.Nested(key='nested.array', filter=models.Filter(must=[models.FieldCondition(key='word', match=models.MatchValue(value=value)), models.FieldCondition(key='numb...
.parametrize('bitsize', [2, 3, 4, 5]) .parametrize('arctan_bitsize', [5, 6, 7]) def test_phase_oracle(bitsize: int, arctan_bitsize: int): phase_oracle = ComplexPhaseOracle(ExampleSelect(bitsize), arctan_bitsize) g = cq_testing.GateHelper(phase_oracle) assert_valid_bloq_decomposition(phase_oracle) circui...
def test_no_monitor_reset_unless_done(): def assert_reset_raises(env): errored = False try: env.reset() except error.Error: errored = True assert errored, "Env allowed a reset when it shouldn't have" with helpers.tempdir() as temp: env = gym.make('...
def oncreate_init_py(unit, *args): keywords = {'DESTINATION': 1, 'INCLUDING_DEST_DIR': 0, 'RESULT': 1} (flat_args, spec_args) = sort_by_keywords(keywords, args) generated = [] dest_dir = (spec_args['DESTINATION'][0] if ('DESTINATION' in spec_args) else '$ARCADIA_BUILD_ROOT') if ('INCLUDING_DEST_DIR'...