code
stringlengths
281
23.7M
class TestPassportElementErrorFrontSideWithoutRequest(TestPassportElementErrorFrontSideBase): def test_slot_behaviour(self, passport_element_error_front_side): inst = passport_element_error_front_side for attr in inst.__slots__: assert (getattr(inst, attr, 'err') != 'err'), f"got extra s...
def test_uniform_types_uniform_type(): for cls in material_classes: ob = cls() assert isinstance(ob.uniform_type, dict) for super_cls in cls.mro(): if (super_cls is cls): continue elif (not hasattr(super_cls, 'uniform_type')): break ...
def calculate_d_to_volume_for_labels(dose_grid, labels, volume, volume_in_cc=False): if (not isinstance(volume, list)): volume = [volume] metrics = [] for label in labels: m = {'label': label} for v in volume: col_name = f'D{v}' if volume_in_cc: ...
def total_token_network_channels(chain_state: ChainState, token_network_registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress) -> int: token_network = get_token_network_by_token_address(chain_state, token_network_registry_address, token_address) result = 0 if token_network: resu...
_module() class MaskedCrossEntropyLoss(nn.Module): def __init__(self, num_labels=None, ignore_index=0): super().__init__() self.num_labels = num_labels self.criterion = CrossEntropyLoss(ignore_index=ignore_index) def forward(self, logits, img_metas): labels = img_metas['labels'] ...
def get_coord_add(dataset_name: str): import numpy as np options = {'mnist': ([[[8.0, 8.0], [12.0, 8.0], [16.0, 8.0]], [[8.0, 12.0], [12.0, 12.0], [16.0, 12.0]], [[8.0, 16.0], [12.0, 16.0], [16.0, 16.0]]], 28.0), 'smallNORB': ([[[8.0, 8.0], [12.0, 8.0], [16.0, 8.0], [24.0, 8.0]], [[8.0, 12.0], [12.0, 12.0], [16...
def main(): args = parse_args() if (os.path.splitext(args.source_model)[(- 1)] != '.pth'): raise ValueError('You should save weights as pth file') source_weights = torch.load(args.source_model, map_location=torch.device('cpu'))['model'] converted_weights = {} keys = list(source_weights.keys(...
class KnownValues(unittest.TestCase): def test_KGKS(self): mf = dft.KGKS(cell, kpts) mf.xc = 'lda' mf.conv_tol = 1e-10 e_kgks = mf.kernel() self.assertAlmostEqual(e_kgks, (- 10.), 8) def test_veff(self): mf = dft.KGKS(cell, kpts) n2c = (cell.nao * 2) ...
class PSPFinalBlock(nn.Module): def __init__(self, in_channels, out_channels, bottleneck_factor=4): super(PSPFinalBlock, self).__init__() assert ((in_channels % bottleneck_factor) == 0) mid_channels = (in_channels // bottleneck_factor) self.conv1 = conv3x3_block(in_channels=in_channe...
def analogy_seq_encoding_model(inputs, params, is_training, reuse): enc_cell_fn = NAME_TO_RNNCELL[params.enc_model] recurrent_dropout_prob = 1.0 if is_training: recurrent_dropout_prob = params.recurrent_dropout_prob rnn_cell = get_rnn_cell(enc_cell_fn, params.enc_rnn_size, use_dropout=(is_traini...
.django_project(extra_settings='\n ROOT_URLCONF = "empty"\n ') def test_urls_cache_is_cleared(django_pytester: DjangoPytester) -> None: django_pytester.makepyfile(empty='\n urlpatterns = []\n ', myurls="\n from django.urls import path\n\n def fake_view(request):\n pass\n...
def save_state(filename, args, model_state_dict, criterion, optimizer, lr_scheduler, num_updates, optim_history=None, extra_state=None): from fairseq import utils if (optim_history is None): optim_history = [] if (extra_state is None): extra_state = {} state_dict = {'args': args, 'model'...
.parametrize('reporttype', reporttypes, ids=[x.__name__ for x in reporttypes]) def test_report_extra_parameters(reporttype: Type[reports.BaseReport]) -> None: args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:] basekw: Dict[(str, List[object])] = dict.fromkeys(args, []) report = report...
class Testfocalloss(object): def _test_softmax(self, dtype=torch.float): if (not torch.cuda.is_available()): return from mmcv.ops import softmax_focal_loss alpha = 0.25 gamma = 2.0 for (case, output) in zip(inputs, softmax_outputs): np_x = np.array(cas...
def test_no_cli_opts(default_file): cli_opts = parse() assert ('save_files' not in cli_opts) opts = api.bootstrap_options(cli_opts) assert (opts['config_files'] == []) default_file.write_text('[pyscaffold]\n') opts = api.bootstrap_options(cli_opts) assert (opts['config_files'] == [default_fi...
def codegen_kernel(kernel, device='cpu'): adj = kernel.adj forward_args = ['launch_bounds_t dim'] reverse_args = ['launch_bounds_t dim'] for arg in adj.args: forward_args.append(((arg.ctype() + ' var_') + arg.label)) reverse_args.append(((arg.ctype() + ' var_') + arg.label)) for arg ...
def run_experiment(num_nodes, failure_prob, max_iterations, averaging_algo, num_restarts, target_precision=None): experiment_result = partial(run_iterative_averaging, num_nodes=num_nodes, failure_prob=failure_prob, max_iterations=max_iterations, averaging_algo=averaging_algo, target_precision=target_precision) ...
class Tdecode_value(TestCase): def test_main(self): self.assertEqual(decode_value('~#foo', 0.25), '0.25') self.assertEqual(decode_value('~#foo', 4), '4') self.assertEqual(decode_value('~#foo', 'bar'), 'bar') self.assertTrue(isinstance(decode_value('~#foo', 'bar'), str)) path ...
def calculate_sentence_transformer_embedding(examples, embedding_model, mean_normal=False): if args.add_prompt: text_to_encode = [['Represent the Wikipedia sentence; Input: ', f'''{raw_item['sentence']} {raw_item['question']}''', 0] for raw_item in examples] else: text_to_encode = [f'''{raw_item...
class ConfirmationQuestion(Question): def __init__(self, question: str, default: bool=True, true_answer_regex: str='(?i)^y') -> None: super().__init__(question, default) self._true_answer_regex = true_answer_regex self._normalizer = self._default_normalizer def _write_prompt(self, io: IO...
def walk(x, path=()): (yield (path, x)) if isinstance(x, Object): for (name, val) in x.inamevals(): if isinstance(val, (list, tuple)): for (iele, ele) in enumerate(val): for y in walk(ele, path=(path + ((name, iele),))): (yield y) ...
class ActivityTest(unittest.TestCase): def setUp(self): self.ddbb = DDBB() main = Mock() main.ddbb = self.ddbb main.profile = Profile() main.ddbb.connect() main.ddbb.create_tables(add_default=True) self.uc = UC() self.uc.set_us(False) self.serv...
class RERB(nn.Module): def __init__(self, in_channels, num_channels, kernel_size, reduction, n_blocks, block): super(RERB, self).__init__() blocks = [] blocks.append(self._make_blocks(in_channels, num_channels, kernel_size, reduction, n_blocks, block)) blocks.append(ops.EoctConv(num_...
def captured_output() -> Generator[(Tuple[(TextIO, TextIO)], None, None)]: (new_out, new_err) = (StringIO(), StringIO()) (old_out, old_err) = (sys.stdout, sys.stderr) try: (sys.stdout, sys.stderr) = (new_out, new_err) (yield (sys.stdout, sys.stderr)) finally: (sys.stdout, sys.std...
def apply_pose(pose, x): if (x is None): return x if isinstance(pose, np.ndarray): pose = Pose.from_transformation_matrix(pose) assert isinstance(pose, Pose) if isinstance(x, Pose): return (pose * x) elif isinstance(x, np.ndarray): return to_nc((to_gc(x, dim=3) pose....
def test_invalid_default(): root = _create_test_config() def validate(val): if (val == 'invalid'): raise ValueError('Test-triggered') with pytest.raises(ValueError, match='Test-triggered'): root.add('test__test_invalid_default_a', doc='unittest', configparam=ConfigParam('invalid'...
def main(): best_acc = 0 for epoch in range(args.epochs): adjust_learning_rate(optimizer_model, epoch) train(train_loader, train_meta_loader, model, vnet, optimizer_model, optimizer_vnet, epoch) test_acc = test(model=model, test_loader=test_loader) if (test_acc >= best_acc): ...
class ClassInfoClass(object): structcode = None def parse_binary(self, data, display): (class_type, length) = struct.unpack('=HH', data[:4]) class_struct = INFO_CLASSES.get(class_type, AnyInfo) (class_data, _) = class_struct.parse_binary(data, display) data = data[(length * 4):] ...
_REGISTRY.register() class StyleGAN2Model(BaseModel): def __init__(self, opt): super(StyleGAN2Model, self).__init__(opt) self.net_g = build_network(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(...
def get_vlnbert_models(args, config=None): from transformers import PretrainedConfig from models.vilmodel import GlocalTextPathNavCMT model_name_or_path = args.bert_ckpt_file new_ckpt_weights = {} if (model_name_or_path is not None): ckpt_weights = torch.load(model_name_or_path, mal_location...
def log_likelihood(probability, indices, gold_indices, gold_labels): gold_indice_labels = [] for (batch_idx, label) in enumerate(gold_indices): for (i, l) in enumerate(label): if (l in indices[batch_idx]): idx = indices[batch_idx].index(l) gold_indice_labels.a...
def do_an_insert(wait_for_api): (request_session, api_url) = wait_for_api item_url = 'items/1' data_string = 'some_data' request_session.put(('%s%s?data_string=%s' % (api_url, item_url, data_string))) (yield (item_url, data_string)) request_session.delete(urljoin(api_url, item_url)).json()
class VectorBC(nn.Module): def __init__(self, num_vector_tokens=64, num_action_queries=6, num_blocks=18): super().__init__() encoder_config = VectorEncoderConfig() self.num_vector_tokens = num_vector_tokens self.vector_encoder = VectorEncoder(encoder_config, VectorObservationConfig()...
def test_add_with_path_dependency_no_loopiness(poetry_with_path_dependency: Poetry, repo: TestRepository, command_tester_factory: CommandTesterFactory) -> None: ' tester = command_tester_factory('add', poetry=poetry_with_path_dependency) requests_old = get_package('requests', '2.25.1') requests_new = ge...
def send_invoice_email(email, contents): msg = Message('Quay payment received - Thank you!', recipients=[email]) msg.html = contents if features.FIPS: assert app.config['MAIL_USE_TLS'], 'MAIL_USE_TLS must be enabled to use SMTP in FIPS mode.' with mock.patch('smtplib.SMTP.login', login_fips_...
class ModbusDeviceIdentification(): __data = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: ''} __names = ['VendorName', 'ProductCode', 'MajorMinorRevision', 'VendorUrl', 'ProductName', 'ModelName', 'UserApplicationName'] def __init__(self, info=None, info_name=None): if isinstance(info...
def test_rapt_corner_case(): def __test(x, fs, hopsize, min, max, otype): f0 = pysptk.rapt(x, fs, hopsize, min=min, max=max, otype=otype) assert np.all(np.isfinite(f0)) if (otype == 1): assert np.all((f0 >= 0)) np.random.seed(98765) fs = 16000 x = np.random.rand(16000...
def search_pypath(module_name: str) -> str: try: spec = importlib.util.find_spec(module_name) except (AttributeError, ImportError, ValueError): return module_name if ((spec is None) or (spec.origin is None) or (spec.origin == 'namespace')): return module_name elif spec.submodule_...
def source_radian_profile(path): if path: path = os.path.expanduser(path) if os.path.exists(path): source_file(path) else: if ('XDG_CONFIG_HOME' in os.environ): xdg_profile = make_path(os.environ['XDG_CONFIG_HOME'], 'radian', 'profile') elif (not sys.platf...
.parametrize('data, expdata', [([100, 0, 0, 0], [100, 0, 0]), ([100, 10, 10, 0], [110, 10, 0]), ([100, 10, 10, (np.pi / 2)], [10, 110, (np.pi / 2)])]) def test_manual_geometry(data, expdata): planview = pyodrx.PlanView() planview.add_fixed_geometry(pyodrx.Line(data[0]), data[1], data[2], data[3]) (x, y, h) ...
class PlayPluginMessageClientBound(Packet): id = 23 to = 1 def __init__(self, channel: str, data: bytes) -> None: super().__init__() self.channel = channel self.data = data def encode(self) -> bytes: return (Buffer.pack_string(self.channel) + self.data)
class WriteDir(Dir, locations.WriteLocation): def setup(self, src_repo, owners_map=None): ret_code = super().setup() if (ret_code & Globals.RET_CODE_ERR): return ret_code if (self.base_dir.conn is Globals.local_connection): from rdiffbackup.locations import _dir_shado...
class CLAVRXNetCDFFileHandler(_CLAVRxHelper, BaseFileHandler): def __init__(self, filename, filename_info, filetype_info): super(CLAVRXNetCDFFileHandler, self).__init__(filename, filename_info, filetype_info) self.nc = xr.open_dataset(filename, decode_cf=True, mask_and_scale=False, decode_coords=Tru...
def test_features_only(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), result.output project_path ...
class Inference(torch.nn.Module, metaclass=abc.ABCMeta): subclasses = {} def register_subclass(cls, inference_type): def decorator(subclass): cls.subclasses[inference_type] = subclass return subclass return decorator def create(cls, inference_type, **kwargs): ...
class LayerNormLSTMCellBackend(nn.LSTMCell): def __init__(self, input_dim, hidden_dim, bias=True, epsilon=1e-05): super(LayerNormLSTMCellBackend, self).__init__(input_dim, hidden_dim, bias) self.epsilon = epsilon def _layerNormalization(self, x): mean = x.mean(1, keepdim=True).expand_as(...
def read_conll(file_in, tokenizer, max_seq_length=512): (words, labels) = ([], []) examples = [] is_title = False with open(file_in, 'r') as fh: for line in fh: line = line.strip() if line.startswith('-DOCSTART-'): is_title = True continue ...
class Node(): path: str method: str = GET params: dict = field(default_factory=dict) source: Optional[str] = None requested: bool = False status_code: Optional[int] = None ignore_form_fields: set = field(default_factory=set) def __post_init__(self): self.method = self.method.uppe...
def test_imatmul_ilshift(): class A(): x: Bits16 B = mk_bitstruct('B', {'x': Bits100, 'y': ([A] * 3), 'z': A}) b = B(, [A(2), A(3), A(4)], A(5)) b = Bits164() assert (b.to_bits() == Bits164()) c = B(, [A(2), A(3), A(4)], A(5)) c <<= Bits164() assert (c == B(, [A(2), A(3), A(4)], ...
class HeuTopoUnrollSim(BasePass): def __init__(s, *, waveform=None, print_line_trace=True, reset_active_high=True): s.waveform = waveform s.print_line_trace = print_line_trace s.reset_active_high = reset_active_high def __call__(s, top): top.elaborate() GenDAGPass()(top) ...
class CaseVLibsTranslation(): class DUT(VerilogPlaceholder, Component): def construct(s): s.d = InPort(Bits32) s.q = OutPort(Bits32) s.set_metadata(VerilogPlaceholderPass.src_file, (dirname(__file__) + '/VRegPassThrough.v')) s.set_metadata(VerilogPlaceholderPa...
def test_env_info_displays_complete_info(tester: CommandTester) -> None: tester.execute() expected = f''' Virtualenv Python: 3.7.0 Implementation: CPython Path: {Path('/prefix')} Executable: {sys.executable} Valid: True Base Platform: darwin OS: posix Python: {'.'.jo...
def test_step_unit(): step_unit = StepUnit() step_unit.elaborate() step_unit.apply(DefaultPassGroup()) step_unit.word_in = 1 step_unit.sum1_in = 1 step_unit.sum2_in = 1 step_unit.sim_eval_combinational() assert (step_unit.sum1_out == 2) assert (step_unit.sum2_out == 3) step_unit....
def handle_code(code, title): run_js(CLIPBOARD_SETUP) session_local.globals = dict(globals()) if title: put_markdown(('## %s' % title)) for p in gen_snippets(code): with use_scope() as scope: put_code(p, 'python') put_buttons([t('Run', ''), t('Edit', ''), t('Copy ...
def ffmpeg_microphone_live(sampling_rate: int, chunk_length_s: float, stream_chunk_s: Optional[int]=None, stride_length_s: Optional[Union[(Tuple[(float, float)], float)]]=None, format_for_conversion: str='f32le'): if (stream_chunk_s is not None): chunk_s = stream_chunk_s else: chunk_s = chunk_le...
def test_dynlib_close(): class Comb(): class A(Component): def construct(s): s.in_ = InPort(Bits32) s.out = OutPort(Bits32) def upblk(): s.out = s.in_ class Seq(): class A(Component): def construct(s): ...
class Encoder(nn.Module): def __init__(self, make_mlp, latent_size): super().__init__() self._make_mlp = make_mlp self._latent_size = latent_size self.node_model = self._make_mlp(latent_size) self.mesh_edge_model = self._make_mlp(latent_size) self.world_edge_model = s...
class DeviceNameHypothesis(Hypothesis): def find_subsystems(cls, context): sys_path = context.sys_path dirnames = ('bus', 'class', 'subsystem') absnames = (os.path.join(sys_path, name) for name in dirnames) realnames = (d for d in absnames if os.path.isdir(d)) return frozense...
(bind=True, base=MlTask) def transform_ptt_post_to_spacy_post(self, post_id: str) -> Dict: post = self.sess.query(PttPost).filter((PttPost.id == post_id)).first() if (not post): raise PostNotExistsError(f'Post: {post_id} is not exist') logger.info('Transforming %s', post_id) spacy_post = transfo...
def download_file(url: str, dest: Path, session: ((Authenticator | Session) | None)=None, chunk_size: int=1024) -> None: from poetry.puzzle.provider import Indicator downloader = Downloader(url, dest, session) set_indicator = False with Indicator.context() as update_context: update_context(f'Dow...
class MultiScaleCornerCrop(object): def __init__(self, scales, size, interpolation=Image.BILINEAR, crop_positions=['c', 'tl', 'tr', 'bl', 'br']): self.scales = scales self.size = size self.interpolation = interpolation self.crop_positions = crop_positions def __call__(self, img):...
def test_catalogreference(): catref = OSC.CatalogReference('VehicleCatalog', 'S60') prettyprint(catref.get_element()) catref.add_parameter_assignment('stuffs', 1) prettyprint(catref.get_element()) catref2 = OSC.CatalogReference('VehicleCatalog', 'S60') catref2.add_parameter_assignment('stuffs', ...
def run_leiden_windows(graph, gamma, nruns, weight=None, node_subset=None, attribute=None, output_dictionary=False, niterations=5, calc_sim_mat=True): np.random.seed() g = graph if (node_subset != None): if (attribute == None): gdel = node_subset else: gdel = [i for (...
class BlockDecoder(object): def _decode_block_string(block_string): assert isinstance(block_string, str) ops = block_string.split('_') options = {} for op in ops: splits = re.split('(\\d.*)', op) if (len(splits) >= 2): (key, value) = splits[:2]...
def parse_parametrs(p): ret = {} while ((len(p) > 1) and (p.count('|') > 0)): s = p.split('|') l = int(s[0]) if (l > 0): p = p[(len(s[0]) + 1):] field_name = p.split('|')[0].split('=')[0] field_value = p[(len(field_name) + 1):l] p = p[(l + ...
def create_logger(save_path='', file_type='', level='debug'): if (level == 'debug'): _level = logging.DEBUG elif (level == 'info'): _level = logging.INFO logger = logging.getLogger() logger.setLevel(_level) cs = logging.StreamHandler() cs.setLevel(_level) logger.addHandler(cs...
def write_topic_model_log(opt, results): log_path = os.path.join(get_topic_root_folder(opt), 'eval_log.txt') if (not os.path.exists(log_path)): with open(log_path, 'a') as outfile: outfile.writelines('{}\t{}\t{}\t{}\n'.format('num_topics', 'topic_alpha', 'coherence', 'perplexity')) with ...
def test_user_avatar_history_multiple_requests(api, mock_req): mock_req({'getUserProfilePhotos': {'ok': True, 'result': {'total_count': 4, 'photos': [[{'file_id': 'aaaaaa', 'width': 50, 'height': 50, 'file_size': 128}], [{'file_id': 'bbbbbb', 'width': 50, 'height': 50, 'file_size': 128}]]}}}) user = botogram.ob...
def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): if (out is None): out = np.empty_like(data) for (row, label_row, out_row) in zip(data, group_labels, out): for label in np.unique(label_row): locs = (label_row == label) out_row[locs] = fun...
def instance_retrieval_test(args, cfg): assert torch.cuda.is_available(), 'CUDA not available, Exit!' train_dataset_name = cfg.IMG_RETRIEVAL.TRAIN_DATASET_NAME eval_dataset_name = cfg.IMG_RETRIEVAL.EVAL_DATASET_NAME spatial_levels = cfg.IMG_RETRIEVAL.SPATIAL_LEVELS resize_img = cfg.IMG_RETRIEVAL.RES...
class OsPathInjectionRegressionTest(TestCase): def setUp(self): self.filesystem = fake_filesystem.FakeFilesystem(path_separator='/') self.os_path = os.path self.os = fake_os.FakeOsModule(self.filesystem) def tearDown(self): os.path = self.os_path def test_create_top_level_dir...
((MANIFEST_DIGEST_ROUTE + '/labels/<labelid>')) _param('repository', 'The full path of the repository. e.g. namespace/name') _param('manifestref', 'The digest of the manifest') _param('labelid', 'The ID of the label') class ManageRepositoryManifestLabel(RepositoryParamResource): _repo_read(allow_for_superuser=True)...
def set_deserializer(func: callable, cls: Union[(type, Sequence[type])], high_prio: bool=True, fork_inst: type=StateHolder) -> None: if isinstance(cls, Sequence): for cls_ in cls: set_deserializer(func, cls_, high_prio, fork_inst) elif cls: index = (0 if high_prio else len(fork_inst....
class FrozenBatchNorm2d(nn.Module): def __init__(self, num_features, eps=1e-05): super().__init__() self.eps = eps self.register_buffer('weight', torch.ones(num_features)) self.register_buffer('bias', torch.zeros(num_features)) self.register_buffer('running_mean', torch.zeros...
class MyApp(App): def __init__(self, *args): super(MyApp, self).__init__(*args) def main(self): wid = gui.VBox(width=300, height=200, margin='0px auto') self.lbl = gui.Label('Press the button', width='80%', height='50%') self.lbl.style['margin'] = 'auto' self.bt = gui.But...
def init(win_id: int, parent: QObject) -> 'ModeManager': commandrunner = runners.CommandRunner(win_id) modeman = ModeManager(win_id, parent) objreg.register('mode-manager', modeman, scope='window', window=win_id) hintmanager = hints.HintManager(win_id, parent=parent) objreg.register('hintmanager', h...
class Optimizer(object): _ARG_MAX_GRAD_NORM = 'max_grad_norm' def __init__(self, optim, max_grad_norm=0): self.optimizer = optim self.scheduler = None self.max_grad_norm = max_grad_norm def set_scheduler(self, scheduler): self.scheduler = scheduler def step(self): ...
class AddressBox(Form): def __init__(self, view, address): form_name = ('address_%s' % address.id) super().__init__(view, form_name) par = self.add_child(P(view, text=('%s: %s ' % (address.name, address.email_address)))) par.add_child(Button(self, address.events.edit.with_arguments(a...
class Network(nn.Module): def __init__(self, C, num_classes, layers, criterion, steps=4, multiplier=4, stem_multiplier=3): super(Network, self).__init__() self._C = C self._num_classes = num_classes self._layers = layers self._criterion = criterion self._steps = steps...
class YAKE(LoadFile): def __init__(self): super(YAKE, self).__init__() self.words = defaultdict(set) self.contexts = defaultdict((lambda : ([], []))) self.features = defaultdict(dict) self.surface_to_lexical = {} def candidate_selection(self, n=3, stoplist=None, **kwargs)...
def get_shortest_unique_filename(filename, filenames): filename1 = filename.replace('\\', '/') filenames = [fn.replace('\\', '/') for fn in filenames] filenames = [fn for fn in filenames if (fn != filename1)] nameparts1 = filename1.split('/') uniqueness = [len(filenames) for i in nameparts1] for...
class ChannelAttention(nn.Module): def __init__(self, in_planes, ratio=16): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.max_pool = nn.AdaptiveMaxPool2d(1) self.sharedMLP = nn.Sequential(nn.Conv2d(in_planes, (in_planes // ratio), 1, bias=False), nn.ReLU(), nn.Conv2...
class EncapsulateFieldTest(unittest.TestCase): def setUp(self): super().setUp() self.project = testutils.sample_project() self.pycore = self.project.pycore self.mod = testutils.create_module(self.project, 'mod') self.mod1 = testutils.create_module(self.project, 'mod1') ...
def export_pinnacle(pinnacle_subparsers): parser = pinnacle_subparsers.add_parser('export', help='Export a raw file to DICOM') parser.add_argument('input_path', type=str, help="Root Patient directory of raw Pinnacle data (directory containing the 'Patient' file). Alternatively a TAR archive can be supplied.") ...
(scope='session') def lombscargle_gen(rand_data_gen): def _generate(num_in_samps, num_out_samps): A = 2.0 w = 1.0 phi = (0.5 * np.pi) frac_points = 0.9 (r, _) = rand_data_gen(num_in_samps, 1) cpu_x = np.linspace(0.01, (10 * np.pi), num_in_samps) cpu_x = cpu_x[...
class OpQuery(): def __init__(self, graph, op_map=None, ops_to_ignore=None, strict=True): self._log = AimetLogger.get_area_logger(AimetLogger.LogAreas.Utils) self._graph = graph self._strict = strict if op_map: self._op_map = op_map else: self._op_map ...
def job_met_opt10(sample_source, tr, te, r, J): met_opt_options = {'n_test_locs': J, 'max_iter': 50, 'locs_step_size': 10.0, 'gwidth_step_size': 0.2, 'seed': (r + 92856), 'tol_fun': 0.001} (test_locs, gwidth, info) = tst.MeanEmbeddingTest.optimize_locs_width(tr, alpha, **met_opt_options) met_opt = tst.MeanE...
_constructor.register(scipy.sparse.spmatrix) def sparse_constructor(value, name=None, strict=False, allow_downcast=None, borrow=False, format=None): if (format is None): format = value.format type = SparseTensorType(format=format, dtype=value.dtype) if (not borrow): value = copy.deepcopy(val...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, number_net=4, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d ...
class GAT(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads): super(GAT, self).__init__() self.dropout = dropout self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)] for (i, attention) in enume...
def test_stochasticoptimization(): last_time_replaced = [False] _rewriter([add]) def insert_broken_add_sometimes(fgraph, node): if (node.op == add): last_time_replaced[0] = (not last_time_replaced[0]) if last_time_replaced[0]: return [off_by_half(*node.inputs)...
class CreationTests(AuthenticatedAPITestCase): def setUpTestData(cls): cls.user = User.objects.create(id=1234, name='joe dart', discriminator=1111) cls.user2 = User.objects.create(id=9876, name='Who?', discriminator=1234) def test_accepts_valid_data(self): url = reverse('api:bot:nominati...
def bitstring_to_alphanumeric(s): text = '' while (len(s) >= 11): part = s[:11] s = s[11:] num = int(part, 2) c1 = min(44, (num // 45)) c2 = (num % 45) text += (find_table_char(c1) + find_table_char(c2)) if (len(s) >= 6): num = min(44, int(s[:6], 2)) ...
class Fastformer(Layer): def __init__(self, nb_head, size_per_head, **kwargs): self.nb_head = nb_head self.size_per_head = size_per_head self.output_dim = (nb_head * size_per_head) self.now_input_shape = None super(Fastformer, self).__init__(**kwargs) def build(self, inpu...
def test_accuracy(logits, labels): logits_idx = tf.to_int32(tf.argmax(logits, axis=1)) logits_idx = tf.reshape(logits_idx, shape=(cfg.batch_size,)) correct_preds = tf.equal(tf.to_int32(labels), logits_idx) accuracy = (tf.reduce_sum(tf.cast(correct_preds, tf.float32)) / cfg.batch_size) return accurac...
class TestsSemiBayes(): def test_compare_to_modernepi3(self): posterior_rr = math.exp(((math.log(3.51) / 0.569) / ((1 / 0.5) + (1 / 0.569)))) posterior_ci = (math.exp((0.587 - (1.96 * (0.266 ** 0.5)))), math.exp((0.587 + (1.96 * (0.266 ** 0.5))))) sb = semibayes(prior_mean=1, prior_lcl=0.25,...
.functions def test_not_case_sensitive_but_nonstring(): df = pd.DataFrame({'ok1': ['ABC', None, 'zzz'], 'ok2': pd.Categorical(['A', 'b', 'A'], ordered=False), 'notok1': [1, 2, 3], 'notok2': [b'ABC', None, b'zzz']}) for okcol in ['ok1', 'ok2']: _ = df.count_cumulative_unique(okcol, dest_column_name='ok_c...
def _get_command_line_arguments() -> Dict: parser = argparse.ArgumentParser() parser.add_argument(('--' + Args.INPUT_DIRS), help='One or more input directories containing features', nargs='+', required=True, type=str) parser.add_argument(('--' + Args.INPUT_FEATURE_NAMES), help='One or more feature file name...
def read_class_weights(class_weights_path: Path, label_map: LabelMap) -> np.ndarray: if (not class_weights_path.exists()): return np.ones(label_map.num_classes()) num_classes = label_map.num_classes() class_weights = np.empty(num_classes) class_weights[:] = np.nan with class_weights_path.ope...
class HyperYan(DynSys): def _rhs(x, y, z, w, t, a=37, b=3, c=26, d=38): xdot = ((a * y) - (a * x)) ydot = ((((c - a) * x) - (x * z)) + (c * y)) zdot = ((((((- b) * z) + (x * y)) - (y * z)) + (x * z)) - w) wdot = ((((- d) * w) + (y * z)) - (x * z)) return (xdot, ydot, zdot, wd...