code
stringlengths
281
23.7M
def find_constraint_latent(model, x, y, w, relaxed=True): h = model.latent(x, y, w) h_hat = model.loss_augmented_inference(x, h, w, relaxed=relaxed) joint_feature = model.joint_feature delta_joint_feature = (joint_feature(x, h) - joint_feature(x, h_hat)) loss = model.loss(y, h_hat) slack = max((...
class TestUVCCVSCF(QiskitChemistryTestCase): def setUp(self): super().setUp() aqua_globals.random_seed = 8 self.reference_energy = 592. def test_uvcc_vscf(self): co2_2modes_2modals_2body = [[[[[0, 0, 0]], 320.], [[[0, 1, 1]], 1760.], [[[1, 0, 0]], 342.], [[[1, 1, 1]], 1032.]], [[...
class _CookieCacheManager(): _Cookie_cache = None def get_cookie_cache(cls): if (cls._Cookie_cache is None): with _cache_init_lock: cls._initialise() return cls._Cookie_cache def _initialise(cls, cache_dir=None): cls._Cookie_cache = _CookieCache()
def howAboutNow(): global delayTime, RUNTIME, READYTIME ticks = int(time.time()) if (ticks >= RUNTIME): return 'T_RUN' elif (ticks >= READYTIME): delayTime = (0.2 if ((RUNTIME - ticks) < 15) else 8) return 'T_READY' else: howlong = (RUNTIME - ticks) if (howlon...
def dice(gt, pred, label=None): (gt, pred) = to_numpy(gt, pred) if (label is None): (gt, pred) = (gt.astype(np.bool), pred.astype(np.bool)) else: (gt, pred) = ((gt == label), (pred == label)) intersection = np.logical_and(gt, pred) return ((2.0 * intersection.sum()) / (gt.sum() + pre...
class UniterEncoder(nn.Module): def __init__(self, args): super().__init__() self.max_seq_length = args.max_seq_length set_visual_config(args) self.tokenizer = BertTokenizer.from_pretrained('bert-base-cased', do_lower_case=True) self.model = UFE.from_pretrained('bert-base-cas...
class TabToolButton(QtWidgets.QToolButton): SIZE = (16, 16) def __init__(self, *args): QtWidgets.QToolButton.__init__(self, *args) self.setIconSize(QtCore.QSize(*self.SIZE)) self.setStyleSheet('QToolButton{ border: none; }') def mousePressEvent(self, event): event.ignore()
class StridedBottomUpStack(BottomUpStackInterface): def __init__(self, strided_block: StridedBlockInterface, layer_num_blocks: List[int], strided_reduction: bool) -> None: self._strided_block = strided_block self._layer_num_blocks = layer_num_blocks self._strided_reduction = strided_reductio...
def validate(model, dataloader, criterion): model.eval() device = model.device epoch_start = time.time() running_loss = 0.0 preds = [] golds = [] with torch.no_grad(): for batch in dataloader: premises = batch['premise'].to(device) premises_lengths = batch['pr...
def _load_libr_all(directory: Path): changed = True loaded = set() loaded_dlls = {} while changed: changed = False for p in directory.iterdir(): if (p in loaded): continue if (p.is_file() and p.name.endswith('dll')): try: ...
def test_cache_metadata(disk_cache): url = ' metadata = QNetworkCacheMetaData() metadata.setUrl(QUrl(url)) assert metadata.isValid() device = disk_cache.prepare(metadata) device.write(b'foobar') disk_cache.insert(device) assert (disk_cache.metaData(QUrl(url)) == metadata)
def test_routing_in_direct_channel(happy_path_fixture, our_signer, one_to_n_address): (addresses, chain_state, _, _, token_network_state) = happy_path_fixture (address1, _, _, _) = addresses pfs_proxy = PFSProxy(PFS_CONFIG) with patch('raiden.routing.get_best_routes_pfs') as pfs_route_request, patch.obj...
def plot_pie(AU_list, pos_freq, neg_freq): ploting_labels = ([(x + '+ {0:.2f}'.format(y)) for (x, y) in zip(AU_list, pos_freq)] + [(x + '- {0:.2f}'.format(y)) for (x, y) in zip(AU_list, neg_freq)]) cmap = matplotlib.cm.get_cmap('coolwarm') colors = ([cmap(x) for x in pos_freq] + [cmap(x) for x in neg_freq])...
def test_named_signals(): ct.iosys.InputOutputSystem._idCounter = 0 h1 = TransferFunction([1], [1, 2, 2]) h2 = TransferFunction([1], [0.1, 1]) omega = np.logspace((- 1), 2, 10) f1 = FRD(h1, omega) f2 = FRD(h2, omega) assert (f1.name == 'sys[2]') assert (f2.name == 'sys[3]') assert (f...
class unet_3D_ds(nn.Module): def __init__(self, feature_scale=4, n_classes=21, is_deconv=True, in_channels=3, is_batchnorm=True): super(unet_3D_ds, self).__init__() self.is_deconv = is_deconv self.in_channels = in_channels self.is_batchnorm = is_batchnorm self.feature_scale =...
class EMAModel(): def __init__(self, model, update_after_step=0, inv_gamma=1.0, power=(2 / 3), min_value=0.0, max_value=0.9999): self.averaged_model = model self.averaged_model.eval() self.averaged_model.requires_grad_(False) self.update_after_step = update_after_step self.in...
def pointer(encoded_ref, query, mask, W_ref, W_q, v, C=10.0, temperature=1.0): encoded_query = tf.expand_dims(tf.matmul(query, W_q), 1) scores = tf.reduce_sum((v * tf.tanh((encoded_ref + encoded_query))), [(- 1)]) scores = (C * tf.tanh((scores / temperature))) masked_scores = tf.clip_by_value((scores - ...
class QuantizableInceptionAux(InceptionAux): def __init__(self, *args, **kwargs): super(QuantizableInceptionAux, self).__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) self.relu = nn.ReLU() self.dropout = nn.Dropout(0.7) def forward(self, x): x = F.adaptive_avg_pool2d...
def test_spin_pairs_iter(): spinful_lattice = HubbardSquareLattice(3, 3) with pytest.raises(ValueError): spinful_lattice.spin_pairs_iter(10) assert (tuple(spinful_lattice.spin_pairs_iter(SpinPairs.ALL, True)) == ((0, 0), (0, 1), (1, 0), (1, 1))) assert (tuple(spinful_lattice.spin_pairs_iter(Spin...
class ScalarAnalysis(object): def __init__(self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block): self.scalar = scalar self.empty = empty self.multiline = multiline self.allow_flow_plain = allow_flow_plain ...
class PEPConverterTests(TestCase): def test_source_link(self): pep = get_pep_page(FAKE_PEP_REPO, '0525') self.assertEqual(pep.title, 'PEP 525 -- Asynchronous Generators') self.assertIn('Source: <a href=" pep.content.rendered) def test_source_link_rst(self): pep = get_pep_page(FAK...
def _create_threshold_tensor(threshold: Union[(int, List[float], torch.Tensor)], device: torch.device) -> torch.Tensor: if isinstance(threshold, int): threshold = torch.linspace(0, 1.0, threshold, device=device) elif isinstance(threshold, list): threshold = torch.tensor(threshold, device=device)...
def _add_property(ClassType, name): fget = (lambda self: self[name]) fset = (lambda self, value: self.set_attribute(name, value)) fdel = (lambda self: self.set_attribute(name, None)) fdoc = 'This is the %s attribute for object definition' setattr(ClassType, name, property(fget, fset, fdel, fdoc))
class Effect6301(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'Energy Nosferatu')), 'falloffEffectiveness', src.getModifiedItemAttr('shipBonusAC2'), skill='Amarr Cruiser', **kwargs) fit...
def get_timezone() -> Optional[timezone]: ctx = _get_current_context() tzinfo = getattr(ctx, 'babel_tzinfo', None) if (tzinfo is None): babel = get_babel() if (babel.timezone_selector is None): tzinfo = babel.instance.default_timezone else: rv = babel.timezone...
class FaceFilter(): def __init__(self, reference_file_paths, nreference_file_paths, detector, aligner, loglevel, multiprocess=False, threshold=0.4): logger.debug('Initializing %s: (reference_file_paths: %s, nreference_file_paths: %s, detector: %s, aligner: %s. loglevel: %s, multiprocess: %s, threshold: %s)'...
class Distribution(torch.Tensor): def init_distribution(self, dist_type, **kwargs): self.dist_type = dist_type self.dist_kwargs = kwargs if (self.dist_type == 'normal'): (self.mean, self.var) = (kwargs['mean'], kwargs['var']) elif (self.dist_type == 'categorical'): ...
def render_pep8_errors_e224_and_e273(msg, _node, source_lines): line = msg.line res = re.search('column (\\d+)', msg.msg) col = int(res.group().split()[(- 1)]) curr_idx = ((col + len(source_lines[(line - 1)][col:])) - len(source_lines[(line - 1)][col:].lstrip('\t'))) (yield from render_context((line...
def cmd_compile(options): from .compile import parse_config, BenchmarkRevision conf = parse_config(options.config_file, 'compile') if (options is not None): if options.no_update: conf.update = False if options.no_tune: conf.system_tune = False bench = BenchmarkRev...
class StatusAction(Action): def __call__(self, twitter, options): statuses = self.getStatuses(twitter, options) sf = get_formatter('status', options) for status in statuses: statusStr = sf(status, options) if statusStr.strip(): printNicely(statusStr)
class DirectedAcyclicGraph(): def __init__(self, exposure, outcome): self.exposure = exposure self.outcome = outcome dag = nx.DiGraph() dag.add_edge(self.exposure, self.outcome) self.dag = dag self.adjustment_sets = None self.minimal_adjustment_sets = None ...
def quantization_aware_training_range_learning(): tf.reset_default_graph() parser2 = tf_gen.MnistParser(batch_size=100, data_inputs=['reshape_input']) generator = tf_gen.TfRecordGenerator(tfrecords=[os.path.join('data', 'mnist', 'validation.tfrecords')], parser=parser2) sess = graph_saver.load_model_fro...
class AoAModel3_no_p(AttModel): def __init__(self, opt): super(AoAModel3_no_p, self).__init__(opt) self.num_layers = 2 self.use_mean_feats = getattr(opt, 'mean_feats', 1) if (opt.use_multi_head == 2): del self.ctx2att self.ctx2att = nn.Linear(opt.rnn_size, ((2...
.parametrize('command_and_args, text, is_error', [('hint --flag foo --', '', False), ('hint --flag foo --help', '', False), ('hint --flag foo', '--', False), ('nargs --one_or_more one --', '', False), ('nargs --one_or_more one or --set_value', '', False), ('nargs --one_or_more one or more', '--', False), ('nargs --set_...
class ButtonList(): def __init__(self, stdscr, on_click, buttons=[], info={}): self.buttons = [] self.on_click = on_click self.stdscr = stdscr self.info = info self._selected = '' for button in buttons: self.add_button(button) def add_button(self, labe...
def add_command_line_args_to_variant_spec(variant_spec, command_line_args): variant_spec['run_params'].update({'checkpoint_frequency': (command_line_args.checkpoint_frequency if (command_line_args.checkpoint_frequency is not None) else variant_spec['run_params'].get('checkpoint_frequency', 0)), 'checkpoint_at_end':...
def partition_into_regions(vcf_path: PathType, *, index_path: Optional[PathType]=None, num_parts: Optional[int]=None, target_part_size: Union[(None, int, str)]=None, storage_options: Optional[Dict[(str, str)]]=None) -> Optional[Sequence[str]]: if ((num_parts is None) and (target_part_size is None)): raise V...
_ASSIGNERS.register_module() class LaneHungarianAssigner(HungarianAssigner): def assign(self, lane_pred, cls_pred, gt_lanes, gt_labels, img_meta, gt_lanes_ignore=None, eps=1e-07): assert (gt_lanes_ignore is None), 'Only case when gt_lanes_ignore is None is supported.' (num_gts, num_lanes) = (gt_lane...
class EntityTrigger(_TriggerType): def __init__(self, name, delay, conditionedge, entitycondition, triggerentity, triggeringrule=TriggeringEntitiesRule.any, triggeringpoint='start'): self.name = name if (triggeringpoint not in ['start', 'stop']): raise ValueError('not a valid triggering ...
class ToggleTheme(Mutation): theme = String() _required def mutate(_root, info): user = info.context.user if (user.theme == Author.Theme.DARK): user.theme = Author.Theme.LIGHT user.save(update_fields=['theme']) return ToggleTheme(user.theme) user.t...
class LogReader(object): def __init__(self, path): self.path = path with open(self.path, 'r') as f: self.doc = f.read() def isfloat(self, str): try: float(str) return True except ValueError: return False def casttype(self, str):...
class MBConvBlock(nn.Module): def __init__(self, ksize, input_filters, output_filters, expand_ratio=1, stride=1, image_size=224): super().__init__() self._bn_mom = 0.1 self._bn_eps = 0.01 self._se_ratio = 0.25 self._input_filters = input_filters self._output_filters =...
def _resolve_transformers_model(model_family): di = {'mbart50': transformers.MBartForConditionalGeneration, 'm2m100': transformers.M2M100ForConditionalGeneration, 'nllb200': transformers.AutoModelForSeq2SeqLM} if (model_family in di): return di[model_family] else: error_msg = f'{model_family...
def verify_model_dtype(model): dtype2param_num = defaultdict(int) dtype2param_name = defaultdict(list) dtype2trainable_param_num = defaultdict(int) dtype2trainable_param_name = defaultdict(list) for (name, p) in model.named_parameters(): dtype = p.dtype dtype2param_num[dtype] += p.nu...
.parametrize('manager', [BareConfig, ManagerConfig], indirect=True) def test_setgroup(manager): manager.test_window('one') manager.c.group['b'].toscreen() manager.groupconsistency() if (len(manager.c.get_screens()) == 1): assert (manager.c.get_groups()['a']['screen'] is None) else: a...
def cmdparser(raw_string, cmdset, caller, match_index=None): if (not raw_string): return [] matches = build_matches(raw_string, cmdset, include_prefixes=True) if (not matches): (mindex, new_raw_string) = try_num_prefixes(raw_string) if (mindex is not None): return cmdpars...
class F9_RaidData(F7_RaidData): removedKeywords = (F7_RaidData.removedKeywords + ['bytesPerInode']) removedAttrs = (F7_RaidData.removedAttrs + ['bytesPerInode']) def __init__(self, *args, **kwargs): F7_RaidData.__init__(self, *args, **kwargs) self.deleteRemovedAttrs() self.fsprofile ...
_element(invalid_data_behavior={'warn', 'raise', 'ignore'}) def winsorise_uint32(df, invalid_data_behavior, column, *columns): columns = list(((column,) + columns)) mask = (df[columns] > UINT32_MAX) if (invalid_data_behavior != 'ignore'): mask |= df[columns].isnull() else: df[columns] = ...
def test_create_spawn_point_field(echoes_game_description, echoes_pickup_database, empty_patches): resource_db = echoes_game_description.resource_database morph = pickup_creator.create_standard_pickup(echoes_pickup_database.get_pickup_with_name('Morph Ball'), StandardPickupState(), resource_db, None, False) ...
def test_kw_only_decorator() -> None: (foodef, bardef, cee, dee) = astroid.extract_node('\n from dataclasses import dataclass\n\n (kw_only=True)\n class Foo:\n a: int\n e: str\n\n\n (kw_only=False)\n class Bar(Foo):\n c: int\n\n\n (kw_only=False)\n class Cee(Bar):\n ...
def ground_union(head_grounding, sql_unit, i_op, qdmr, sql_spider_data, table_data, grounding_out): assert (qdmr.ops[i_op] == 'union') args = qdmr.args[i_op] if (len(head_grounding) == len(args)): for (grnd, arg) in zip(head_grounding, args): i_op_arg = QdmrInstance.ref_to_index(arg, max...
class DevDataset(Dataset): def __init__(self, args, raw_datasets, cache_root): self.raw_datasets = raw_datasets cache_path = os.path.join(cache_root, 'grailqa_dev.cache') if (os.path.exists(cache_path) and args.dataset.use_cache): self.extended_data = torch.load(cache_path) ...
_fixtures(GitFixture) def test_is_version_controlled(git_fixture): fixture = git_fixture non_initialised_directory = fixture.new_git_directory(initialised=False) git = Git(non_initialised_directory.name) assert (not git.is_version_controlled()) git = Git(fixture.git_directory.name) assert git.is...
def fix_jukebox_keys(state_dict, model_state_dict, key_prefix, mapping): new_dict = {} import re re_encoder_block_conv_in = re.compile('encoders.(\\d*).level_blocks.(\\d*).model.(\\d*).(\\d).(bias|weight)') re_encoder_block_resnet = re.compile('encoders.(\\d*).level_blocks.(\\d*).model.(\\d*).(\\d).mode...
def insert_cylinder(arr, cyl_radius=4, cyl_height=2, cyl_centre=(0, 0, 0)): arr_copy = arr[:] (x, y, z) = np.indices(arr.shape) if (not hasattr(cyl_radius, '__iter__')): cyl_radius = ([cyl_radius] * 2) condition_radial = (((((z - cyl_centre[0]) / cyl_radius[0]) ** 2) + (((y - cyl_centre[1]) / cy...
def _get_dataclass_attributes(node: nodes.ClassDef, init: bool=False) -> Iterator[nodes.AnnAssign]: for assign_node in node.body: if ((not isinstance(assign_node, nodes.AnnAssign)) or (not isinstance(assign_node.target, nodes.AssignName))): continue if _is_class_var(assign_node.annotatio...
_2_unicode_compatible class ConferenceModerator(AuditModel): conference = models.ForeignKey(Conference, related_name='moderators', on_delete=models.CASCADE) moderator = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True, verbose_name='Is Active?') class Meta(): ...
class MCSls(object): def __init__(self, formula, use_cld=False, solver_name='m22', use_timer=False): self.oracle = Solver(name=solver_name, bootstrap_with=formula.hard, use_timer=use_timer) self.solver = solver_name if (isinstance(formula, WCNFPlus) and formula.atms): assert self...
def order_and_id_of_texts(found_polygons_text_region, found_polygons_text_region_h, matrix_of_orders, indexes_sorted, index_of_types, kind_of_texts, ref_point): indexes_sorted = np.array(indexes_sorted) index_of_types = np.array(index_of_types) kind_of_texts = np.array(kind_of_texts) id_of_texts = [] ...
def iload_stationxml(sx, segment, content): inut = 0 far_future = (time.time() + (20 * Y)) from pyrocko.io import stationxml value_or_none = stationxml.value_or_none for network in sx.network_list: for station in network.station_list: net = network.code sta = station....
class BasicLayer(nn.Module): def __init__(self, dim, out_dim, input_resolution, depth, num_heads, window_size, mlp_ratio=4.0, qkv_bias=True, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, norm_layer=nn.LayerNorm, downsample=None): super().__init__() self.dim = dim self.input_resoluti...
class RTStructBuilder(): def create_new(dicom_series_path: str) -> RTStruct: series_data = image_helper.load_sorted_image_series(dicom_series_path) ds = ds_helper.create_rtstruct_dataset(series_data) return RTStruct(series_data, ds) def create_from(dicom_series_path: str, rt_struct_path:...
class HARSave(BaseHandler): env = Fetcher().jinja_env def get_variables(env, tpl): variables = set() extracted = set(utils.jinja_globals.keys()) loop_extracted = set(('loop_index0', 'loop_index', 'loop_first', 'loop_last', 'loop_length', 'loop_revindex0', 'loop_revindex', 'loop_depth', '...
def main(): parser = argparse.ArgumentParser(description='Process Markdown according to the CommonMark specification.') if (sys.version_info < (3, 0)): reload(sys) sys.setdefaultencoding('utf-8') parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='I...
def update_hints_text(game: RandovaniaGame, hint_item_names_tree_widget: QtWidgets.QTableWidget): pickup_database = default_database.pickup_database_for_game(game) rows = [] for item in pickup_database.standard_pickups.values(): rows.append((item.name, item.pickup_category.hint_details[1], item.pick...
def test_imbalance_penalty_with_barely_sufficient_balance(): imbalance_penalty = calculate_imbalance_fees(channel_capacity=TokenAmount(20), proportional_imbalance_fee=ProportionalFeeAmount(1)) (pair, _) = _foward_transfer_pair(TokenAmount(10), NettingChannelStateProperties(our_state=NettingChannelEndStateProper...
def to_starred_table_for_no_overlap2(x1, x2, y1, y2, w1, w2, h1, h2): t = [] _non_overlapping_tuples_for(t, x1.dom, x2.dom, w1, True, True) _non_overlapping_tuples_for(t, x2.dom, x1.dom, w2, False, True) _non_overlapping_tuples_for(t, y1.dom, y2.dom, h1, True, False) _non_overlapping_tuples_for(t, y...
class AmmoPickerContents(wx.ScrolledCanvas): indent = 15 def __init__(self, parent, fit): wx.ScrolledCanvas.__init__(self, parent) self.SetScrollRate(0, 15) mods = self.getMods(fit) drones = self.getDrones(fit) fighters = self.getFighters(fit) self.rbLabelMap = {}...
def trashicra_to_detectwaste(label): metals_and_plastics = ['plastic', 'metal', 'rubber'] non_recyclable = ['cloth', 'paper'] bio = ['wood'] unknown = ['unknown'] if (label in metals_and_plastics): label = 'metals_and_plastics' elif (label in non_recyclable): label = 'non-recycla...
class ResNetBasicblock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, last_relu=True): super(ResNetBasicblock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=...
('/repository/<repopath:repository>/status', methods=['GET']) _repository_name() _protect def build_status_badge(namespace_name, repo_name): token = request.args.get('token', None) repo = model.repository.get_repository(namespace_name, repo_name) if (repo and (repo.kind.name != 'image')): abort(404)...
def match_graph(loc_dict, max_loc, max_obj_perloc): num_locations = len(loc_dict) chosen_locs = np.random.choice(range(num_locations), min(max_loc, num_locations), replace=False) new_loc_dict = {} count = 0 for (l, attr) in loc_dict.items(): cur_index = attr['index'] obj_list = attr[...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10, drop=False): super(ResNet, self).__init__() self.drop = drop self.in_planes = 64 self.conv1 = conv3x3(3, 64) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_bloc...
class DPRQuestionEncoderTokenizerFast(BertTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = QUESTION_ENCODER_PRETRA...
class Migration(migrations.Migration): dependencies = [('sponsors', '0071_auto__1843')] operations = [migrations.AddField(model_name='requiredtextasset', name='max_length', field=models.IntegerField(blank=True, default=None, help_text='Limit to length of the input, empty means unlimited', null=True)), migration...
class KombuThriftSerializer(KombuSerializer[T]): def __init__(self, thrift_class: Type[T], protocol_factory: TProtocolFactory=TBinaryProtocolAcceleratedFactory()): self.thrift_class = thrift_class self.factory = protocol_factory def name(self) -> str: return f'thrift-{self.thrift_class._...
def process(data): (candidates, references, pool_id) = data cnt = len(candidates) current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) tmp_dir = 'rouge-tmp-{}-{}'.format(current_time, pool_id) if (not os.path.isdir(tmp_dir)): os.mkdir(tmp_dir) os.mkdir((tmp_dir + '/can...
def deprecated(value: object, module_name: str, message: str, warning_class: type[Warning], name: (str | None)=None) -> _DeprecatedValue: module = sys.modules[module_name] if (not isinstance(module, _ModuleWithDeprecations)): sys.modules[module_name] = module = _ModuleWithDeprecations(module) dv = _...
def validate_branch_ops(conn_graph: ConnectedGraph): def check_for_branch_op(op_info: ModuleIdentifierOpInfo): op = conn_graph.get_all_ops()[op_info.module_name] return_bool = True product = op.output if ('branch' not in product.name): logger.error('branch not in product ...
def timebase(sys, strict=True): if isinstance(sys, (int, float, complex, np.number)): return None elif (not isinstance(sys, InputOutputSystem)): raise ValueError('Timebase not defined') if (sys.dt == None): return None elif strict: return float(sys.dt) return sys.dt
def start_all_dummy_clients(nclients): global NCLIENTS NCLIENTS = int(nclients) actions = DUMMYRUNNER_SETTINGS.ACTIONS if (len(actions) < 2): print(ERROR_FEW_ACTIONS) return pratio = (1.0 / sum((tup[0] for tup in actions[2:]))) (flogin, flogout, probs, cfuncs) = (actions[0], acti...
class ReplaceDataset(BaseWrapperDataset): def __init__(self, dataset, replace_map, offsets): super().__init__(dataset) assert (len(replace_map) > 0) self.replace_map = replace_map self.offsets = offsets def __getitem__(self, index): item = self.dataset[index] is_t...
class HP6634A(HP6632A): def __init__(self, adapter, name='Hewlett Packard HP6634A', **kwargs): super().__init__(adapter, name, **kwargs) current_values = [0, limits['HP6634A']['Cur_lim']] OVP_values = [0, limits['HP6634A']['OVP_lim']] voltage_values = [0, limits['HP6634A']['Volt_lim']]
def convert(framework: str, model: str, output: Path, opset: int, tokenizer: Optional[str]=None, use_external_format: bool=False, pipeline_name: str='feature-extraction', **model_kwargs): warnings.warn('The `transformers.convert_graph_to_onnx` package is deprecated and will be removed in version 5 of Transformers',...
def annotation_difference(first, second): union = set(first).union(set(second)) first_not_second = union.difference(set(second)) second_not_first = union.difference(set(first)) total = (len(first_not_second) + len(second_not_first)) return (first_not_second, second_not_first, total)
def pytorch2onnx(model, input_shape, opset_version=11, show=False, output_file='tmp.onnx', verify=False): model.cpu().eval() one_img = torch.randn(input_shape) register_extra_symbolics(opset_version) torch.onnx.export(model, one_img, output_file, export_params=True, keep_initializers_as_inputs=True, ver...
def test(): cmd = argparse.ArgumentParser('The testing components of') cmd.add_argument('--gpu', default=(- 1), type=int, help='use id of gpu, -1 if cpu.') cmd.add_argument('--input', help='the path to the raw text file.') cmd.add_argument('--model', required=True, help='path to save model') cmd.add...
.xfail def test_tell_in_random_order(first_add_33=False): import random from operator import attrgetter tol = 1e-10 for (f, a, b) in ([f0, 0, 3], [f21, 0, 1], [f24, 0, 3], [f7, 0, 1]): learners = [] for shuffle in [True, False]: learner = IntegratorLearner(f, bounds=(a, b), t...
def get_ghz_simple(n: int, measure: bool=True, full_measurement: bool=True) -> QuantumCircuit: q = QuantumRegister(n, 'q') circ = QuantumCircuit(q) circ.h(q[0]) for i in range(1, n): circ.cx(q[(i - 1)], q[i]) if measure: meas = get_measurement_circ(n, 'q', 'c', full_measurement) ...
class MultilingualLinear(torch.nn.Module): def __init__(self, input_size, output_size, n_factors=1, rank=1, use_multiplicative=False, weight_drop=0.0, mfw_activation='none', no_bias=False): super().__init__() self.use_multiplicative = use_multiplicative self.weight_drop = weight_drop ...
class TaskPool(TaskPoolBase): def __init__(self, process_func: callable, max_batch_size: int, name: str, min_batch_size=1, timeout=None, pool_size=None, prefetch_batches=1, daemon=True, start=False): super().__init__(process_func, daemon=daemon, name=name) (self.min_batch_size, self.max_batch_size, ...
def sample_function(user_train, usernum, itemnum, batch_size, maxlen, threshold_user, threshold_item, result_queue, SEED): def sample(): user = np.random.randint(1, (usernum + 1)) while (len(user_train[user]) <= 1): user = np.random.randint(1, (usernum + 1)) seq = np.zeros([maxle...
class NvidiaGPUCollector(diamond.collector.ProcessCollector): def get_default_config_help(self): config_help = super(NvidiaGPUCollector, self).get_default_config_help() config_help.update({'bin': 'The path to the nvidia-smi binary', 'stats': 'A list of Nvidia GPU stats to collect. Use `nvidia-smi --...
class CpmTokenizerFast(XLNetTokenizerFast): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: import jieba except ModuleNotFoundError as error: raise error.__class__('You need to install jieba to use CpmTokenizer or CpmTokenizerFast. See for...
class CustomCircuitOracle(Oracle): def __init__(self, variable_register: QuantumRegister, output_register: QuantumRegister, circuit: QuantumCircuit, ancillary_register: Optional[QuantumRegister]=None, evaluate_classically_callback: Optional[Callable[([str], Tuple[(bool, List[int])])]]=None): super().__init_...
def convert(src, dst): state_dict = OrderedDict() src_dict = torch.load(src) src_state_dict = src_dict.get('state_dict', src_dict) for (k, v) in src_state_dict.items(): if (not k.startswith('backbone')): continue b_k = k.replace('backbone.', '') b_k_splits = b_k.split...
class GatedConv(nn.Module): def __init__(self, input_size, width=3, dropout=0.2, nopad=False): super(GatedConv, self).__init__() self.conv = onmt.modules.WeightNormConv2d(input_size, (2 * input_size), kernel_size=(width, 1), stride=(1, 1), padding=(((width // 2) * (1 - nopad)), 0)) init.xavi...
def _applyActionSide1(state, act): (me, them, extra) = state if (act == 'Super Potion'): me = applyHPChange(me, 50) return {(me, them, extra): Fraction(1)} mdata = attack_data[act] aind = (3 if mdata.isspec else 0) dind = (3 if mdata.isspec else 1) pdiv = (64 if mdata.crit else 5...
def exceptions2exit(exception_list): def exceptions2exit_decorator(func): (func) def func_wrapper(*args, **kwargs): try: func(*args, **kwargs) except tuple(exception_list) as ex: from .cli import get_log_level if (get_log_level(...
def _validate_jwk(jwk): if ('kty' not in jwk): abort(400) if (jwk['kty'] == 'EC'): if (('x' not in jwk) or ('y' not in jwk)): abort(400) elif (jwk['kty'] == 'RSA'): if (('e' not in jwk) or ('n' not in jwk)): abort(400) else: abort(400)