code
stringlengths
281
23.7M
def update_hint_locations(game: RandovaniaGame, hint_tree_widget: QtWidgets.QTreeWidget): game_description = default_database.game_description_for(game) used_hint_kind = set() hint_tree_widget.clear() hint_tree_widget.setSortingEnabled(False) hint_type_tree = collections.defaultdict(dict) for re...
def preprocess_input(tokenizer, sentences): inputs = [] MAX_LEN = 64 for sentence in sentences: encoded_sent = tokenizer.encode(sentence, add_special_tokens=True) if (len(encoded_sent) < MAX_LEN): encoded_sent.extend(([0] * (MAX_LEN - len(encoded_sent)))) if (len(encoded_...
def timeout(seconds=10): def decorator(func): (func) def wrapper(*args, **kwargs): def handle_timeout(signum, frame): raise Exception() signal(SIGALRM, handle_timeout) alarm(seconds) result = None try: result...
def start_global_server( (int | None)=None, urls: list[str]=['.'], server: type[ServerType]=BottleServer, **server_args: Unpack[ServerArgs]) -> tuple[(str, (str | None), BottleServer)]: global global_server (address, common_path, global_server) = start_server(urls=urls, server=server, **server_args) return...
.mosaiqdb def test_get_patient_fields(connection: pymedphys.mosaiq.Connection): mock_patient_ident_df = mocks.create_mock_patients() mock_site_df = mocks.create_mock_treatment_sites(mock_patient_ident_df) mocks.create_mock_treatment_fields(mock_site_df) fields_for_moe_df = helpers.get_patient_fields(con...
def resolve_remote(uri, handlers): scheme = urlparse.urlsplit(uri).scheme if (scheme in handlers): result = handlers[scheme](uri) else: from urllib.request import urlopen req = urlopen(uri) encoding = (req.info().get_content_charset() or 'utf-8') try: resu...
_families def test_logging_passing_tests_disabled_does_not_log_test_output(pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str) -> None: pytester.makeini('\n [pytest]\n junit_log_passing_tests=False\n junit_logging=system-out\n junit_family={family}\n '.format(family=xun...
class TransactWrite(Transaction): def __init__(self, client_request_token: Optional[str]=None, return_item_collection_metrics: Optional[str]=None, **kwargs: Any) -> None: super(TransactWrite, self).__init__(**kwargs) self._client_request_token: Optional[str] = client_request_token self._retu...
class ConflictCause(IncompatibilityCause): def __init__(self, conflict: Incompatibility, other: Incompatibility) -> None: self._conflict = conflict self._other = other def conflict(self) -> Incompatibility: return self._conflict def other(self) -> Incompatibility: return self...
_criterion('winogrande') class WinograndeCriterion(WSCCriterion): def forward(self, model, sample, reduce=True): query_lprobs = self.get_lprobs(model, sample['query_tokens'], sample['query_masks']) cand_lprobs = self.get_lprobs(model, sample['candidate_tokens'], sample['candidate_masks']) pr...
class ModelFormTagFieldRequiredTest(TagTestManager, TestCase): manage_models = [test_models.TagFieldRequiredModel] def setUpExtra(self): self.form = test_forms.TagFieldRequiredModelForm self.model = test_models.TagFieldRequiredModel self.tag_model = self.model.tag.tag_model def test_...
def test_get_conference_roles_for_user(conference_factory, requests_mock): conference = conference_factory() requests_mock.get(f'{settings.PRETIX_API}organizers/base-pretix-organizer-id/events/base-pretix-event-id/vouchers', status_code=200, json={'next': None, 'results': []}) requests_mock.get(f'{settings....
def download_huggingface_tokenizers(): huggingface_dir = './data/huggingface' if (not os.path.isdir(huggingface_dir)): os.makedirs(huggingface_dir, exist_ok=True) tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') tokenizer.save_pretrained('{}/bert-base-uncased'.format(huggin...
def get_video_dataset_dicts(dataset_names, gen_inst_id=False): assert len(dataset_names) dataset_dicts = [DatasetCatalog.get(dataset_name) for dataset_name in dataset_names] for (dataset_name, dicts) in zip(dataset_names, dataset_dicts): assert len(dicts), "Dataset '{}' is empty!".format(dataset_nam...
class TestTimePoolHead(nn.Module): def __init__(self, base, original_pool=7): super(TestTimePoolHead, self).__init__() self.base = base self.original_pool = original_pool base_fc = self.base.get_classifier() if isinstance(base_fc, nn.Conv2d): self.fc = base_fc ...
class WarmupConstantSchedule(LambdaLR): def __init__(self, optimizer, warmup_steps, last_epoch=(- 1)): self.warmup_steps = warmup_steps super(WarmupConstantSchedule, self).__init__(optimizer, self.lr_lambda, last_epoch=last_epoch) def lr_lambda(self, step): if (step < self.warmup_steps):...
class ConferenceModeratorAdmin(AuditAdmin): list_display = (('conference', 'moderator', 'active') + AuditAdmin.list_display) list_filter = ('conference',) def get_queryset(self, request): qs = super(ConferenceModeratorAdmin, self).get_queryset(request) if request.user.is_superuser: ...
class PlanSelector(discord.ui.Select): def __init__(self, plans: List[PremiumPlan]): super().__init__(placeholder='Select a Quotient Premium Plan... ') for _ in plans: self.add_option(label=f'{_.name} - {_.price}', description=_.description, value=_.id) async def callback(self, inter...
def run_params(args): params = deepcopy(vars(args)) params['model'] = 'MLP_SIG' params['optimizer'] = 'Adam' if (args.data_cache_path != 'None'): pathlib.Path(args.data_cache_path).mkdir(parents=True, exist_ok=True) if (args.mode == 'pretrain'): if (args.method == 'Pretrain'): ...
def test_registry(): registry = Registry() assert ('DIFF' not in registry) assert (len(registry) == 0) ('DIFF') def difference(a, b): return (a - b) assert ('DIFF' in registry) assert (len(registry) == 1) assert (registry['DIFF'] == difference) with pytest.raises(KeyError): ...
def test_field_renaming(converter: Converter): class A(): a: int class B(): a: int converter.register_structure_hook(B, make_dict_structure_fn(B, converter, a=override(rename='b'))) assert (converter.structure({'a': 1}, Union[(A, B)]) == A(1)) assert (converter.structure({'b': 1}, Un...
class TestTradingControls(zf.WithMakeAlgo, zf.ZiplineTestCase): START_DATE = pd.Timestamp('2006-01-03', tz='utc') END_DATE = pd.Timestamp('2006-01-06', tz='utc') sid = 133 sids = ASSET_FINDER_EQUITY_SIDS = (133, 134) SIM_PARAMS_DATA_FREQUENCY = 'daily' DATA_PORTAL_USE_MINUTE_DATA = True def ...
def is2_use(use): def factory(): from qiime2.core.testing.format import IntSequenceFormatV2 from qiime2.plugin.util import transform ff = transform([1, 2, 3], to_type=IntSequenceFormatV2) ff.validate() return ff to_import = use.init_format('to_import', factory, ext='.hell...
def process_dis_batch_recur(input_filename_list, dim_input, num, reshape_with_one=False): img_list = [] random.seed(6) random.shuffle(input_filename_list) for filepath in input_filename_list: filepath2 = (FLAGS.data_path + filepath) this_img = scm.imread(filepath2) this_img = np....
def test_scene_to_pixmap_exporter_export_with_worker(view, tmpdir): filename = os.path.join(tmpdir, 'foo.png') item_img = QtGui.QImage(1000, 1200, QtGui.QImage.Format.Format_RGB32) item = BeePixmapItem(item_img) view.scene.addItem(item) exporter = SceneToPixmapExporter(view.scene) exporter.size ...
def assert_reversible_orbit(inst, iterations): n_time = [] p_time = [] control = inst.copy() for j in range(iterations): n_time.append(inst.index[0]) inst.orbits.next() for j in range(iterations): inst.orbits.prev() p_time.append(inst.index[0]) assert all((control...
class MapsGrid(): def __init__(self, r=2, c=2, crs=None, m_inits=None, ax_inits=None, figsize=None, layer='base', f=None, **kwargs): self._Maps = [] self._names = dict() if (WebMapContainer is not None): self._wms_container = WebMapContainer(self) gskwargs = dict(bottom=0...
class _ADTSStream(object): parsed_frames = 0 offset = 0 def find_stream(cls, fileobj, max_bytes): r = BitReader(fileobj) stream = cls(r) if stream.sync(max_bytes): stream.offset = ((r.get_position() - 12) // 8) return stream def sync(self, max_bytes): ...
class RegisterFileRst(Component): def construct(s, Type, nregs=32, rd_ports=1, wr_ports=1, const_zero=False, reset_value=0): addr_type = mk_bits(max(1, clog2(nregs))) s.raddr = [InPort(addr_type) for i in range(rd_ports)] s.rdata = [OutPort(Type) for i in range(rd_ports)] s.waddr = [...
def get_type_desktop(): cmd_status_gui = Command(shlex.split('systemctl get-default')) status = 0 try: status_gui = cmd_status_gui()[0] if (status_gui == 'multi-user.target'): status = 1 if os.path.isfile('/etc/systemd/system/.service.d/autologin.conf'): ...
class ManiSkill2Dataset(Dataset): def __init__(self, dataset_file: str, load_count=(- 1)) -> None: self.dataset_file = dataset_file import h5py from mani_skill2.utils.io_utils import load_json self.data = h5py.File(dataset_file, 'r') json_path = dataset_file.replace('.h5', '....
class Encoder(Ranker): def __init__(self, on: typing.Union[(str, typing.List[str])], key: str, encoder, normalize: bool=True, k: typing.Optional[int]=None, batch_size: int=64) -> None: super().__init__(key=key, on=on, encoder=encoder, normalize=normalize, k=k, batch_size=batch_size) def __call__(self, q...
def open_circuit_potential(c_surf): stretch = 1.062 sto = ((stretch * c_surf) / c_max) u_eq = ((((((2.16216 + (0.07645 * tanh((30.834 - (54.4806 * sto))))) + (2.1581 * tanh((52.294 - (50.294 * sto))))) - (0.14169 * tanh((11.0923 - (19.8543 * sto))))) + (0.2051 * tanh((1.4684 - (5.4888 * sto))))) + (0.2531 *...
def encode_report(rpt, rpt_path): rpt_dict = {} parcels = spatial.read_shapefile(sg.config.parcels_shapefile) parcels = parcels[['PARCELID', 'coords']] flooded = rpt.alt_report.parcel_flooding flooded = pd.merge(flooded, parcels, right_on='PARCELID', left_index=True) rpt_dict['parcels'] = spatia...
class Infraction(ModelReprMixin, models.Model): TYPE_CHOICES = (('note', 'Note'), ('warning', 'Warning'), ('watch', 'Watch'), ('timeout', 'Timeout'), ('kick', 'Kick'), ('ban', 'Ban'), ('superstar', 'Superstar'), ('voice_ban', 'Voice Ban'), ('voice_mute', 'Voice Mute')) inserted_at = models.DateTimeField(default...
class SubscriptionHandler(object): def __init__(self, obj): self.obj = obj self._cache = None def _recache(self): self._cache = {account: True for account in self.obj.db_account_subscriptions.all() if (hasattr(account, 'pk') and account.pk)} self._cache.update({obj: True for obj ...
(scope='session', autouse=True) def symbols_by_file() -> Dict[(str, Set[str])]: sys.stdout = StringIO() lint.Run(['--reports=n', '--rcfile=python_ta/config/.pylintrc', '--output-format=json', *get_file_paths()], exit=False) jsons_output = sys.stdout.getvalue() sys.stdout = sys.__stdout__ pylint_list...
class Attention(nn.Module): def __init__(self, dim, num_heads=8, sr_ratio=1): super().__init__() self.num_heads = num_heads head_dim = (dim // num_heads) self.scale = (head_dim ** (- 0.5)) self.dim = dim self.q = nn.Linear(dim, dim, bias=True) self.kv = nn.Lin...
def _test_false_cyclic_dependency(): class Top(Component): def construct(s): s.a = Wire(int) s.b = Wire(int) s.c = Wire(int) s.d = Wire(int) s.e = Wire(int) s.f = Wire(int) s.g = Wire(int) s.h = Wire(int) ...
def flatten_settings(json: dict) -> dict: settings = json.pop('settings', {}) flattened_settings = {} for (entry, value) in settings.items(): if isinstance(value, dict): flattened_settings.update(value) else: flattened_settings[entry] = value json.update(flattened...
def eval_auto_attack(model, device, cfgs, logger, test_loader, individual=False, print_freq=20, mode='test', train_val=False): logger.info('Evaluating Auto Attack!') model.eval() attacks_to_run = ['apgd-ce', 'apgd-t'] adversary = AutoAttack(model, norm='Linf', eps=cfgs.test_epsilon, version='standard', ...
def get_predictions(example, features, all_results, n_best_size, max_answer_length, do_lower_case, version_2_with_negative, null_score_diff_threshold): unique_id_to_result = {} for result in all_results: unique_id_to_result[result.unique_id] = result _PrelimPrediction = collections.namedtuple('Preli...
.parametrize('name', 'test tests whatever .dotdir'.split()) def test_setinitial_conftest_subdirs(pytester: Pytester, name: str) -> None: sub = pytester.mkdir(name) subconftest = sub.joinpath('conftest.py') subconftest.touch() pm = PytestPluginManager() conftest_setinitial(pm, [sub.parent], confcutdi...
(cc=STDCALL, params={'pIdentifierAuthority': PSID_IDENTIFIER_AUTHORITY, 'nSubAuthorityCount': BYTE, 'nSubAuthority0': DWORD, 'nSubAuthority1': DWORD, 'nSubAuthority2': DWORD, 'nSubAuthority3': DWORD, 'nSubAuthority4': DWORD, 'nSubAuthority5': DWORD, 'nSubAuthority6': DWORD, 'nSubAuthority7': DWORD, 'pSid': POINTER}) de...
class KNearestPMedian(PMedian): def __init__(self, name: str, ai_sum: (int | float), clients: np.array, facilities: np.array, weights: np.array, k_array: np.array, p_facilities: int, capacities: np.array=None, distance_metric: str='euclidean'): self.ai_sum = ai_sum self.clients = clients sel...
class HDDFeatureExtractor(nn.Module): def __init__(self, args): super(HDDFeatureExtractor, self).__init__() if (args.inputs in ['camera', 'sensor', 'multimodal']): self.with_camera = ('sensor' not in args.inputs) self.with_sensor = ('camera' not in args.inputs) else: ...
def relayfee(network: 'Network'=None) -> int: from .simple_config import FEERATE_DEFAULT_RELAY, FEERATE_MAX_RELAY if (network and (network.relay_fee is not None)): fee = network.relay_fee else: fee = FEERATE_DEFAULT_RELAY fee = min(fee, FEERATE_MAX_RELAY) fee = max(fee, FEERATE_DEFAU...
class TestMulticlassPrecisionRecallCurve(unittest.TestCase): def test_multiclass_precision_recall_curve_base(self) -> None: input = torch.tensor([[0.1, 0.2, 0.1], [0.4, 0.2, 0.1], [0.6, 0.1, 0.2], [0.4, 0.2, 0.3], [0.6, 0.2, 0.4]]) target = torch.tensor([0, 1, 2, 1, 0]) my_compute_result = m...
def find_dataset_using_name(dataset_name): dataset_filename = (('data.' + dataset_name) + '_dataset') datasetlib = importlib.import_module(dataset_filename) dataset = None target_dataset_name = (dataset_name.replace('_', '') + 'dataset') for (name, cls) in datasetlib.__dict__.items(): if (na...
class W_ThreadCell(W_Object): errorname = 'thread-cell' _immutable_fields_ = ['initial', 'preserved'] _attrs_ = ['initial', 'preserved', 'value'] _table = ThreadCellTable() def __init__(self, val, preserved): self.value = val self.initial = val self.preserved = preserved ...
_model_architecture('char_source_transformer', 'char_source_transformer') def base_architecture(args): transformer.base_architecture(args) args.char_cnn_params = getattr(args, 'char_cnn_params', '[(50, 1), (100,2)]') args.char_cnn_nonlinear_fn = getattr(args, 'chr_cnn_nonlinear_fn', 'relu') args.char_cn...
def test_sample_partially_observed(): with pm.Model() as m: with pytest.warns(ImputationWarning): x = pm.Normal('x', observed=np.array([0, 1, np.nan])) idata = pm.sample(nuts_sampler='numpyro', chains=1, draws=10, tune=10) assert (idata.observed_data['x_observed'].shape == (2,)) ...
def split_documents(documents: dict) -> dict: (titles, texts) = ([], []) for (title, text) in zip(documents['title'], documents['text']): if (text is not None): for passage in split_text(text): titles.append((title if (title is not None) else '')) texts.append...
.parametrize('add_version_condition', [True, False]) def test_model_version_attribute_save(add_version_condition: bool) -> None: item = VersionedModel('test_user_name', email='test_') with patch(PATCH_METHOD) as req: req.return_value = {} item.save(add_version_condition=add_version_condition) ...
_pypy def test_class_method_with_metaclass_spy(mocker: MockerFixture) -> None: class MetaFoo(type): pass class Foo(): __metaclass__ = MetaFoo def bar(cls, arg): return (arg * 2) spy = mocker.spy(Foo, 'bar') assert (Foo.bar(arg=10) == 20) Foo.bar.assert_called_once...
class GreedyBipartiteMatcherTest(tf.test.TestCase): def test_get_expected_matches_when_all_rows_are_valid(self): similarity_matrix = tf.constant([[0.5, 0.1, 0.8], [0.15, 0.2, 0.3]]) num_valid_rows = 2 expected_match_results = [(- 1), 1, 0] matcher = bipartite_matcher.GreedyBipartiteM...
def read_yaml_file(filename): try: with open(filename) as yaml_file: data = yaml.safe_load(yaml_file) return data except IOError as error: if (LOGGER is None): print(f'File error: {str(error)}') else: LOGGER.error(f'File error: {str(error)}...
def pretty_print_results(args, address_to_index, p2p_bw, results): if args.markdown: print('```') print('Shuffle benchmark') print_separator(separator='-') print_key_value(key='Backend', value=f'{args.backend}') print_key_value(key='Partition size', value=f'{format_bytes(args.partition_size)...
def rename_state_to_visibility(migrator: playhouse.migrate.SqliteMigrator): with database.db.atomic(): database.db.execute(migrator._alter_table(migrator.make_context(), 'multiplayer_session').literal(' RENAME COLUMN ').sql(peewee.Entity('state')).literal(' TO ').sql(peewee.Entity('visibility'))) da...
def all_scores(mols, data, norm=False, reconstruction=False): m0 = {k: list(filter((lambda e: (e is not None)), v)) for (k, v) in {'NP score': MolecularMetrics.natural_product_scores(mols, norm=norm), 'QED score': MolecularMetrics.quantitative_estimation_druglikeness_scores(mols), 'logP score': MolecularMetrics.wat...
def _fix_indentation(content: str) -> str: lines = content.splitlines(keepends=True) first_indent = _get_leading_spaces(content) first_line = lines[0][first_indent:] if (len(lines) == 1): return first_line second_indent = _get_leading_spaces(lines[1]) if first_line.rstrip().endswith(':')...
class unit_gtcn_689(nn.Module): def __init__(self, in_channels, out_channels, A, coff_embedding=4, num_subset=3): super(unit_gtcn_689, self).__init__() inter_channels = (out_channels // coff_embedding) self.inter_c = inter_channels self.PA = nn.Parameter(torch.from_numpy(A.astype(np....
class MatchingForTraining(torch.nn.Module): def __init__(self, config={}): super().__init__() self.superpoint = SuperPoint(config.get('superpoint', {})) self.superglue = SuperGlue(config.get('superglue', {})) def forward(self, data): pred = {} if ('keypoints0' not in data...
(repr=False, frozen=True, slots=True) class _MaxLengthValidator(): max_length = attrib() def __call__(self, inst, attr, value): if (len(value) > self.max_length): msg = f"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}" raise ValueError(msg) def __repr__(se...
def _throughput_compute(num_processed: int, elapsed_time_sec: float) -> torch.Tensor: if (num_processed < 0): raise ValueError(f'Expected num_processed to be a non-negative number, but received {num_processed}.') if (elapsed_time_sec <= 0): raise ValueError(f'Expected elapsed_time_sec to be a po...
class GamePresetDescriber(): def _calculate_pickup_pool(self, configuration: BaseConfiguration) -> list[str]: expected_starting_count = self.expected_starting_item_count(configuration) expected_shuffled_count = self.expected_shuffled_pickup_count(configuration) shuffled_list = [] sta...
def adam(func, x, n_iter, learning_rate=0.001, beta1=0.9, beta2=0.999, eps=1e-08): V = 0.0 S = 0.0 for i in range((n_iter + 1)): (_, grad) = func(x) V = ((beta1 * V) + ((1 - beta1) * grad)) S = ((beta2 * S) + ((1 - beta2) * (grad ** 2))) V_hat = (V / (1 - (beta1 ** (i + 1))))...
class TestDriverHDF5Save(QiskitChemistryTestCase, TestDriver): def setUp(self): super().setUp() driver = HDF5Driver(hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5')) temp_qmolecule = driver.run() (file, self.save_file) = tempfile.mkstemp(suffix='.hdf5') os.close(fil...
def parse_args(): parser = optparse.OptionParser() parser.add_option('-f', '--file', dest='file_path') parser.add_option('-a', '--append', action='store_true', default=False) parser.add_option('-Q', '--quote', action='store_true', default=False) parser.add_option('-s', '--addspace', action='store_tr...
def upgrade(saveddata_engine): saveddata_engine.execute(tmpTable) saveddata_engine.execute('INSERT INTO damagePatternsTemp (ID, name, emAmount, thermalAmount, kineticAmount, explosiveAmount, ownerID, created, modified) SELECT ID, name, emAmount, thermalAmount, kineticAmount, explosiveAmount, ownerID, created, m...
.parametrize('bin_op', [pytest.param((lambda a, b: (a + b)), id='add'), pytest.param((lambda a, b: (a - b)), id='sub'), pytest.param((lambda a, b: (a * b)), id='mul'), pytest.param(_div, id='div')]) def test_binopt_scalar(all_qevo, bin_op): obj = all_qevo scalar = (0.5 + 1j) for t in TESTTIMES: as_q...
class DepositfilesCom(BaseAccount): __name__ = 'DepositfilesCom' __type__ = 'account' __version__ = '0.39' __status__ = 'testing' __description__ = 'Depositfiles.com account plugin' __license__ = 'GPLv3' __authors__ = [('mkaay', ''), ('stickell', 'l.'), ('Walter Purcaro', '')] def grab_i...
def cross_validation(edge_embs, edge_labels): (auc, mrr) = ([], []) (seed_nodes, num_nodes) = (np.array(list(edge_embs.keys())), len(edge_embs)) skf = KFold(n_splits=5, shuffle=True, random_state=seed) for (fold, (train_idx, test_idx)) in enumerate(skf.split(np.zeros((num_nodes, 1)), np.zeros(num_nodes)...
class SpMatrix(_PackedMatrixBase, _sp_matrix.SpMatrix): def __init__(self, num_rows=None, resize_type=_matrix_common.MatrixResizeType.SET_ZERO): super(SpMatrix, self).__init__() if (num_rows is not None): if (isinstance(num_rows, int) and (num_rows >= 0)): self.resize_(nu...
def EfficientNetB0(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, **kwargs): return EfficientNet(1.0, 1.0, 224, 0.2, model_name='efficientnet-b0', include_top=include_top, weights=weights, input_tensor=input_tensor, input_shape=input_shape, pooling=pooling, cl...
def cast_waveunit(unit, force_match=True): if (unit in WAVELEN_UNITS): return 'nm' if (unit in WAVELENVAC_UNITS): return 'nm_vac' elif (unit in WAVENUM_UNITS): return 'cm-1' elif force_match: raise ValueError('Unknown wavespace unit: {0}. Should be one of {1}'.format(unit...
class Effect744(BaseEffect): type = 'passive' def handler(fit, container, context, projectionRange, **kwargs): level = (container.level if ('skill' in context) else 1) fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('CPU Management')), 'duration', (container.getModifiedItemAttr...
def target(): options = ['A', 'B', 'C'] put_input('input', label='input') put_textarea('textarea', label='textarea', rows=3, code=None, maxlength=10, minlength=20, value=None, placeholder='placeholder', readonly=False, help_text='help_text') put_textarea('code', label='code', rows=4, code=True, maxlengt...
class CmdLearnSpell(Command): key = 'learnspell' help_category = 'magic' def func(self): spell_list = sorted(SPELLS.keys()) args = self.args.lower() args = args.strip(' ') caller = self.caller spell_to_learn = [] if ((not args) or (len(args) < 3)): ...
(frozen=True) class ReceiveWithdrawExpired(AuthenticatedSenderStateChange): message_identifier: MessageID canonical_identifier: CanonicalIdentifier total_withdraw: WithdrawAmount expiration: BlockExpiration nonce: Nonce participant: Address def channel_identifier(self) -> ChannelID: ...
def host_tuple(url: QUrl) -> HostTupleType: ensure_valid(url) (scheme, host, port) = (url.scheme(), url.host(), url.port()) assert scheme if (not host): raise ValueError('Got URL {} without host.'.format(url.toDisplayString())) if (port == (- 1)): port_mapping = {' 80, ' 443, 'ftp': ...
def test_AddValueToZero_simple_weights(): dm = skcriteria.mkdm(matrix=[[1, 0, 3], [0, 5, 6]], objectives=[min, max, min], weights=[1, 2, 0]) expected = skcriteria.mkdm(matrix=[[1, 0, 3], [0, 5, 6]], objectives=[min, max, min], weights=[1.5, 2.5, 0.5]) scaler = AddValueToZero(value=0.5, target='weights') ...
def main(): learning_rate = 0.001 parser = argparse.ArgumentParser('Self-Supervised') parser.add_argument('--tau', type=float, default=1.0, metavar='LR') parser.add_argument('--EPS', type=float, default=1e-05, help='episillon') parser.add_argument('--weight-decay', type=float, default=1.5e-06, help=...
class GasMeter(GasMeterAPI): start_gas: int = None gas_refunded: int = None gas_remaining: int = None logger = get_extended_debug_logger('eth.gas.GasMeter') def __init__(self, start_gas: int, refund_strategy: RefundStrategy=default_refund_strategy) -> None: validate_uint256(start_gas, title=...
class ST_plus_TR_block_cross(nn.Module): def __init__(self, config, embed_feat): super(ST_plus_TR_block_cross, self).__init__() self.embed_features = embed_feat encoder_layer_actor = TransformerEncoderLayer_cluster(self.embed_features, config.Nhead, total_size=config.total_size, window_size=...
class QlOsPosix(QlOs): def __init__(self, ql: Qiling): super().__init__(ql) self.ql = ql self.sigaction_act = ([0] * 256) conf = self.profile['KERNEL'] self.uid = self.euid = conf.getint('uid') self.gid = self.egid = conf.getint('gid') self.pid = conf.getint('...
def set_flat_params(model, flat_params, trainable=False): prev_ind = 0 for param in model.parameters(): if (trainable and (not param.requires_grad)): continue flat_size = int(param.numel()) param.data.copy_(flat_params[prev_ind:(prev_ind + flat_size)].view(param.size())) ...
class Effect6724(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.modules.filteredItemBoost((lambda mod: mod.item.requiresSkill('Remote Armor Repair Systems')), 'duration', src.getModifiedItemAttr('eliteBonusLogistics3'), skill='Logistics Cruisers', **kwargs)
def _orient(array, wcs): if (array.ndim != 3): raise ValueError('Input array must be 3-dimensional') if (wcs.wcs.naxis != 3): raise ValueError('Input WCS must be 3-dimensional') wcs = wcs_utils.diagonal_wcs_to_cdelt(_fix_spectral(wcs)) axtypes = wcs.get_axis_types()[::(- 1)] types = ...
class Package(models.Model): is_active = models.BooleanField(verbose_name=_('Is active'), default=True) name = models.CharField(verbose_name=_('Name'), max_length=255) description = models.TextField(verbose_name=_('Description'), blank=True) link = models.URLField(verbose_name=_('URL'), max_length=255) ...
_metaclass(abc.ABCMeta) class BaseGraph(object): def __init__(self, machine): self.machine = machine self.fsm_graph = None self.generate() def generate(self): def set_previous_transition(self, src, dst): def reset_styling(self): def set_node_style(self, state, style): def...
class keep_wl(): def __init__(self, labels): self.loss = torch.zeros(labels.shape[0], 1, dtype=torch.float).cuda(non_blocking=True) self.weight = torch.zeros(labels.shape[0], dtype=torch.float).cuda(non_blocking=True) def __call__(self, epoch_loss=None, epoch_weight=None, index=None): se...
def weight_pad(sim: QuantizationSimModel, layer_bw_dict: Dict[(str, WeightPaddingParams)]): for (layer_name, layer) in sim.quant_wrappers(): bw_values = layer_bw_dict[layer_name] param_quant_dict = layer.param_quantizers if (('weight' in param_quant_dict) and (bw_values.target_kernel_bw > bw...
class NodeLaunchActor(): def run(self, master_addr, master_port, node_rank, dist_world_size, args): processes = [] current_env = os.environ.copy() current_env['MASTER_ADDR'] = master_addr current_env['MASTER_PORT'] = str(master_port) current_env['WORLD_SIZE'] = str(dist_world...
def test_submit_forms_by_get(app, client): crawler = Crawler(client=client, initial_paths=['/'], rules=(PERMISSIVE_HYPERLINKS_ONLY_RULE_SET + SUBMIT_GET_FORMS_RULE_SET)) crawler.crawl() submitted_forms = [form for form in crawler.graph.get_nodes_by_source(FORM) if form.requested] assert (len(submitted_f...
def handle_long_project_instruments_request(**kwargs) -> Any: headers = kwargs['headers'] resp = [{'instrument_name': 'form_1', 'instrument_label': 'Form 1'}, {'instrument_name': 'form_2', 'instrument_label': 'Form 2'}, {'instrument_name': 'form_3', 'instrument_label': 'Form 3'}] return (201, headers, json....
def test_run_tests_in_workers_error_traceback(): def target_fn(): def inner_2(): def inner_1(): raise ValueError('42') inner_1() inner_2() try: run_tests_in_workers(target=target_fn, num_workers=1) except ValueError: (exc_type, exc_valu...
class ViewProviderAsmGroup(ViewProviderAsmBase): def claimChildren(self): return getattr(self.ViewObject.Object, 'Group', []) def doubleClicked(self, _vobj): return False def canDropObject(self, _child): return False def canReplaceObject(self, _oldObj, newObj): return (ne...
def tankSection(fit): ehp = ([fit.ehp[tank] for tank in tankTypes] if (fit.ehp is not None) else [0, 0, 0]) ehp.append(sum(ehp)) ehpStr = [formatAmount(ehpVal, 3, 0, 9) for ehpVal in ehp] resists = {tankType: [(1 - fit.ship.getModifiedItemAttr(s)) for s in resonanceNames[tankType]] for tankType in tankT...
class TestChangeOrganizationDetails(ApiTestCase): def test_changeinvoiceemail(self): self.login(ADMIN_ACCESS_USER) json = self.putJsonResponse(Organization, params=dict(orgname=ORGANIZATION), data=dict(invoice_email=True)) self.assertEqual(True, json['invoice_email']) json = self.put...