code
stringlengths
281
23.7M
def send_subscription_change(change_description, customer_id, customer_email, quay_username): SUBSCRIPTION_CHANGE_TITLE = 'Subscription Change - {0} {1}' SUBSCRIPTION_CHANGE = '\n Change: {0}<br>\n Customer id: <a href=" Customer email: <a href="mailto:{2}">{2}</a><br>\n Quay user or org name: {3}<br>\n ' ...
def create_video_from_containers(in_container: InputContainer, out_container: OutputContainer, draw_on_av_frame: DrawOnAvFrame, add_border: bool) -> None: in_video_stream = in_container.streams.video[0] in_video_stream.thread_type = 'AUTO' transformation_sizes = _compute_transformation_sizes(in_video_stream...
class FSMTTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = FSMTTokenizer test_rust_tokenizer = False def setUp(self): super().setUp() vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w...
def test_service_registry_random_pfs(service_registry_address, private_keys, web3, contract_manager): addresses = [privatekey_to_address(key) for key in private_keys] (c1_service_proxy, urls) = deploy_service_registry_and_set_urls(private_keys=private_keys, web3=web3, contract_manager=contract_manager, service_...
def get_triplet_mask(labels: torch.Tensor) -> torch.Tensor: indices_equal = torch.eye(labels.size()[0], dtype=torch.bool, device=labels.device) indices_not_equal = torch.logical_not(indices_equal) i_not_equal_j = indices_not_equal.unsqueeze(2) i_not_equal_k = indices_not_equal.unsqueeze(1) j_not_equ...
class ChannelSpatialSELayer3D(nn.Module): def __init__(self, num_channels, reduction_ratio=2): super(ChannelSpatialSELayer3D, self).__init__() self.cSE = ChannelSELayer3D(num_channels, reduction_ratio) self.sSE = SpatialSELayer3D(num_channels) def forward(self, input_tensor): out...
class Material(): def __init__(self, normalmap=None): if (normalmap != None): normalmap = load_image(('sightpy/normalmaps/' + normalmap)) self.normalmap = normalmap def get_Normal(self, hit): N_coll = hit.collider.get_Normal(hit) if (self.normalmap is not None): ...
class SolveModel(): solver: pybamm.BaseSolver model: pybamm.BaseModel t_eval: np.ndarray def solve_setup(self, parameter, model_, option, value, solver_class): import importlib idaklu_spec = importlib.util.find_spec('pybamm.solvers.idaklu') if (idaklu_spec is not None): ...
def scale_jitter(tensor, target, jitter_factor, jitter_size=None, mask=None): if (jitter_size is None): (_, h, w) = tensor.shape (new_h, new_w) = (int((h * jitter_factor)), int((w * jitter_factor))) jitter_factor_x = jitter_factor_y = jitter_factor else: (new_h, new_w) = jitter_s...
class ReleaseFile(ContentManageable, NameSlugModel): os = models.ForeignKey(OS, related_name='releases', verbose_name='OS', on_delete=models.CASCADE) release = models.ForeignKey(Release, related_name='files', on_delete=models.CASCADE) description = models.TextField(blank=True) is_source = models.Boolean...
class AM2RBasePatchesFactory(BasePatchesFactory): def create_base_patches(self, configuration: BaseConfiguration, rng: Random, game: GameDescription, is_multiworld: bool, player_index: int, rng_required: bool=True) -> GamePatches: assert isinstance(configuration, AM2RConfiguration) parent = super()....
class Effect7233(BaseEffect): type = 'passive' def handler(fit, implant, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Precursor Weapon')), 'damageMultiplierBonusPerCycle', implant.getModifiedItemAttr('damageMultiplierBonusPerCycleModifier'), **...
def main(): dicts = {} tokenizer = onmt.Tokenizer(opt.input_type, opt.lower) if ((opt.load_dict is not None) and (len(opt.load_dict) > 0)): print(('[INFO] Loading dictionary from ... %s' % opt.load_dict)) dicts = torch.load(opt.load_dict) src_langs = opt.train_src_lang.split('|') tgt...
class Effect5778(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Missile Launcher Operation')), 'speed', ship.getModifiedItemAttr('shipBonusMF2'), skill='Minmatar Frigate', **kwargs)
class TestTfWinnower(unittest.TestCase): .tf1 def test_mask_propagation_on_keras_model(self): tf.compat.v1.reset_default_graph() sess = tf.compat.v1.Session() module_zero_channels_list = [] _ = keras_model() init = tf.compat.v1.global_variables_initializer() sess....
class BaselineYNet(nn.Module): def __init__(self, input_size=(3, 32, 32), num_classes=10, activation='softplus', residual=False, hidden_width=128, aug=0): super(BaselineYNet, self).__init__() (y_net, output_size) = make_y_net(input_size=input_size, explicit_params=False, activation=activation, hidde...
class MissingDependencies(RuntimeError): def __init__(self, missing_dependencies, *args, **kwargs): super().__init__(*args, **kwargs) self.missing_dependencies = missing_dependencies def __str__(self): prefix = super().__str__() unknown_str = ', '.join(map(str, self.missing_depen...
def test_search(requests_mock): requests_mock.get(f'{API_V1}/search', json=load_sample_data('get_search.json'), status_code=200) response = search([8348, 6432]) taxon_result = response['results'][0] place_result = response['results'][1] project_result = response['results'][2] user_result = respo...
class CurrentUserGPGKeyManager(RetrieveMixin, CreateMixin, DeleteMixin, RESTManager): _path = '/user/gpg_keys' _obj_cls = CurrentUserGPGKey _create_attrs = RequiredOptional(required=('key',)) def get(self, id: Union[(str, int)], lazy: bool=False, **kwargs: Any) -> CurrentUserGPGKey: return cast(...
class BTOOLS_OT_material_group_assign(bpy.types.Operator): bl_idname = 'btools.material_group_assign' bl_label = 'Assign Faces to Group' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): obj = context.object matgroup = obj.bt_materials[obj.bt_materials_active_index] retur...
def test_solver_does_not_return_prereleases_if_not_requested(solver: Solver, repo: Repository, package: ProjectPackage) -> None: package.add_dependency(Factory.create_dependency('A', '*')) package.add_dependency(Factory.create_dependency('B', '*')) package.add_dependency(Factory.create_dependency('C', '*'))...
def mc_elbo(z0, t0, t1, prior_params, post_params, log_likelihood_params, prior_drift, diffusion, posterior_drift, log_likelihood, rng): (aug_drift, aug_diffusion) = make_aug_dynamics(prior_drift, diffusion, posterior_drift) aug_init = pack(z0, 0.0) out = sdeint_ito(aug_drift, aug_diffusion, aug_init, np.ar...
def save_churns(churns, path='./results/code_churns_features_multithread.csv'): with open(path, 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(['commit', 'lines_of_code_added', 'lines_of_code_deleted', 'files_churned', 'line_of_code_old']) for row in churns: if r...
class _FindExecutor(ActionExecutor): def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False): current_line = script[0] info.set_current_line(current_line) current_obj = current_line.object() for node in state.select_nod...
def zero_scale_fix(model, device): for (k, m) in model.named_modules(): if (isinstance(m, quant_nn.QuantConv2d) or isinstance(m, quant_nn.QuantConvTranspose2d)): weight_amax = m._weight_quantizer._amax.detach().cpu().numpy() print(k) ones = np.ones_like(weight_amax) ...
def monotonically_increasing_and_bounded(iterable, min=None, max=None): if (not isinstance(iterable, Iterable)): raise TypeError('Expected iterable to be of type Iterable, got ({})'.format(iterable.__class__.__name__)) for i in range(len(iterable)): if ((min is not None) and (iterable[i] < min))...
class Gumbel(Continuous): rv_op = gumbel def dist(cls, mu, beta, **kwargs): mu = pt.as_tensor_variable(floatX(mu)) beta = pt.as_tensor_variable(floatX(beta)) return super().dist([mu, beta], **kwargs) def moment(rv, size, mu, beta): mean = (mu + (beta * np.euler_gamma)) ...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, is_last=False): super(BasicBlock, self).__init__() self.is_last = is_last self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu ...
class TextReporter(Reporter): def __init__(self, *, verbosity: int, stream: (t.TextIO | None)=None) -> None: super().__init__(verbosity=verbosity) self.stream = stream def _echo(self, s: str, *, indent: int=0) -> None: click.echo(((' ' * indent) + s), file=self.stream) def report_suc...
class Win32Window(BaseWindow): _window_class = None _hwnd = None _dc = None _wgl_context = None _tracking = False _hidden = False _has_focus = False _exclusive_keyboard = False _exclusive_keyboard_focus = True _exclusive_mouse = False _exclusive_mouse_focus = True _exclus...
class VGG(nn.Module): def __init__(self, builder, features): super(VGG, self).__init__() self.features = features num_classes = (10 if (parser_args.set == 'CIFAR10') else 100) self.linear = builder.conv1x1(512, num_classes) def forward(self, x): x = self.features(x) ...
class Bobby(Configurable): handler = Method() handler2 = Method() foo = Option(positional=True) bar = Option(required=False) def think(self, context): (yield 'different') def __call__(self, think, *args, **kwargs): self.handler('1', *args, **kwargs) self.handler2('2', *ar...
class MLPRegression(nn.Module): def __init__(self, input_dim=86): super(MLPRegression, self).__init__() self.fc1 = nn.Linear(input_dim, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 1) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.f...
.parametrize('fun', [ct.series, ct.parallel, ct.feedback]) .parametrize('ltype', bd_types) .parametrize('rtype', bd_types) def test_bdalg_type_conversions(fun, ltype, rtype, sys_dict): leftsys = sys_dict[ltype] rightsys = sys_dict[rtype] expected = bd_expect[bd_types.index(ltype)][1][bd_types.index(rtype)] ...
class TransformerSentenceEncoderLayer(nn.Module): def __init__(self, embedding_dim: float=768, ffn_embedding_dim: float=3072, num_attention_heads: float=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, activation_fn: str='relu', add_bias_kv: bool=False, add_zero_attn: bool=False, ...
def print_table(rows, headers, nicks, order): rows.insert(0, headers) rows = filter_table(rows, nicks, order) if (not rows): return widths = [] for c in range(len(rows[0])): widths.append(max((len(r[c]) for r in rows))) seperator = (' %s ' % Colorise.gray('|')) format_string ...
class TestCustomScripts(): def test_only_linter_fix(self, hatch, temp_dir, config_file, mocker): 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) a...
.parametrize('prefer_grpc', [False, True]) .parametrize('numpy_upload', [False, True]) .parametrize('local_mode', [False, True]) def test_qdrant_client_integration(prefer_grpc, numpy_upload, local_mode): vectors_path = create_random_vectors() if numpy_upload: vectors = np.memmap(vectors_path, dtype='flo...
class NonStructured_Encoder(): def __init__(self, sess, FLAGS, embed, num_units=None, scope='Sentence_Encoder'): self.sess = sess self.dim_embed_word = FLAGS.dim_embed_word self.num_units = (num_units if (num_units is not None) else FLAGS.num_units) self.num_layers = FLAGS.num_layers...
class DistWorker(CovController): _ensure_topdir def start(self): cleanup() self.is_collocated = ((socket.gethostname() == self.config.workerinput['cov_master_host']) and (self.topdir == self.config.workerinput['cov_master_topdir'])) if (not self.is_collocated): master_topdir ...
def freeze_bn(model): for module in model.modules(): if isinstance(module, torch.nn.BatchNorm2d): if hasattr(module, 'weight'): module.weight.requires_grad_(False) if hasattr(module, 'bias'): module.bias.requires_grad_(False) module.eval()
def rtn_ftell(se: 'SymbolicExecutor', pstate: 'ProcessState'): logger.debug('ftell hooked') arg0 = pstate.get_argument_value(0) if pstate.file_descriptor_exists(arg0): desc = pstate.get_file_descriptor(arg0) if desc.fd.seekable(): return desc.fd.tell() else: r...
def get_commandline(server=False, description=None, extras=None, cmdline=None): parser = argparse.ArgumentParser(description=description) parser.add_argument('-c', '--comm', choices=['tcp', 'udp', 'serial', 'tls'], help='set communication, default is tcp', dest='comm', default='tcp', type=str) parser.add_ar...
def multiplicative_jitter(x, device: torch.device, epsilon=0.01): if (epsilon == 0): return x minval = torch.tensor((1.0 - epsilon), device=device) maxval = torch.tensor((1.0 + epsilon), device=device) uniform = uniform_map.get(device) if (uniform is None): uniform = torch.distributi...
def test_pattern_should_be_used2(): def parse_yesno(text): return parse_yesno.mapping[text.lower()] parse_yesno.mapping = {'yes': True, 'no': False, 'on': True, 'off': False, 'true': True, 'false': False} parse_yesno.pattern = '|'.join(parse_yesno.mapping.keys()) parse_yesno.name = 'YesNo' e...
class ELF32_Phdr(ELF_Phdr): Phdr_SIZE = (4 * 8) def __init__(self, buf, endian=0): if (len(buf) != self.Phdr_SIZE): raise fmt = ('<IIIIIIII' if (endian == 0) else '>IIIIIIII') (p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags, p_align) = struct.unpack(fmt, buf) ...
class TestDateField(TestCase): def setUp(self): self.field = fields.DateField() def test_deserialize_none(self): actual_value = self.field.deserialize(None) expected_value = None self.assertEqual(actual_value, expected_value) def test_deserialize_naive(self): arbitrar...
class Client(Iface): def __init__(self, iprot, oprot=None): self._iprot = self._oprot = iprot if (oprot is not None): self._oprot = oprot self._seqid = 0 def example(self): self.send_example() return self.recv_example() def send_example(self): self...
class Playlist(BasePathMixin): def __init__(self, uri, stream_info, media, base_uri): self.uri = uri self.base_uri = base_uri resolution = stream_info.get('resolution') if (resolution != None): resolution = resolution.strip('"') values = resolution.split('x') ...
def main(OPTS): with open(OPTS.data_file) as f: dataset_json = json.load(f) dataset = dataset_json['data'] with open(OPTS.pred_file) as f: preds = json.load(f) if OPTS.na_prob_file: with open(OPTS.na_prob_file) as f: na_probs = json.load(f) else: na_pr...
def apply_ccx(circuit, a, b, c, use_basis_gates=True): if use_basis_gates: circuit.h(c) circuit.cx(b, c) circuit.tdg(c) circuit.cx(a, c) circuit.t(c) circuit.cx(b, c) circuit.tdg(c) circuit.cx(a, c) circuit.t(b) circuit.t(c) cir...
def resnet50_v1b(pretrained=False, local_rank=None, **kwargs): model = ResNetV1b(BottleneckV1b, [3, 4, 6, 3], **kwargs) if (pretrained != 'None'): if (local_rank is not None): old_dict = torch.load(pretrained, map_location=torch.device(local_rank)) else: old_dict = torch....
def _get_quicklook(area_def, data, vmin=None, vmax=None, label='Variable (units)', num_meridians=45, num_parallels=10, coast_res='110m', cmap='RdBu_r'): import matplotlib.pyplot as plt (coast_res, is_cartopy) = _translate_coast_resolution_to_cartopy(coast_res) if (not is_cartopy): return _basemap_ge...
class GradientDescent(OptimizationAlgorithm): def __init__(self, **kwargs): default_parameters = {'learning_rate': 1.0} restart_variables = {} super(self.__class__, self).__init__(alg_default_parameters=default_parameters, alg_restart_variables=restart_variables, **kwargs) def _step(self...
def news_articles(hostname: str, language: str) -> list[NewsArticle]: site = Site.objects.filter(hostname=hostname).first() if (not site): raise ValueError(f'Site {hostname} not found') return [NewsArticle.from_model(article) for article in NewsArticleModel.objects.in_site(site).order_by('-first_pub...
class STTHandler(): def __init__(self, settings, pip_path, stt): self.settings = settings self.pip_path = pip_path self.stt = stt self.key = '' def install(self): for module in self.stt['extra_requirements']: install_module(module, self.pip_path) def is_in...
.filterwarnings('default') def test_nose_deprecated_with_setup(pytester: Pytester) -> None: pytest.importorskip('nose') pytester.makepyfile('\n from nose.tools import with_setup\n\n def setup_fn_no_op():\n ...\n\n def teardown_fn_no_op():\n ...\n\n _setup(setup_...
def test_change_truncated_size(): x = Truncated.dist(icdf_normal(0, [1, 2, 3]), lower=(- 1), size=(2, 3)) (x.eval().shape == (2, 3)) new_x = change_dist_size(x, (4, 3)) assert isinstance(new_x.owner.op, TruncatedRV) (new_x.eval().shape == (4, 3)) new_x = change_dist_size(x, (4, 3), expand=True) ...
class DbmsXslprocessor(DirectoryManagement): def __init__(self, args): logging.debug('DbmsXslprocessor object created') DirectoryManagement.__init__(self, args) def putFile(self, remotePath, remoteNameFile, data=None, localFile=None): if (((localFile == None) and (data == None)) or ((loc...
def _even_ext(x, n, axis=(- 1)): x = cp.asarray(x) if (n < 1): return x if (n > (x.shape[axis] - 1)): raise ValueError((('The extension length n (%d) is too big. ' + 'It must not exceed x.shape[axis]-1, which is %d.') % (n, (x.shape[axis] - 1)))) left_ext = _axis_slice(x, start=n, stop=0...
('PyQt6.QtGui.QAction.triggered') ('beeref.actions.mixin.menu_structure') ('beeref.actions.mixin.actions') def test_update_recent_files(actions_mock, menu_mock, triggered_mock, qapp): widget = FooWidget() widget.settings.get_recent_files.return_value = [os.path.abspath('foo.bee')] menu_mock.__iter__.return_...
def main(): logging.basicConfig(level=logging.DEBUG, filename='/home/xapp-logger.log', filemode='a+', format='%(asctime)-15s %(levelname)-8s %(message)s') formatter = logging.Formatter('%(asctime)-15s %(levelname)-8s %(message)s') console = logging.StreamHandler() console.setLevel(logging.INFO) cons...
def dataset_walker(datasets): for dataset in datasets: (yield (dataset, None)) for anc_ds in dataset.attrs.get('ancillary_variables', []): try: anc_ds.attrs (yield (anc_ds, dataset)) except AttributeError: continue
def progress(items, desc='', total=None, min_delay=0.1, displaytype='s1k'): total = (total or len(items)) t_start = time.time() t_last = 0 for (n, item) in enumerate(items): t_now = time.time() if ((t_now - t_last) > min_delay): print(('\r%s%d/%d (%6.2f%%)' % (desc, (n + 1), ...
class Logger(): def print(str): if MPIUtil.is_root_proc(): print(str) return def __init__(self): self.output_file = None self.first_row = True self.log_headers = [] self.log_current_row = {} self._dump_str_template = '' return def r...
class WebDriverHandler(): def __init__(self, command_executor): self.command_executor = command_executor self.original_execute = command_executor.execute self.reahl_server = None def uninstall(self): self.command_executor.execute = self.original_execute def reinstall(self): ...
def get_doc_input_bert(news, news_index, category_dict, domain_dict, subcategory_dict, args): news_num = (len(news) + 1) if ('title' in args.news_attributes): news_title = np.zeros((news_num, args.num_words_title), dtype='int32') news_title_type = np.zeros((news_num, args.num_words_title), dtype...
class double_conv(nn.Module): def __init__(self, in_ch, out_ch): super(double_conv, self).__init__() self.conv = nn.Sequential(nn.Conv1d(in_ch, out_ch, 3, padding=1), nn.BatchNorm1d(out_ch), nn.ReLU(inplace=True), nn.Conv1d(out_ch, out_ch, 3, padding=1), nn.BatchNorm1d(out_ch), nn.ReLU(inplace=True)...
def _template_online_dataset(**kwargs): lqargs = [] for k in ['network', 'station', 'channel']: if (k in kwargs): v = kwargs.pop(k) lqargs.append((" %s: '%s'" % (k, v))) kwargs['qargs'] = (('\n' + '\n'.join(lqargs)) if lqargs else '{}') return '\n--- !squirrel.Dataset\...
class Effect6928(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.requiresSkill('Afterburner') or mod.item.requiresSkill('High Speed Maneuvering'))), 'overloadSpeedFactorBonus', src.getModifiedItemAttr('subsyste...
def repeat_tensors(n, x): if torch.is_tensor(x): x = x.unsqueeze(1) x = x.expand((- 1), n, *([(- 1)] * len(x.shape[2:]))) x = x.reshape((x.shape[0] * n), *x.shape[2:]) elif ((type(x) is list) or (type(x) is tuple)): x = [repeat_tensors(n, _) for _ in x] return x
def calc_tf_padding(x, kernel_size, stride=1, dilation=1): (height, width) = x.size()[2:] oh = math.ceil((height / stride)) ow = math.ceil((width / stride)) pad_h = max((((((oh - 1) * stride) + ((kernel_size - 1) * dilation)) + 1) - height), 0) pad_w = max((((((ow - 1) * stride) + ((kernel_size - 1)...
class Inferer(): def __init__(self, config): self.config = config if torch.cuda.is_available(): self.device = torch.device('cuda') else: self.device = torch.device('cpu') torch.set_num_threads(1) self.model_preproc = registry.instantiate(registry.l...
class TargetAssigner(object): def __init__(self, similarity_calc: IouSimilarity, matcher: ArgMaxMatcher, box_coder: FasterRcnnBoxCoder, negative_class_weight: float=1.0, unmatched_cls_target: Optional[float]=None, keypoints_field_name: str=KEYPOINTS_FIELD_NAME): self._similarity_calc = similarity_calc ...
def _choose_chains(traces: Sequence[S], tune: int) -> Tuple[(List[S], int)]: if (not traces): raise ValueError('No traces to slice.') lengths = [max(0, (len(trace) - tune)) for trace in traces] if (not sum(lengths)): raise ValueError('Not enough samples to build a trace.') idxs = np.args...
def retry(exception_cls, max_tries=10, sleep=0.05): assert (max_tries > 0) def with_max_retries_call(delegate): for i in range(max_tries): try: return delegate() except exception_cls: if ((i + 1) == max_tries): raise ...
class BaseClean(): clean_fns = ['to_lower', 'to_symbol', 'remove_emoji', 'clean_contractions', 'common_us_word', 'query_clean_v1', 'remove_control_char', 'remove_duplicate', 'remove_ending_underscore', 'remove_starting_underscore', 'clean_multiple_form', 'leet_clean'] def __init__(self, clean_fns=None): ...
def main(): (train_annot, val_annot) = (pickle.load(open('clean_train.pkl', 'rb')), pickle.load(open('clean_valid.pkl', 'rb'))) data_path = 'data_hmor' os.makedirs(data_path, exist_ok=True) for (annot_name, annot) in zip(('train', 'valid'), (train_annot, val_annot)): for term in tqdm(annot): ...
class TranslationTestMixin(object): def setUp(self): super(TranslationTestMixin, self).setUp() self.backend = self.create_backend(data={'name': 'mockbackend'}) def create_lang_connection(self, identity, language): contact = self.create_contact(data={'language': language}) connect...
class FeedForward(nn.Module): def __init__(self, dim_in, hidden_dim, dim_out=None, *, dropout=0.0, f=nn.Linear, activation=nn.GELU): super().__init__() dim_out = (dim_in if (dim_out is None) else dim_out) self.net = nn.Sequential(f(dim_in, hidden_dim), activation(), (nn.Dropout(dropout) if (...
def update_diffs(module, is_similar, img, stored_img): diffs_dir.mkdir(exist_ok=True) diffs_rgba = None def get_diffs_rgba(slicer): nonlocal diffs_rgba if (diffs_rgba is None): diffs_rgba = np.abs((stored_img.astype('f4') - img)) diffs_rgba = (((diffs_rgba / 255) ** 0...
class Tuple(Type): def __init__(self, *elem_types): self.elem_types = elem_types def __eq__(self, other): return ((self.__class__ == other.__class__) and (self.elem_types == other.elem_types)) def from_str(self, s): if (';' in s): segments = s.split(';') elif (','...
class BertFeatExtractor(object): def __init__(self, model_name): self.tokenizer = BertTokenizer.from_pretrained(model_name) self.model = BertModel.from_pretrained(model_name).eval() self.model.cuda() def get_bert_embedding(self, text): tokenized_text = self.tokenizer.tokenize(tex...
def gmetric_read(msg): unpacker = Unpacker(msg) values = dict() unpacker.unpack_int() values['TYPE'] = unpacker.unpack_string() values['NAME'] = unpacker.unpack_string() values['VAL'] = unpacker.unpack_string() values['UNITS'] = unpacker.unpack_string() values['SLOPE'] = slope_int2str[un...
def geometry_window(dataset, shapes, pad_x=0, pad_y=0, north_up=None, rotated=None, pixel_precision=None, boundless=False): all_bounds = [bounds(shape, transform=(~ dataset.transform)) for shape in shapes] cols = [x for (left, bottom, right, top) in all_bounds for x in ((left - pad_x), (right + pad_x), (right +...
def train_one_epoch(train_loader, model, criterion, optimizer, scheduler, epoch, logger, config, scaler=None): model.train() loss_list = [] for (iter, data) in enumerate(train_loader): optimizer.zero_grad() (images, targets) = data (images, targets) = (images.cuda(non_blocking=True)....
def get_user_emails(list_id): users = [] response = req(get_url(f'sub/lists/{list_id}/subscribers/')) users.extend([x for x in response.json()['results'] if (x['is_active'] and x['is_email_verified'])]) while (response.json()['next'] is not None): response = req(response.json()['next']) ...
class Effect2882(BaseEffect): type = 'passive' def handler(fit, container, context, projectionRange, **kwargs): fit.modules.filteredChargeBoost((lambda mod: mod.charge.requiresSkill('Cruise Missiles')), 'explosiveDamage', container.getModifiedItemAttr('damageMultiplierBonus'), **kwargs)
def eval_callback(model: torch.nn.Module, num_samples: Optional[int]=None) -> float: if (num_samples is None): num_samples = EVAL_DATASET_SIZE data_loader = _create_sampled_data_loader(imagenet_dataset, num_samples) device = get_device(model) correct = 0 with in_eval_mode(model), torch.no_gr...
class ProjectWindow(tk.Frame): def __init__(self, parent, sdkpath, args): tk.Frame.__init__(self, parent) self.master = parent self.sdkpath = sdkpath self.init_window(args) self.configs = dict() self.ssid = str() self.password = str() def setState(self, th...
class CumOp(COp): __props__ = ('axis', 'mode') check_input = False params_type = ParamsType(c_axis=int_t, mode=EnumList(('MODE_ADD', 'add'), ('MODE_MUL', 'mul'))) def __init__(self, axis: Optional[int]=None, mode='add'): if (mode not in ('add', 'mul')): raise ValueError(f'{type(self)...
def log_args_to_txt(log_txt, args): if (not os.path.exists(log_txt)): with open(log_txt, 'w') as txtfile: args_ = vars(args) args_str = '' for (k, v) in args_.items(): args_str = ((((args_str + str(k)) + ':') + str(v)) + ',\t\n') txtfile.write(...
def rounding_numerical_components(): Print_Function() (ex, ey, ez) = MV.setup('e_x e_y e_z', metric='[1,1,1]') X = (((1.2 * ex) + (2.34 * ey)) + (0.555 * ez)) Y = (((0.333 * ex) + (4 * ey)) + (5.3 * ez)) print('X =', X) print('Nga(X,2) =', Nga(X, 2)) print('X*Y =', (X * Y)) print('Nga(X*...
def preprocess_for_train(image, output_height, output_width, resize_side_min=_RESIZE_SIDE_MIN, resize_side_max=_RESIZE_SIDE_MAX): resize_side = tf.random_uniform([], minval=resize_side_min, maxval=(resize_side_max + 1), dtype=tf.int32) image = _aspect_preserving_resize(image, resize_side) image = _random_cr...
class ExtractPathTest(object): def test_extract_static_path(self): path = '/test' assert (extract_path(path) == '/test') def test_extract_path_with_a_single_simple_parameter(self): path = '/test/<parameter>' assert (extract_path(path) == '/test/{parameter}') def test_extract_...
def decoder_rnn(cell, inputs, enc_outputs, enc_final_states, seq_length, hidden_dim, num_glimpse, batch_size, is_train, end_of_sequence_id=0, initializer=None, max_length=None): with tf.variable_scope('decoder_rnn') as scope: def attention(ref, query, with_softmax, scope='attention'): with tf.va...
def get_cfg_tree(nsql: str): stack: List = [] expression_stack: List = [] current_tree_node = TreeNode(name=nsql) for idx in range(len(nsql)): if (nsql[idx] == '('): stack.append(idx) if ((idx > 1) and (nsql[(idx - 2):(idx + 1)] == 'QA(') and ((idx - 2) != 0)): ...
def data_masks(all_usr_pois, item_tail): us_lens = [len(upois) for upois in all_usr_pois] len_max = max(us_lens) us_pois = [(upois + (item_tail * (len_max - le))) for (upois, le) in zip(all_usr_pois, us_lens)] us_msks = [(([1] * le) + ([0] * (len_max - le))) for le in us_lens] return (us_pois, us_ms...
_module() class UNet(BaseModule): def __init__(self, in_channels=3, base_channels=64, num_stages=5, strides=(1, 1, 1, 1, 1), enc_num_convs=(2, 2, 2, 2, 2), dec_num_convs=(2, 2, 2, 2), downsamples=(True, True, True, True), enc_dilations=(1, 1, 1, 1, 1), dec_dilations=(1, 1, 1, 1), with_cp=False, conv_cfg=None, norm_...
() _options(dbt_flags) _tracking def detect(**kwargs): print(f'Detecting tables', 'RUN') dbt_vars = parse_dbt_vars(kwargs.get('dbt_vars')) run_list = ['dbt', 'run', '--models', 're_data_columns', 're_data_monitored'] if dbt_vars: run_list.extend(['--vars', yaml.dump(dbt_vars)]) add_dbt_flags...