code
stringlengths
281
23.7M
def _tf_create_chunk_masks(chunk_starts, num_chunk_frames, video_len): def tf_map_to_chunk_mask(chunk_start): valid_chunk_labels_len = tf.minimum(num_chunk_frames, (video_len - chunk_start)) return _tf_create_chunk_mask(valid_chunk_labels_len) return tf.map_fn(fn=tf_map_to_chunk_mask, elems=chun...
def test_foreach_with_iterator(): context = Context({'lst': []}) from itertools import product context.pystring_globals_update({'product': product}) step = Step({'name': 'pypyr.steps.py', 'foreach': PyString('product([1, 2], ["A", "B"])'), 'in': {'py': 'lst.append(i)'}}) step.run_step(context) a...
def betweenness_centrality(graph, name='betweenness', mode='nodes', weight='mm_len', endpoints=True, radius=None, distance=None, normalized=False, verbose=True, **kwargs): netx = graph.copy() graph = nx.Graph() for (u, v, k, data) in netx.edges(data=True, keys=True): if graph.has_edge(u, v): ...
def _apply_project_table(dist: 'Distribution', config: dict, root_dir: _Path): project_table = config.get('project', {}).copy() if (not project_table): return _handle_missing_dynamic(dist, project_table) _unify_entry_points(project_table) for (field, value) in project_table.items(): ...
class SAGEModule(nn.Module): def __init__(self, dim, hidden_dim_multiplier, dropout, **kwargs): super().__init__() self.feed_forward_module = FeedForwardModule(dim=dim, input_dim_multiplier=2, hidden_dim_multiplier=hidden_dim_multiplier, dropout=dropout) def forward(self, graph, x): mess...
class CalibrationPlot(object): def __init__(self, name): self.name = name self.mode = GL_LINE self.fusionQPose = [1, 0, 0, 0] self.alignmentQ = [1, 0, 0, 0] self.recentpoints = [] self.historypoints = [] self.sigmapoints = [] self.points = [] def a...
def summary_string(model, input_size, batch_size=(- 1), device=torch.device('cuda:0'), dtypes=None): if (dtypes == None): dtypes = ([torch.FloatTensor] * len(input_size)) summary_str = '' def register_hook(module): def hook(module, input, output): class_name = str(module.__class_...
class _ReversibleFunction(Function): def forward(ctx, x, blocks, kwargs): ctx.kwargs = kwargs for block in blocks: x = block(x, **kwargs) ctx.y = x.detach() ctx.blocks = blocks return x def backward(ctx, dy): y = ctx.y kwargs = ctx.kwargs ...
def trapezoidal(mini, mode1, mode2, maxi, size=None): if (size is None): p = np.random.uniform() v = (((p * (((maxi + mode2) - mini) - mode1)) + (mini + mode1)) / 2) if (v < mode1): v = (mini + np.sqrt(((mode1 - mini) * (((2 * v) - mini) - mode1)))) elif (v > mode2): ...
class BottleneckLayer(GenericLayer): def __init__(self, in_planes, out_planes, stride=1, mid_planes_and_cardinality=None, reduction=4, final_bn_relu=True, use_se=False, se_reduction_ratio=16): assert (is_pos_int(in_planes) and is_pos_int(out_planes)) assert ((is_pos_int(stride) or is_pos_int_tuple(s...
class Status(StatusBitsBase): _fields_ = [('function', c_uint8, 3), ('range', c_uint8, 3), ('digits', c_uint8, 2), ('res1', c_uint8, 1), ('ext_trig', c_uint8, 1), ('cal_enable', c_uint8, 1), ('front_rear', c_uint8, 1), ('fifty_hz', c_uint8, 1), ('auto_zero', c_uint8, 1), ('auto_range', c_uint8, 1), ('int_trig', c_u...
def se_resnext101_32x4d(num_classes=1000, pretrained='imagenet'): model = SENet(SEResNeXtBottleneck, [3, 4, 23, 3], groups=32, reduction=16, dropout_p=None, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, num_classes=num_classes) if (pretrained is not None): settings = pret...
def initialize_weights(net_l, scale=1): if (not isinstance(net_l, list)): net_l = [net_l] for net in net_l: for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight, a=0, mode='fan_in') m.weight.data *= scale i...
class AttrVI_ATTR_GPIB_SECONDARY_ADDR(RangeAttribute): resources = [(constants.InterfaceType.gpib, 'INSTR'), (constants.InterfaceType.gpib, 'INTFC')] py_name = 'secondary_address' visa_name = 'VI_ATTR_GPIB_SECONDARY_ADDR' visa_type = 'ViUInt16' default = NotAvailable (read, write, local) = (True...
.skipif((not numpyro_available), reason='BetaBinomial dispatch requires numpyro') def test_beta_binomial(): rng = shared(np.random.RandomState(123)) n = np.array([10, 40]) a = np.array([1.5, 13]) b = np.array([0.5, 9]) g = pt.random.betabinom(n, a, b, size=(10000, 2), rng=rng) g_fn = random_func...
def trace_begin(): global show_tx global show_rx global dev global debug for i in range(len(sys.argv)): if (i == 0): continue arg = sys.argv[i] if (arg == 'tx'): show_tx = 1 elif (arg == 'rx'): show_rx = 1 elif (arg.find('de...
def constant_fold(xs: Sequence[TensorVariable], raise_not_constant: bool=True) -> Tuple[(np.ndarray, ...)]: fg = FunctionGraph(outputs=xs, features=[ShapeFeature()], clone=True) folded_xs = rewrite_graph(fg).outputs if (raise_not_constant and (not all((isinstance(folded_x, Constant) for folded_x in folded_x...
class PrepareISIC2018(): def __init__(self, data_dir, image_size, logger=None): self.print = (logger.info if logger else print) self.data_dir = data_dir self.image_size = image_size self.data_prefix = 'ISIC_' self.target_postfix = '_segmentation' self.target_fex = 'pn...
class VGNet(torch.nn.Module): def __init__(self): super(VGNet, self).__init__() self.node_encode = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3, 8, 3, stride=1)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(8, 5, 5, stride=2)), ('relu2', nn.ReLU()), ('flatten', nn.Flatten()), ('lin1', Lin(245, 128...
def sync_buffer(buffers, average=True): if (not is_distributed()): return handles = [] for buffer in buffers: if torch.is_floating_point(buffer.data): if average: handle = torch.distributed.all_reduce(buffer.data, op=torch.distributed.ReduceOp.SUM, async_op=True) ...
class Reader(): def __init__(self): pass def read(self, file, get_meta=False, autojoin_paragraphs=True, para_joiner='\n\n'): with open(file, 'rb') as fh: self.fh = fh cctx = zstandard.ZstdDecompressor() reader = io.BufferedReader(cctx.stream_reader(fh)) ...
def wait_for_token_network(raiden: 'RaidenService', token_network_registry_address: TokenNetworkRegistryAddress, token_address: TokenAddress, retry_timeout: float) -> None: token_network = views.get_token_network_by_token_address(views.state_from_raiden(raiden), token_network_registry_address, token_address) lo...
class resnet(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True, num=18): super(resnet, self).__init__() if (num == 18): self.net = tv.resnet18(pretrained=pretrained) elif (num == 34): self.net = tv.resnet34(pretrained=pretrained) elif (...
class TestOp(): def test_sanity_0(self): (r1, r2) = (MyType(1)(), MyType(2)()) node = MyOp.make_node(r1, r2) assert (list(node.inputs) == [r1, r2]) assert ([x.type for x in node.outputs] == [MyType(3)]) assert ((node.outputs[0].owner is node) and (node.outputs[0].index == 0))...
class ShapeBase(ABC): _rgba = (255, 255, 255, 255) _rotation = 0 _visible = True _x = 0 _y = 0 _anchor_x = 0 _anchor_y = 0 _batch = None _group = None _num_verts = 0 _vertex_list = None _draw_mode = GL_TRIANGLES group_class = _ShapeGroup def __del__(self): ...
def test_ubuntu_checker_no_release_update_available(fake_process): fake_process.register_subprocess(('do-release-upgrade', '-c'), returncode=1) fake_process.register_subprocess('/usr/lib/update-notifier/apt-check', stdout=('0;0',)) ret = os_updates.ubuntu_checker() assert (ret['release'] is False)
def rowbased_pearson(x, y): def ss(a, axis): return np.sum((a * a), axis=axis) x = np.asarray(x) y = np.asarray(y) mx = x.mean(axis=(- 1)) my = y.mean(axis=(- 1)) (xm, ym) = ((x - mx[(..., None)]), (y - my[(..., None)])) r_num = np.add.reduce((xm * ym), axis=(- 1)) r_den = np.sqr...
def test_mouse_move_event_when_no_action_reset_prev_transform(view, item): view.scene.addItem(item) view.reset_previous_transform = MagicMock() event = MagicMock() item.event_start = QtCore.QPointF(10, 10) event.scenePos.return_value = QtCore.QPointF(50, 40) with patch('PyQt6.QtWidgets.QGraphics...
_cache(maxsize=512) def progress(paths, total_progress=False): total = 0 translated = 0 previous = '/' is_root = True for path in paths: pofile = polib.pofile(path) total += (len(pofile) - len(pofile.obsolete_entries())) translated += len(pofile.translated_entries()) ...
def _data_arrays_from_params(shapes: list[tuple[(int, ...)]], chunks: list[tuple[(int, ...)]], dims: list[tuple[(int, ...)]]) -> typing.Generator[(xr.DataArray, None, None)]: for (shape, chunk, dim) in zip(shapes, chunks, dims): (yield xr.DataArray(da.ones(shape, chunks=chunk), dims=dim))
def countstat_current(L, c_ops=None, rhoss=None, J_ops=None): if (J_ops is None): if (c_ops is None): raise ValueError('c_ops must be given if J_ops is not') J_ops = [sprepost(c, c.dag()) for c in c_ops] if (rhoss is None): if (c_ops is None): raise ValueError('c_...
class RelativeGateEncoderLayer(nn.Module): def __init__(self, opt, **kwargs): super(RelativeGateEncoderLayer, self).__init__() self.variational = opt.variational_dropout self.depthwise_conv = opt.depthwise_conv self.mfw = opt.multilingual_factorized_weights self.mpw = opt.mul...
def eval_id_to_info(eval_id): repeat_id = '' if (('repeat' in eval_id) or ('incontextknn' in eval_id)): repeat_id = eval_id.split('-')[(- 1)] eval_id = '-'.join(eval_id.split('-')[:(- 1)]) (n, temp) = eval_id.split('-')[(- 2):] version = '-'.join(eval_id.split('-')[:(- 2)]) n = int(n...
def eval_having(pred, label): pred_total = label_total = cnt = 0 if (len(pred['groupBy']) > 0): pred_total = 1 if (len(label['groupBy']) > 0): label_total = 1 pred_cols = [unit[1] for unit in pred['groupBy']] label_cols = [unit[1] for unit in label['groupBy']] if ((pred_total == ...
def fashion_mnist(data_augmentation=True): train_loader = datasets.FashionMNIST(args.dataset_path, train=True, download=True) train_data = (train_loader.data.float() / 256).unsqueeze(1) train_targets = torch.LongTensor(train_loader.targets) if (args.dataset_size >= 0): data_per_class = [] ...
class _AsyncPropertyOverrideContext(contexts.AsyncContext): def __init__(self, target, property_name, value): self._target = target self._property_name = property_name self._value = value self._old_value = None def resume(self): self._old_value = getattr(self._target, sel...
class RopLopChecker(): def setup_method(self): self.x = vector('x') self.v = vector('v') self.rng = np.random.default_rng(utt.fetch_seed()) self.in_shape = ((5 + self.rng.integers(3)),) self.mx = matrix('mx') self.mv = matrix('mv') self.mat_in_shape = ((5 + se...
def get_conv_accum_bounds(weights: np.ndarray, quant_bw: int, accum_bw: int): max_int_value = ((2 ** quant_bw) - 1) max_accum_value = (2 ** (accum_bw - 1)) quant_min = min(np.min(weights), 0) quant_max = max(np.max(weights), 0) quant_scale = ((2 * max(abs(quant_min), abs(quant_max))) / max_int_value...
class CmdSdesc(RPCommand): key = 'sdesc' locks = 'cmd:all()' def func(self): caller = self.caller if (not self.args): caller.msg('Usage: sdesc <sdesc-text>') return else: sdesc = _RE_CHAREND.sub('', self.args) try: sdesc...
def test_commandresult_truthy(commandresult_app): arg = 'foo' run_cmd(commandresult_app, 'affirmative {}'.format(arg)) assert commandresult_app.last_result assert (commandresult_app.last_result == cmd2.CommandResult(arg, data=True)) run_cmd(commandresult_app, 'affirmative_no_data {}'.format(arg)) ...
class Effect2745(BaseEffect): attr = 'boosterCapacitorCapacityPenalty' displayName = 'Cap Capacity' type = 'boosterSideEffect' def handler(cls, fit, booster, context, projectionRange, **kwargs): fit.ship.boostItemAttr('capacitorCapacity', booster.getModifiedItemAttr(cls.attr), **kwargs)
def get_num_bits(dtype: torch.dtype) -> int: if (dtype == torch.bool): return 8 elif dtype.is_floating_point: return torch.finfo(dtype).bits else: try: return torch.iinfo(dtype).bits except TypeError: raise TypeError(f'Could not infer size for tensor t...
class EmptyMessage(Message): __slots__ = () type = b'' def __new__(typ): return typ.SingleInstance def serialize(self): return b'' def parse(typ, data): if (data != b''): raise ValueError(('empty message(%r) had data' % (typ.type,))) return typ.SingleInsta...
def test_context_block(): with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), pooling_type='unsupport_type') with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), fusion_types='unsupport_type') with pytest.raises(AssertionError): ContextBlock(16, (1.0 / 4), fusi...
class TrezorPlugin(HW_PluginBase): firmware_URL = ' libraries_URL = ' minimum_firmware = (1, 8, 1) keystore_class = TrezorKeyStore minimum_library = (0, 13, 0) maximum_library = (0, 14) SUPPORTED_XTYPES = ('standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2wsh') DEVICE_IDS = (TREZOR_P...
def main(): best_acc = 0 opt = parse_option() if (opt.dataset == 'cifar100'): (train_loader, val_loader) = get_cifar100_dataloaders(batch_size=opt.batch_size, num_workers=opt.num_workers) n_cls = 100 else: raise NotImplementedError(opt.dataset) model = model_dict[opt.model](n...
class BaseGoogleAuth(): def get_user_id(self, details, response): if self.setting('USE_UNIQUE_USER_ID', False): if ('sub' in response): return response['sub'] else: return response['id'] else: return details['email'] def get_use...
class Migration(migrations.Migration): dependencies = [('questions', '0070_alter_questionset_section')] operations = [migrations.AlterField(model_name='question', name='questionset', field=models.ForeignKey(blank=True, help_text='The question set this question belongs to.', null=True, on_delete=django.db.models...
class TestChatMemberUpdatedWithoutRequest(TestChatMemberUpdatedBase): def test_slot_behaviour(self, chat_member_updated): action = chat_member_updated for attr in action.__slots__: assert (getattr(action, attr, 'err') != 'err'), f"got extra slot '{attr}'" assert (len(mro_slots(ac...
class InteractionArchTransformerTest(unittest.TestCase): def test_basic(self) -> None: D = 8 B = 10 nhead = 8 ntransformer_layers = 4 keys = ['f1', 'f2'] F = len(keys) inter_arch = InteractionTransformerArch(num_sparse_features=F, embedding_dim=D, nhead=nhead,...
class RippleMachine(): def __init__(self, ripple_generation, ripple_generation_number, ripple_node_selection, ripple_node_selection_random_top_n, ripple_node_connection, ripple_node_ncross): self._ripple_generation = ripple_generation self._ripple_generation_number = ripple_generation_number ...
class MarginMSELoss(nn.Module): def __init__(self, model, scale: float=1.0, similarity_fct='dot'): super(MarginMSELoss, self).__init__() self.model = model self.scale = scale self.similarity_fct = similarity_fct self.loss_fct = nn.MSELoss() def forward(self, sentence_feat...
def convert_path(path: str) -> str: if (len(path) < 250): return path if _supports_long_paths(): return path prefix = '\\\\?\\' if path.startswith(prefix): return path path = _win_prepare_path(path) if (not path.startswith(prefix)): path = (prefix + path) retu...
def get_feature_importance(est_name, est, dim_red, num_features, fill_value=np.nan): feat_importance = np.full(num_features, fill_value) if hasattr(dim_red, 'get_support'): index_selected_features = dim_red.get_support(indices=True) if hasattr(est, cfg.importance_attr[est_name]): fea...
class DescribeCT_Default(): def it_provides_read_access_to_xml_values(self): default = a_Default().element assert (default.extension == 'xml') assert (default.content_type == 'application/xml') def it_can_construct_a_new_default_element(self): default = CT_Default.new('xml', 'app...
def get_test_mlp_task_config(): return {'name': 'classification_task', 'num_epochs': 10, 'loss': {'name': 'CrossEntropyLoss'}, 'dataset': {'train': {'name': 'synthetic_image', 'num_classes': 2, 'crop_size': 20, 'class_ratio': 0.5, 'num_samples': 20, 'seed': 0, 'batchsize_per_replica': 6, 'use_augmentation': False, ...
class AprilFoolVideos(commands.Cog): (name='fool') async def april_fools(self, ctx: commands.Context) -> None: video = random.choice(ALL_VIDS) (channel, url) = (video['channel'], video['url']) (await ctx.send(f'''Check out this April Fools' video by {channel}. {url}'''))
class Video2Vec(): def __init__(self, dataset='evve', model='resnet-50', layers=['layer1', 'layer2', 'layer3', 'layer4'], feat='imac', num_workers=4): self.model_name = model self.feat = feat (self.model, self.extraction_layers) = self._get_model_and_layers(model, layers) self.model ...
class MyLSTMForSequenceClassification(BertPreTrainedModel): def __init__(self, config, num_labels): super(MyLSTMForSequenceClassification, self).__init__(config) self.num_labels = num_labels self.my_word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) ...
def _load_options(): options.set_values('data', 'dataparser', 'dataexport', 'dataformat', 'variant', 'tocsp', 'checker', 'solver', 'output', 'suffix') options.set_flags('dataexport', 'solve', 'display', 'verbose', 'lzma', 'sober', 'ev', 'safe', 'recognizeSlides', 'keepHybrid', 'keepSmartTransitions', 'keepsum',...
class ModelWithBertCustomLayerNorm(nn.Module): def __init__(self): super(ModelWithBertCustomLayerNorm, self).__init__() self.linear1 = torch.nn.Linear(4, 4) self.customln1 = torch.nn.LayerNorm(4) self.gelu = torch.nn.GELU() def forward(self, x): x = self.linear1(x) ...
def remove_starting_underscore(data): if verbose: print(('#' * 10), 'Step - Remove starting underscore:') local_vocab = {} temp_vocab = _check_vocab(data, local_vocab, response='unknown_list') temp_vocab = [k for k in temp_vocab if (_check_replace(k) and ('_' in k))] temp_dict = {} for w...
def parsefile(fullpath): dsz.ui.Echo('Parsing file...') global fileDate fileDate = fullpath.split('GetFile')[(- 1)] parsethis(fullpath, '-tu -l -enus') parsethis(fullpath, '-tau -l -enus') try: yakshaver(('%s\\GetFiles\\Yak_Decrypted\\keylogger_scancodes_UNICODE_EN%s.txt' % (logdir, file...
def test_wheel_package() -> None: module_path = (fixtures_dir / 'complete') WheelBuilder.make(Factory().create_poetry(module_path)) whl = ((module_path / 'dist') / 'my_package-1.2.3-py3-none-any.whl') assert whl.exists() with zipfile.ZipFile(str(whl)) as z: assert ('my_package/sub_pkg1/__ini...
class TestOnError(): def test_closed(self, ipc_server): ipc_server._socket = QLocalSocket() ipc_server._timer.timeout.disconnect() ipc_server._timer.start() ipc_server.on_error(QLocalSocket.LocalSocketError.PeerClosedError) assert (not ipc_server._timer.isActive()) def te...
def catch_response(update, context): query = update.callback_query if (query.data == (pattern_to_save_everything + 'OK')): save_product_info_in_db(update, context) text = get_text('information_stored', context) else: text = get_text('canceled_operation', context) query.edit_messa...
class AQSOL(InMemoryDataset): url = ' def __init__(self, root, split='train', transform=None, pre_transform=None, pre_filter=None): self.name = 'AQSOL' assert (split in ['train', 'val', 'test']) super().__init__(root, transform, pre_transform, pre_filter) path = osp.join(self.pro...
class ColorFlags(): class CaretMode(enum.Enum): off = enum.auto() on = enum.auto() selection = enum.auto() prompt: bool = False insert: bool = False command: bool = False caret: CaretMode = CaretMode.off private: bool = False passthrough: bool = False def to_strin...
_shapely def test_geometry_length__multipolygon__radians(): geod = Geod(ellps='WGS84') polygon = Polygon(LineString([Point(math.radians(1), math.radians(2)), Point(math.radians(3), math.radians(4)), Point(math.radians(5), math.radians(2))])) assert_almost_equal(geod.geometry_length(MultiPolygon([polygon, po...
def hex_to_hash(hexstr, hash_size=8): l = [] count = (hash_size * (hash_size // 4)) if (len(hexstr) != count): emsg = 'Expected hex string size of {}.' raise ValueError(emsg.format(count)) for i in range((count // 2)): h = hexstr[(i * 2):((i * 2) + 2)] v = int(('0x' + h),...
class NVPModel(object): def __init__(self, controller, nvpmodel): self._controller = controller self._nvp_models = nvpmodel['models'] self._nvp_default = nvpmodel['default'] self._status = [] self._running = False self._nvpmodel_now = {} def _update(self, nvp_stat...
class LmdbBackend(BaseStorageBackend): def __init__(self, db_paths, client_keys='default', readonly=True, lock=False, readahead=False, **kwargs): try: import lmdb except ImportError: raise ImportError('Please install lmdb to enable LmdbBackend.') if isinstance(client_...
class GetVersion(rq.ReplyRequest): _request = rq.Struct(rq.Card8('opcode'), rq.Opcode(0), rq.RequestLength(), rq.Card16('major_version'), rq.Card16('minor_version')) _reply = rq.Struct(rq.Pad(2), rq.Card16('sequence_number'), rq.ReplyLength(), rq.Card16('major_version'), rq.Card16('minor_version'), rq.Pad(20))
def numpy_aware_eq(a, b): if (isinstance(a, np.ndarray) or isinstance(b, np.ndarray)): return np.array_equal(a, b) if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and (not isinstance(a, str)) and (not isinstance(b, str))): if (len(a) != len(b)): return False return ...
def normalized_qty2(sumall, proall, a): sqrtand = (((81 * (a ** 2)) * (sumall ** 2)) + ((48 * proall) * ((a - 1) ** 3))) q = ((((((- 2) * (6 ** (2 / 3))) * proall) * (a - 1)) + ((6 ** (1 / 3)) * ((proall * (((9 * a) * sumall) + sqrt(sqrtand))) ** (2 / 3)))) / (6 * ((proall * (((9 * a) * sumall) + sqrt(sqrtand))...
def get_args(): parser = argparse.ArgumentParser(description='training neural Datalog through time (NDTT) using MLE') parser.add_argument('-d', '--Domain', required=True, type=str, help='which domain to work on?') parser.add_argument('-fn', '--FolderName', required=True, type=str, help='base name of the fol...
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = None self.sum = 0 self.count = 0 def is_valid(self): return (self.count > 0) def update(self, val, n=1): if (val is not None): self.va...
def test_log_match_start(): events = telemetry.events_from_type('LogMatchStart') data = events[0] assert isinstance(data, LogMatchStart) assert isinstance(data.characters, list) assert isinstance(data.characters[0], Character) assert isinstance(data.blue_zone_custom_options, BlueZoneCustomOption...
def test_encoded_id(fake_manager): obj = helpers.FakeObject(fake_manager, {'foo': 'bar'}) obj.id = 42 assert (42 == obj.encoded_id) obj.id = None assert (obj.encoded_id is None) obj.id = 'plain' assert ('plain' == obj.encoded_id) obj.id = 'a/path' assert ('a%2Fpath' == obj.encoded_id...
(version='0.4.0', reason='You should use simulated annealing sampler of dwave-neal directly.') def solve_ising(linear, quad, num_reads=10, sweeps=1000, beta_range=(1.0, 50.0)): max_abs_value = float(max((abs(v) for v in (list(quad.values()) + list(linear.values()))))) scale_linear = {k: (float(v) / max_abs_valu...
class MultiValueHeadersTests(unittest.TestCase): def setUp(self): self.headers = Headers([('Server', 'Python'), ('Server', 'websockets')]) def test_init_from_headers(self): self.assertEqual(Headers(self.headers), self.headers) def test_init_from_headers_and_kwargs(self): self.assertE...
class ImageNet_truncated_hdf5(data.Dataset): def __init__(self, imagenet_dataset: ImageNet_hdf5, dataidxs, net_dataidx_map, train=True, transform=None, target_transform=None, download=False): self.dataidxs = dataidxs self.train = train self.download = download self.all_data_hdf5 = im...
def set_cycles(w=None, h=None, n_samples=None): scene = bpy.context.scene scene.render.engine = 'CYCLES' cycles = scene.cycles cycles.use_progressive_refine = True if (n_samples is not None): cycles.samples = n_samples cycles.max_bounces = 100 cycles.min_bounces = 10 cycles.caust...
def main(): parser = argparse.ArgumentParser(description='Create a swap file and enable on boot (require sudo)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--dir', dest='directory', help='Directory to place swapfile', type=str, default='') parser.add_argument('-n', '-...
class ArtLinkFromMarkerBetween(ArtLinkBetween): def __init__(self, marker_name, min_state, max_state, obj_offset_factor, sim, name_to_id, succ_thresh): real_marker_name = name_to_id[marker_name] link_idx = (sim.markers[real_marker_name]['relative'][1] - 1) self.marker_name = real_marker_name...
class ShellResourceCompute(cpi_resource.Compute): def __init__(self, api, adaptor): self._cpi_base = super(ShellResourceCompute, self) self._cpi_base.__init__(api, adaptor) self.state = c.ACTIVE self.rtype = None self.manager = None self.manager_url = None sel...
class TestOpDecorator(utt.InferShapeTester): def test_1arg(self): x = dmatrix('x') _op(dmatrix, dvector) def cumprod(x): return np.cumprod(x) fn = function([x], cumprod(x)) r = fn([[1.5, 5], [2, 2]]) r0 = np.array([1.5, 7.5, 15.0, 30.0]) assert np....
def crossover_ring(parent_A, parent_B, **mol_ok_kwargs): ring_smarts = Chem.MolFromSmarts('[R]') if ((not parent_A.HasSubstructMatch(ring_smarts)) and (not parent_B.HasSubstructMatch(ring_smarts))): return None rxn_smarts1 = ['[*:1]~[1*].[1*]~[*:2]>>[*:1]-[*:2]', '[*:1]~[1*].[1*]~[*:2]>>[*:1]=[*:2]'...
def plot_graph(graph, char_id=1, visible_ids=None, action_ids=None): nodes_interest = [node for node in graph['nodes'] if ('GRABBABLE' in node['properties'])] container_surf = (dict_info['objects_inside'] + dict_info['objects_surface']) container_and_surface = [node for node in graph['nodes'] if (node['clas...
class Migration(migrations.Migration): dependencies = [('schedule', '0011_auto__0115')] operations = [migrations.RemoveField(model_name='scheduleitem', name='end'), migrations.RemoveField(model_name='scheduleitem', name='start'), migrations.AddField(model_name='scheduleitem', name='duration', field=models.Posit...
def register_distill_coco_instances(name, metadata, json_file, image_root): assert isinstance(name, str), name assert isinstance(json_file, (str, os.PathLike)), json_file assert isinstance(image_root, (str, os.PathLike)), image_root DatasetCatalog.register(name, (lambda : load_coco_json(json_file, image...
def get_string_property(device_type, property): key = cf.CFStringCreateWithCString(kCFAllocatorDefault, property.encode('utf-8'), kCFStringEncodingUTF8) CFContainer = iokit.IORegistryEntryCreateCFProperty(device_type, key, kCFAllocatorDefault, 0) output = None if CFContainer: output = cf.CFStrin...
class RandomModel(Model): def __init__(self, seed: Optional[int]=None, **kwargs): self.rg = np.random.default_rng(seed) super().__init__(**kwargs) def provides(self): return {'means', 'vars'} def type_(self): return 'random' def train(self, *args, **kwargs): retur...
.skipif((not sys.platform.startswith('win')), reason='Looks for Python.exe') .parametrize('venv', [True, False]) def test_windows_python_with_version(monkeypatch, venv): def which(name): return 'py' major = sys.version_info.major minor = sys.version_info.minor monkeypatch.setattr(pipx.interprete...
class Dist2LogitLayer(nn.Module): def __init__(self, chn_mid=32, use_sigmoid=True): super(Dist2LogitLayer, self).__init__() layers = [nn.Conv2d(5, chn_mid, 1, stride=1, padding=0, bias=True)] layers += [nn.LeakyReLU(0.2, True)] layers += [nn.Conv2d(chn_mid, chn_mid, 1, stride=1, padd...
class BuildMan(Command): user_options = [] def run(self): cmd = 'sphinx-build -b man docs man' sphinx_proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE) (stdout, stderr) = sphinx_proc.communicate() return_code = sphinx_proc.wait() if return_code: print(('Warn...
class Cut(_CutBase): __slots__ = ('from_nodes', 'to_nodes', 'node_labels') def __init__(self, from_nodes, to_nodes, node_labels=None): self.from_nodes = from_nodes self.to_nodes = to_nodes self.node_labels = node_labels def indices(self): return tuple(sorted(set((self.from_no...
class MlpGeLUFunctionBLASLT(torch.autograd.Function): _fwd def forward(ctx, p, recompute, *args): outputs = mlp_gelu_blaslt.forward(p, args) ctx.save_for_backward(*args) ctx.recompute = recompute if recompute: ctx.outputs = (outputs[0], outputs[(- 1)]) else: ...
def _evp_cipher_decrypt(backend: Backend, cipher: _AEADTypes, nonce: bytes, data: bytes, associated_data: list[bytes], tag_length: int, ctx: typing.Any=None) -> bytes: from cryptography.hazmat.primitives.ciphers.aead import AESCCM if (len(data) < tag_length): raise InvalidTag tag = data[(- tag_lengt...
.parametrize('my_keys', [['q'], ['qdot'], ['qddot'], ['q', 'qdot'], ['qdot', 'q'], ['q', 'qdot', 'qddot'], ['qddot', 'q', 'qdot'], ['qdot', 'qddot', 'q'], ['q', 'qddot', 'qdot'], ['qddot', 'qdot', 'q'], ['qdot', 'q', 'qddot']]) def test_bounds_from_ranges(my_keys): from bioptim.examples.getting_started import pendu...