code
stringlengths
281
23.7M
def all_smt(formula, keys): target_logic = get_logic(formula) print(('Target Logic: %s' % target_logic)) with Solver(logic=target_logic) as solver: solver.add_assertion(formula) while solver.solve(): partial_model = [EqualsOrIff(k, solver.get_value(k)) for k in keys] ...
def _pseudonymise_DS(value): original_DS_value = str(value) my_decimal = Decimal(original_DS_value) as_tuple = my_decimal.as_tuple() digits = as_tuple.digits count_digits = len(digits) my_hash_func = hashlib.new('sha3_256') encoded_value = original_DS_value.encode('ASCII') my_hash_func.u...
class ObserverMeta(type): def __new__(cls, clsname, superclasses, attributedict): klass = super().__new__(cls, clsname, superclasses, attributedict) observes = attributedict.get('observes') if (clsname == 'Observer'): return klass if (observes is None): raise ...
.slow .parametrize('untied', [True, False]) _figures_equal() def test_RanksComparatorPlotter_r2_score(fig_test, fig_ref, untied): test_ax = fig_test.subplots() rank0 = agg.RankResult('test', ['a', 'b'], [1, 1], {}) rank1 = agg.RankResult('test', ['a', 'b'], [1, 1], {}) rcmp = ranks_cmp.mkrank_cmp(rank0,...
def load_feature(ft_path, ft_format, shape=None): if (ft_format == 'npy'): video_df = np.load(ft_path) if (shape == 'CT'): video_df = video_df.T elif (ft_format == 'torch'): video_df = torch.load(ft_path).numpy() else: raise ValueError('unsupported feature format:...
def test_shape_tuple(): x = Variable(MyType2(), None, None) assert (shape_tuple(x) == ()) x = tensor(dtype=np.float64, shape=(1, 2, None)) res = shape_tuple(x) assert isinstance(res, tuple) assert isinstance(res[0], ScalarConstant) assert (res[0].data == 1) assert isinstance(res[1], Scal...
class TestUnittestMethods(): def test_django(self, django_pytester: DjangoPytester) -> None: django_pytester.create_test_module("\n from django.test import TestCase\n\n class TestFoo(TestCase):\n \n def setUpClass(self):\n print('\\nCALL...
def main(data_dir, client, bc, config): benchmark(read_tables, data_dir, bc, dask_profile=config['dask_profile']) query_1 = '\n\t\tSELECT\n\t\t\tss.ss_customer_sk AS customer_sk,\n\t\t\tsum( case when (d_year = 2001) THEN ss_net_paid ELSE 0.0 END) first_year_total,\n\t\t\tsum( case when (d_year = 2002) THEN ss_...
def simplified_power(left, right): (left, right) = _simplify_elementwise_binary_broadcasts(left, right) out = _simplified_binary_broadcast_concatenation(left, right, simplified_power) if (out is not None): return out if pybamm.is_scalar_zero(right): return pybamm.ones_like(left) if p...
class FileSlice(AbstractContextManager): def __init__(self, filepath: str, seek_from: int, read_limit: int): self.filepath = filepath self.seek_from = seek_from self.read_limit = read_limit self.n_seen = 0 def __enter__(self): self.f = open(self.filepath, 'rb') se...
class AsyncHypothesisTest(PytestAsyncioFunction): def _can_substitute(item: Function) -> bool: func = item.obj return (getattr(func, 'is_hypothesis_test', False) and asyncio.iscoroutinefunction(func.hypothesis.inner_test)) def runtest(self) -> None: self.obj.hypothesis.inner_test = wrap_...
def hook_init(fm): fm.execute_console('map {key} shell -p lsblk'.format(key=LIST_MOUNTS_KEY)) diskcmd = 'lsblk -lno NAME | awk \'!/[1-9]/ {sub(/sd/, ""); print}\'' disks = subprocess.check_output(diskcmd, shell=True).decode('utf-8').replace('\r', '').replace('\n', '') for disk in disks: partcmd ...
class SplitTags(SongsMenuPlugin): PLUGIN_ID = 'Split Tags' PLUGIN_NAME = _('Split Tags') PLUGIN_DESC = _('Splits the disc number from the album and the version from the title at the same time.') PLUGIN_ICON = Icons.EDIT_FIND_REPLACE plugin_handles = any_song(has_title_splittable) def plugin_song...
def start_portal_interactive(): def _iportal(fail): (portal_twistd_cmd, server_twistd_cmd) = _get_twistd_cmdline(False, False) portal_twistd_cmd.append('--nodaemon') if _is_windows(): create_no_window = Popen(server_twistd_cmd, env=getenv(), bufsize=(- 1), creationfl...
def make_batch_data_sampler(sampler, images_per_batch, num_iters=None, start_iter=0): batch_sampler = data.sampler.BatchSampler(sampler, images_per_batch, drop_last=False) if (num_iters is not None): batch_sampler = IterationBasedBatchSampler(batch_sampler, num_iters, start_iter) return batch_sample...
class NewTaskTrainer(Inc_Learning_Appr): def __init__(self, model, device, nepochs=160, lr=0.1, lr_min=0.0001, lr_factor=10, lr_patience=8, clipgrad=10000, momentum=0.9, wd=0.0005, multi_softmax=False, wu_nepochs=0, wu_lr_factor=1, fix_bn=False, eval_on_train=False, logger=None): super(NewTaskTrainer, self)...
def get_args(method='MLE'): parser = argparse.ArgumentParser(description=f'training neural Datalog through time (NDTT) using {method}') parser.add_argument('-d', '--Domain', required=True, type=str, help='which domain to work on?') parser.add_argument('-db', '--Database', required=True, type=str, help='whic...
def get_prev_current_ss(df, store_sales_col='ss_sum'): curr_ss_f = ((df['ss_sold_date_sk'] >= df['imp_start_date']) & (df['ss_sold_date_sk'] < (df['imp_start_date'] + df['no_days_comp_price']))) prev_ss_f = ((df['ss_sold_date_sk'] >= (df['imp_start_date'] - df['no_days_comp_price'])) & (df['ss_sold_date_sk'] < ...
class VGG(nn.Module): def __init__(self, features, num_classes=1000): super(VGG, self).__init__() self.features = features self.classifier = nn.Linear(512, num_classes) self._initialize_weights() def forward(self, x): x = self.features(x) x = x.view(x.size(0), (- ...
def test_get_conference_found(client, db): conference = f.ConferenceFactory() url = reverse('get-conference', kwargs={'conference_slug': conference.slug}) response = client.get(url, follow=True) assert (response.redirect_chain == [(reverse('proposals-list', kwargs={'conference_slug': conference.slug}), ...
class V1Protocol(RegistryProtocol): FAILURE_CODES: Dict[(Enum, Dict[(Failures, int)])] = {V1ProtocolSteps.PUT_IMAGES: {Failures.INVALID_AUTHENTICATION: 403, Failures.UNAUTHENTICATED: 401, Failures.UNAUTHORIZED: 403, Failures.APP_REPOSITORY: 405, Failures.SLASH_REPOSITORY: 400, Failures.INVALID_REPOSITORY: 400, Fail...
class TestWeightSvdLayerSplitandSVDPrunner(): .parametrize('model_type', ['Sequential', 'Functional']) .parametrize('rank', [12, 20]) .parametrize('cost_metric', [CostMetric.mac, CostMetric.memory]) def test_split_layer(self, model_type, rank, cost_metric): model = get_model(model_type) ...
class YAMLPrinter(): def display(d: Union[(str, Dict[(str, Any)])], **_kwargs: Any) -> None: try: import yaml print(yaml.safe_dump(d, default_flow_style=False)) except ImportError: sys.exit('PyYaml is not installed.\nInstall it with `pip install PyYaml` to use the...
class TestCFtime(): def test_add_time_bounds_dimension(self): from satpy.cf.coords import add_time_bounds_dimension test_array = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) times = np.array(['2018-05-30T10:05:00', '2018-05-30T10:05:01', '2018-05-30T10:05:02', '2018-05-30T10:05:03'], dtype=np....
class Blackbox(namedtuple('Blackbox', ['partition', 'output_indices'])): def hidden_indices(self): return tuple(sorted((set(self.micro_indices) - set(self.output_indices)))) def micro_indices(self): return tuple(sorted((idx for part in self.partition for idx in part))) def macro_indices(self...
class FontRow(Adw.ActionRow): __gtype_name__ = 'FontRow' def __init__(self, font_data: dict): super().__init__() self.props.title = font_data['name'] self.props.subtitle = ' / '.join((font_data['family'], font_data['style'], font_data['weight'])) btn_remove = Gtk.Button(valign=Gt...
def get_param_dict(args, model_without_ddp: nn.Module): try: param_dict_type = args.param_dict_type except: param_dict_type = 'default' assert (param_dict_type in ['default', 'ddetr_in_mmdet', 'large_wd']) if (param_dict_type == 'default'): param_dicts = [{'params': [p for (n, p)...
class AddDestroyHandler(GraphRewriter): def apply(self, fgraph): supervisor_added = False for feature in fgraph._features: if isinstance(feature, Supervisor): supervisor_added = True break if (not supervisor_added): warnings.warn(f'A Su...
class NormalQueue1EntryRTL(Component): def construct(s, EntryType): s.recv = RecvIfcRTL(EntryType) s.send = SendIfcRTL(EntryType) s.count = OutPort() s.full = Wire() s.entry = Wire(EntryType) s.count //= s.full s.send.msg //= s.entry s.send.val //= s.f...
def diagonal_coulomb_potential_and_kinetic_terms_as_arrays(hamiltonian): if (not isinstance(hamiltonian, FermionOperator)): try: hamiltonian = normal_ordered(get_fermion_operator(hamiltonian)) except TypeError: raise TypeError('hamiltonian must be either a FermionOperator or ...
def prepare_query_payload(backend, offset, payload_string, column_name=None): _temp = [] if column_name: _payload = payload_string.format(offset=offset, column_name=column_name) if ((backend == 'Microsoft SQL Server') and ('id' in column_name)): _payload = replace_with(_payload, colu...
def parse_old_label(data_root, in_path, img_size=False): imgid2imgname = {} imgid2anno = {} idx = 0 for line in list_from_file(in_path): line = line.strip().split() img_full_path = osp.join(data_root, line[0]) if (not osp.exists(img_full_path)): continue ann_f...
_canonicalize _stabilize _rewriter([Reshape]) def local_reshape_lift(fgraph, node): if (isinstance(node.op, Reshape) and node.inputs[0].owner and isinstance(node.inputs[0].owner.op, Elemwise) and (len(node.inputs[0].owner.inputs) == 1)): r = node.op(node.inputs[0].owner.inputs[0], node.inputs[1]) co...
class NotAllowedMethodsTests(AuthenticatedAPITestCase): def setUpTestData(cls): cls.message = create_offensive_message() def test_returns_405_for_get(self): url = reverse('api:bot:offensivemessage-detail', args=(self.message.id,)) response = self.client.get(url) self.assertEqual(...
def reconstructions(data, model, session, batch_dim=10, sample=False): (m0, _, _, a, x, _, f, _, _) = data.next_train_batch(batch_dim) (n, e) = session.run(([model.nodes_gumbel_argmax, model.edges_gumbel_argmax] if sample else [model.nodes_argmax, model.edges_argmax]), feed_dict={model.edges_labels: a, model.no...
class ServiceConfig(): pathfinding_service_address: Optional[Address] = None pathfinding_max_paths: int = DEFAULT_PATHFINDING_MAX_PATHS pathfinding_max_fee: TokenAmount = DEFAULT_PATHFINDING_MAX_FEE pathfinding_iou_timeout: BlockTimeout = DEFAULT_PATHFINDING_IOU_TIMEOUT monitoring_enabled: bool = Fa...
class Quantile8BitQuantization(Quantization): compression_type = runtime_pb2.QUANTILE_8BIT def quantize(self, tensor: torch.Tensor, allow_inplace: bool=False) -> Tuple[(np.ndarray, np.ndarray)]: tensor = tensor.detach().float() borders = torch.as_tensor(quantile_qq_approximation(tensor.numpy(), ...
class TestSilent(unittest.TestCase): def test_nonsilent(self): actual = file_info.silent(INPUT_FILE) expected = False self.assertEqual(expected, actual) def test_nonsilent_pathlib(self): actual = file_info.silent(Path(INPUT_FILE)) expected = False self.assertEqual...
class TestInitialSetup(TestCase): ('evennia.server.initial_setup.AccountDB') def test_get_god_account(self, mocked_accountdb): mocked_accountdb.objects.get = MagicMock(return_value=1) self.assertEqual(initial_setup.get_god_account(), 1) mocked_accountdb.objects.get.assert_called_with(id=...
class TestInSubprocess(unittest.TestCase): def runProcessAndGetAsciiStdoutOrStderr(self, cmdline): if (sys.platform != 'win32'): cmdline = shlex.split(cmdline) p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() ...
class Up(nn.Module): def __init__(self, in_channels, out_channels, bilinear=True): super().__init__() if bilinear: self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) else: self.up = nn.ConvTranspose2d((in_channels // 2), (in_channels // 2), ker...
def get_pure_function(fcn) -> PureFunction: errmsg = 'The input function must be a function, a method of torch.nn.Module, a method of xitorch.EditableModule, or a sibling method' if isinstance(fcn, PureFunction): return fcn elif (inspect.isfunction(fcn) or isinstance(fcn, torch.jit.ScriptFunction)):...
def get_artifact(owner: str, repo: str, sha: str, action_name: str, artifact_name: str) -> str: client = authorize(owner, repo) try: runs = client.get(f'/repos/{owner}/{repo}/actions/runs', params={'per_page': 100}) runs.raise_for_status() runs = runs.json() for run in runs['work...
def cal_false_alarm(gt, preds, threshold=0.5): preds = list(preds.cpu().detach().numpy()) gt = list(gt.cpu().detach().numpy()) preds = np.repeat(preds, 16) preds[(preds < threshold)] = 0 preds[(preds >= threshold)] = 1 (tn, fp, fn, tp) = confusion_matrix(gt, preds, labels=[0, 1]).ravel() far...
def perform_cle_bc(config: argparse.Namespace): data_pipeline = ImageNetDataPipeline(config) input_shape = (image_net_config.dataset['image_width'], image_net_config.dataset['image_height'], image_net_config.dataset['image_channels']) tf.keras.backend.clear_session() tf_config = tf.ConfigProto() tf_...
class GlobalDecl(Statement): __slots__ = ('names',) __match_args__ = ('names',) names: list[str] def __init__(self, names: list[str]) -> None: super().__init__() self.names = names def accept(self, visitor: StatementVisitor[T]) -> T: return visitor.visit_global_decl(self)
def build_data_info(args): args.dataset = osp.basename(osp.normpath(args.data_root)) with open(args.data_info, 'r') as f: data_info = json.load(f)[args.dataset] args.train_session_set = data_info['train_session_set'] args.test_session_set = data_info['test_session_set'] args.class_index = da...
def resize_dataset(i_root, o_root, mode='train'): out_images_path = osp.join(o_root, mode, 'images') out_masks_path = osp.join(o_root, mode, 'masks_12') check_dir(o_root) check_dir(out_images_path) check_dir(out_masks_path) image_path = osp.join(i_root, mode, 'images') mask_path = osp.join(i...
class TFCvtIntermediate(tf.keras.layers.Layer): def __init__(self, config: CvtConfig, embed_dim: int, mlp_ratio: int, **kwargs): super().__init__(**kwargs) self.dense = tf.keras.layers.Dense(units=int((embed_dim * mlp_ratio)), kernel_initializer=get_initializer(config.initializer_range), activation=...
class TextureGrid(TextureRegion, UniformTextureSequence): items = () rows = 1 columns = 1 item_width = 0 item_height = 0 def __init__(self, grid): image = grid.get_texture() if isinstance(image, TextureRegion): owner = image.owner else: owner = ima...
class ClassificationTask(LightningModule): def __init__(self, model: PreTrainedModel, args: ClassificationTrainArguments): super().__init__() self.model = model self.args = args def configure_optimizers(self): optimizer = AdamW(self.parameters(), lr=self.args.learning_rate) ...
_module() class MeshAdversarialDataset(Dataset): def __init__(self, train_dataset, adversarial_dataset): super().__init__() self.train_dataset = build_dataset(train_dataset) self.adversarial_dataset = build_dataset(adversarial_dataset) self.length = len(self.train_dataset) def __...
class Graph(): name = '' def __init__(self, *chain): self.edges = {BEGIN: set()} self.named = {} self.nodes = [] if len(chain): self.add_chain(*chain) def __iter__(self): (yield from self.nodes) def __len__(self): return len(self.nodes) def...
def __get_all_files(root: Path, folder: (Path | None)=None) -> list[str]: if (not folder): folder = root results = [] for sub_folder in folder.iterdir(): results.append(sub_folder.relative_to(root).__str__().replace('\\', '/').replace('.html', '')) if sub_folder.is_dir(): ...
def get_method_config(key, config={}, yaml_path='configs/methods.yaml', yaml_data=None): if ((not key) or (key is None)): return None assert (yaml_path or yaml_data) if (yaml_data is None): yaml_data = yaml.load(open(yaml_path), Loader=yaml.Loader) assert (key in yaml_data.keys()), f'`{k...
class TestEndecaDgraphCollector(CollectorTestCase): def setUp(self): config = get_collector_config('EndecaDgraphCollector', {}) self.collector = EndecaDgraphCollector(config, None) def test_import(self): self.assertTrue(EndecaDgraphCollector) ('urllib2.urlopen') (Collector, 'publ...
def load_model_config_from_hf(model_id: str): assert has_hf_hub(True) cached_file = _download_from_hf(model_id, 'config.json') pretrained_cfg = load_cfg_from_json(cached_file) pretrained_cfg['hf_hub_id'] = model_id pretrained_cfg['source'] = 'hf-hub' model_name = pretrained_cfg.get('architecture...
def repo_with_no_tags_tag_commits(git_repo_factory, file_in_repo): git_repo = git_repo_factory() add_text_to_file(git_repo, file_in_repo) git_repo.git.commit(m='Initial commit') add_text_to_file(git_repo, file_in_repo) git_repo.git.commit(m=':nut_and_bolt: add some more text') add_text_to_file(g...
class DataTrainingArguments(): task_name: Optional[str] = field(default='ner', metadata={'help': 'The name of the task (ner, pos...).'}) dataset_name: Optional[str] = field(default='nielsr/funsd-layoutlmv3', metadata={'help': 'The name of the dataset to use (via the datasets library).'}) dataset_config_name...
def compute_mIoU(gt_dir, pred_dir, devkit_dir=''): with open(join(devkit_dir, 'info.json'), 'r') as fp: info = json.load(fp) num_classes = np.int(info['classes']) print('Num classes', num_classes) name_classes = np.array(info['label'], dtype=np.str) mapping = np.array(info['label2train'], dt...
def find_char_span_by_token_idx(id, doc): doc_text = (doc.text + ' ABCDEF') token_list = doc_text.split() token_text = doc[id].text assert (token_text in token_list[id]) if (token_text != token_list[id]): return [] new_sen = ' '.join(token_list[id:]) char_star = doc_text.find(new_sen...
class CT_TabStops(BaseOxmlElement): tab = OneOrMore('w:tab', successors=()) def insert_tab_in_order(self, pos, align, leader): new_tab = self._new_tab() (new_tab.pos, new_tab.val, new_tab.leader) = (pos, align, leader) for tab in self.tab_lst: if (new_tab.pos < tab.pos): ...
def getWholeCount(path): count = [] catories = os.listdir(path) for catory in catories: pathcat = os.path.join(path, catory) count.append(len(os.listdir(pathcat))) print((((((('|' + catory) + '|') + str(len(os.listdir(pathcat)))) + '|') + str(len(os.listdir(os.path.join(pathapks, cat...
class StatisticsDisplay(Observer, DisplayElement): __maxTemp: float = 0.0 __minTemp: float = 200 __tempSum: float = 0.0 __numReadings: int = 0 __weatherData: WeatherData def __init__(self, weatherData: WeatherData): self.__weatherData = weatherData weatherData.registerObserver(se...
def main_worker(ngpus_per_node, args): global best_acc1 if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.pretrained: print("=> using pre-trained model '{}'".format(args.arch)) model = models.__dict__[args.arch](pretrained=True, args=args) else...
def add_weight_decay(adjust_per_optimizer=True): if (adjust_per_optimizer and ('lars' in FLAGS.optimizer)): return l2_losses = [tf.nn.l2_loss(v) for v in tf.trainable_variables() if ('batch_normalization' not in v.name)] tf.losses.add_loss((FLAGS.weight_decay * tf.add_n(l2_losses)), tf.GraphKeys.REG...
_auth def update_pwd(request): if (request.method == 'POST'): pks = request.POST.getlist('pks') pwd = request.POST.get('pwd') try: for pk in pks: server = Assets.objects.get(id=pk).serverassets server.password = CryptPwd().encrypt_pwd(pwd) ...
class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.linear1 = nn.Linear(d_model, dim_feedfor...
class RandomChoiceShear(object): def __init__(self, values, p=None, interp='bilinear', lazy=False): if isinstance(values, (list, tuple)): values = th.FloatTensor(values) self.values = values if (p is None): p = (th.ones(len(values)) / len(values)) elif (abs((1...
class SnapshotSerializer(serializers.ModelSerializer): values = serializers.SerializerMethodField() class Meta(): model = Snapshot fields = ('title', 'description', 'values', 'created', 'updated') def get_values(self, obj): values = Value.objects.filter(snapshot=obj).select_related('...
_config def test_kill(manager): manager.c.group['SCRATCHPAD'].dropdown_reconfigure('dd-a') manager.test_window('one') assert_focused(manager, 'one') assert ('window' not in manager.c.group['SCRATCHPAD'].dropdown_info('dd-a')) manager.c.group['SCRATCHPAD'].dropdown_toggle('dd-a') is_spawned(manag...
def _populate_kernel_cache(np_type, blocks, dim_x, dim_z, dim_u, max_tpb): if (np_type not in _SUPPORTED_TYPES): raise ValueError('Datatype {} not found for Kalman Filter'.format(np_type)) if (np_type == 'float32'): c_type = 'float' else: c_type = 'double' specializations = ('_cu...
def parse_args(): parser = ArgumentParser(description='PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes') parser.add_argument('--num_cores', type=int, default=1, help='Number of TPU cores to use (1 or 8).') parser.add_argument('training_script', type=s...
def _gen_rhf_response_gam(mf, mo_coeff=None, mo_occ=None, singlet=None, hermi=0, max_memory=None): from pyscf.pbc.dft import numint, multigrid assert isinstance(mf, hf.RHF) if (mo_coeff is None): mo_coeff = mf.mo_coeff if (mo_occ is None): mo_occ = mf.mo_occ cell = mf.cell kpt = ...
class DLRM_Transformer(DLRM): def __init__(self, embedding_bag_collection: EmbeddingBagCollection, dense_in_features: int, dense_arch_layer_sizes: List[int], over_arch_layer_sizes: List[int], nhead: int=8, ntransformer_layers: int=4, dense_device: Optional[torch.device]=None) -> None: super().__init__(embed...
class Embed(): def __init__(self): self.transformer = SentenceTransformer(model_name, device='cuda') def __call__(self, text_batch: List[str]): embeddings = self.transformer.encode(text_batch, batch_size=100, device='cuda').tolist() return list(zip(text_batch, embeddings))
class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) pages = models.IntegerField() def __str__(self): return self.name def get_absolute_url(self): return reverse('books_fbv_user:book_edit', kwar...
def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = {'SayHello': grpc.unary_unary_rpc_method_handler(servicer.SayHello, request_deserializer=generated_dot_greeter__pb2.HelloRequest.FromString, response_serializer=generated_dot_greeter__pb2.HelloReply.SerializeToString), 'SayHelloGoodbye': grp...
def get_logger(log_path, results_raw_metrics_path, results_avg_metrics_path): with open(logging_configs_path, 'r') as f: dict_conf = yaml.safe_load(f) dict_conf['handlers']['fh']['filename'] = log_path dict_conf['handlers']['fh_avg']['filename'] = results_avg_metrics_path dict_conf['handlers']['...
def round_window_to_full_blocks(window, block_shapes, height=0, width=0): if (len(set(block_shapes)) != 1): raise WindowError('All bands must have the same block/stripe structure') window = evaluate(window, height=height, width=width) height_shape = block_shapes[0][0] width_shape = block_shapes[...
class TBItemsTurnHandler(DefaultScript): def at_script_creation(self): self.key = 'Combat Turn Handler' self.interval = 5 self.persistent = True self.db.fighters = [] for thing in self.obj.contents: if thing.db.hp: self.db.fighters.append(thing) ...
class F8_TestCase(FC3_TestCase): def runTest(self): FC3_TestCase.runTest(self) self.assertFalse(F8_RootPw().lock) self.assert_parse('rootpw --lock secrethandshake', 'rootpw --lock --plaintext secrethandshake\n') self.assert_parse('rootpw --plaintext secrethandshake', 'rootpw --plaint...
class PositionWiseFeedForward(nn.Module): def __init__(self, model_size, inner_size, dropout=0.0, variational=False, activation='relu', glu=False, weight_drop=0.0, dropout_residual=False, res_dropout=0.0): super().__init__() self.model_size = model_size self.inner_size = inner_size s...
def test_make_prompt(): import difflib def assert_equal_and_show_diff(expected, actual): if (expected != actual): diff = difflib.ndiff(expected.splitlines(keepends=True), actual.splitlines(keepends=True)) print(''.join(diff)) assert (expected == actual) example1 =...
_new_faces(MaterialGroup.ROOF) def create_flat_roof(bm, faces, prop): top_face = extrude_and_outset(bm, faces, prop.thickness, prop.outset) if prop.add_border: bmesh.ops.inset_region(bm, faces=top_face, thickness=prop.border, use_even_offset=True) ret = bmesh.ops.extrude_face_region(bm, geom=top...
def test_html_configured_output_dir(testdir): script = testdir.makepyfile(SCRIPT) testdir.tmpdir.join('.coveragerc').write('\n[html]\ndirectory = somewhere\n') result = testdir.runpytest('-v', f'--cov={script.dirpath()}', '--cov-report=html', script) result.stdout.fnmatch_lines(['*- coverage: platform *...
class TSongsMenuPlugins(TestCase): def _confirmer(self, *args): self.confirmed = True def setUp(self): self.tempdir = mkdtemp() self.pm = PluginManager(folders=[self.tempdir]) self.confirmed = False self.handler = SongsMenuPluginHandler(self._confirmer, self._confirmer) ...
def main(): import argparse import IPython parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) choices = ['franka_panda/panda_suction', 'franka_panda/panda_drl'] parser.add_argument('--robot-model', default=choices[0], choices=choices, help=' ') args = parser...
class MobileViTASPP(nn.Module): def __init__(self, config: MobileViTConfig) -> None: super().__init__() in_channels = config.neck_hidden_sizes[(- 2)] out_channels = config.aspp_out_channels if (len(config.atrous_rates) != 3): raise ValueError('Expected 3 values for atrous...
class ImageDecoder(Decoder): def get_animation_file_extensions(self): return [] def decode(self, filename, file): raise NotImplementedError() def decode_animation(self, filename, file): raise ImageDecodeException('This decoder cannot decode animations.') def __repr__(self): ...
def mask(self, operation, destination_kind, x_offset, y_offset, source_bitmap): Mask(display=self.display, opcode=self.display.get_extension_major(extname), destination_window=self, operation=operation, destination_kind=destination_kind, x_offset=x_offset, y_offset=y_offset, source_bitmap=source_bitmap)
def get_image_path(image_lists, label_name, index, image_dir, category): if (label_name not in image_lists): tf.logging.fatal('Label does not exist %s.', label_name) label_lists = image_lists[label_name] if (category not in label_lists): tf.logging.fatal('Category does not exist %s.', catego...
def _set_ctrl_swap(ctrl_bit, bloq: CSwap): states = [ZeroState(), OneState()] effs = [ZeroEffect(), OneEffect()] bb = BloqBuilder() q0 = bb.add(states[ctrl_bit]) q1 = bb.add_register('q1', bloq.bitsize) q2 = bb.add_register('q2', bloq.bitsize) (q0, q1, q2) = bb.add(bloq, ctrl=q0, x=q1, y=q2)...
class TestBloombergTickerMapper(TestCase): def test_ticker_to_figi__no_data_preloading(self): mapper = BloombergTickerMapper(data_caching=False) tickers = [BloombergTicker('SPX Index', SecurityType.INDEX), BloombergTicker('SPY US Equity', SecurityType.STOCK), BloombergTicker('USDCHF Curncy', Securit...
class BiRecurrentMapper(SequenceMapper): def __init__(self, fw, bw=None, merge: MergeLayer=None, swap_memory=False): self.fw = fw self.swap_memory = swap_memory self.bw = bw self.merge = merge def apply(self, is_train, inputs, mask=None): fw = self.fw(is_train) bw...
class AttrVI_ATTR_USB_INTR_IN_PIPE(RangeAttribute): resources = [(constants.InterfaceType.usb, 'RAW')] py_name = '' visa_name = 'VI_ATTR_USB_INTR_IN_PIPE' visa_type = 'ViInt16' default = NotAvailable (read, write, local) = (True, True, True) (min_value, max_value, values) = (129, 143, [(- 1)...
class TestInlineQueryWithoutRequest(TestInlineQueryBase): def test_slot_behaviour(self, inline_query): for attr in inline_query.__slots__: assert (getattr(inline_query, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(inline_query)) == len(set(mro_slots(inline_que...
def parse_pyproject_toml(text, rootdir, name=None, *, tools=None, requirefiles=True): data = tomllib.loads(text) unused = list(data) for (section, normalize) in SECTIONS.items(): try: secdata = data[section] except KeyError: data[section] = None else: ...
class DRN_A(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(DRN_A, self).__init__() self.out_dim = (512 * block.expansion) self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) ...
class Add(GateWithRegisters, cirq.ArithmeticGate): bitsize: int def signature(self): return Signature.build(a=self.bitsize, b=self.bitsize) def registers(self) -> Sequence[Union[(int, Sequence[int])]]: return (([2] * self.bitsize), ([2] * self.bitsize)) def with_registers(self, *new_regi...