code
stringlengths
281
23.7M
def test_solver_does_not_raise_conflict_for_locked_conditional_dependencies(solver: Solver, repo: Repository, package: ProjectPackage) -> None: set_package_python_versions(solver.provider, '~2.7 || ^3.4') dependency_a = Factory.create_dependency('A', {'version': '^1.0', 'python': '^3.6'}) package.add_depend...
class XPath(): def __init__(self, *xpaths): self.xpaths = xpaths def __str__(self): return self.xpath def __repr__(self): return ("%s('%s')" % (self.__class__.__name__, str(self))) def __getitem__(self, n): return self.__class__(*[('%s[%s]' % (xpath, n)) for xpath in self...
def get_cover_and_lastbit0image(reshaped_image): cover_temp = np.zeros(reshaped_image.shape[0]).astype('int8') for i in range(reshaped_image.shape[0]): last_bit = int(bin(reshaped_image[i])[2:].zfill(8)[(- 1)]) cover_temp[i] = last_bit lastbit0image = (reshaped_image - cover_temp) return...
.parametrize('auth, pj_type, deprecated', [(None, None, False), ('EPSG', PJType.PROJECTED_CRS, False), ('EPSG', PJType.PROJECTED_CRS, True), ('IGNF', [PJType.GEOGRAPHIC_3D_CRS, PJType.GEOGRAPHIC_2D_CRS], False), ('EPSG', 'PROJECTED_CRS', False), ('EPSG', 'Projected_Crs', True)]) def test_query_crs_info(auth, pj_type, d...
.parametrize(['method', 'order'], [pytest.param('euler', 0.5, id='Euler'), pytest.param('milstein', 1.0, id='Milstein'), pytest.param('milstein_imp', 1.0, id='Milstein implicit'), pytest.param('platen', 1.0, id='Platen'), pytest.param('pred_corr', 1.0, id='PredCorr'), pytest.param('rouchon', 1.0, id='rouchon'), pytest....
_cache() def get_executable_even_when_embedded(): exe = str(sys.executable) if pathlib.Path(exe).name.startswith('python'): try: test_exe(exe) return exe except FileNotFoundError: pass current_path = pathlib.Path(np.__file__).parents[4] exe = str(curre...
def test_format_currency(): assert (numbers.format_currency(1099.98, 'USD', locale='en_US') == '$1,099.98') assert (numbers.format_currency(1099.98, 'USD', locale='en_US', numbering_system='default') == '$1,099.98') assert (numbers.format_currency(0, 'USD', locale='en_US') == '$0.00') assert (numbers.fo...
(os.environ, {'CUDA_VISIBLE_DEVICES': '0'}) def test_worker_fraction_limits(loop): pytest.importorskip('rmm') with popen(['dask', 'scheduler', '--port', '9369', '--no-dashboard']): with popen(['dask', 'cuda', 'worker', '127.0.0.1:9369', '--host', '127.0.0.1', '--device-memory-limit', '0.1', '--rmm-pool-...
def test_uniquifier(): obj1 = [1] obj2 = [2] obj3 = [3] obj4 = [4] obj5 = [5] objs = [obj1, obj2, obj1, obj2, obj3, obj3] objsA = [obj2, obj1, obj2, obj1, obj4, obj4] uniq = Uniquifier(objs) unique_objs = uniq.get_unique_objs() assert (len(unique_objs) == 3) assert (unique_ob...
class SDFusionImage2ShapeModel(BaseModel): def name(self): return 'SDFusionImage2ShapeModel' def initialize(self, opt): BaseModel.initialize(self, opt) self.isTrain = opt.isTrain self.model_name = self.name() self.device = opt.device assert (opt.df_cfg is not None...
.parametrize('freq, start_date, days_in_current_year, days_in_next_year', [('1D', '2012-12-31', 1, 0), ('1D', '2011-12-31', 1, 0), ('3D', '2012-12-30', 2, 1), (7, '2012-12-29', 3, 4), ('60h', '2012-12-31', 1, 1.5), ('15h', '2012-12-31', 0.625, 0), ('39h', '2012-12-31', 1, 0.625)]) def test_timestep_days_in_year_methods...
class ResearchModels(): def __init__(self, nb_classes, num_of_snip, opt_flow_len, image_shape=(224, 224), saved_model=None): self.num_of_snip = num_of_snip self.opt_flow_len = opt_flow_len self.load_model = load_model self.saved_model = saved_model self.nb_classes = nb_classe...
def kbkdf_counter_mode_test(backend, params): supported_counter_locations = {'before_fixed': CounterLocation.BeforeFixed, 'after_fixed': CounterLocation.AfterFixed, 'middle_fixed': CounterLocation.MiddleFixed} ctr_loc = supported_counter_locations[params.pop('ctrlocation')] brk_loc = None if (ctr_loc ==...
class ChaCha20(CipherAlgorithm): name = 'ChaCha20' key_sizes = frozenset([256]) def __init__(self, key: bytes, nonce: bytes): self.key = _verify_key_size(self, key) utils._check_byteslike('nonce', nonce) if (len(nonce) != 16): raise ValueError('nonce must be 128-bits (16 ...
def test_upgrade_specifier(pipx_temp_env, capsys): name = 'pylint' pkg_spec = PKG[name]['spec'] initial_version = pkg_spec.split('==')[(- 1)] assert (not run_pipx_cli(['install', f'{pkg_spec}'])) assert (not run_pipx_cli(['upgrade', f'{name}'])) captured = capsys.readouterr() assert (f'upgra...
class StartupsDataset(Dataset): def __init__(self, path: str, max_samples: int=500): super().__init__() with open(path, 'r', encoding='utf8') as f: lines = f.readlines()[:max_samples] random.shuffle(lines) self.data = [json.loads(line) for line in lines] i...
class FakeDirectory(FakeFile): def __init__(self, name: str, perm_bits: int=helpers.PERM_DEF, filesystem: Optional['FakeFilesystem']=None): FakeFile.__init__(self, name, (S_IFDIR | perm_bits), '', filesystem=filesystem) self.st_nlink += 1 self._entries: Dict[(str, AnyFile)] = {} def set_...
def build_custom_train_loader(cfg, mapper=None): source_aware = cfg.DATALOADER.SOURCE_AWARE if source_aware: dataset_dicts = get_detection_dataset_dicts_with_source(cfg.DATASETS.TRAIN, filter_empty=cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS, min_keypoints=(cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAG...
def _read_classes(csv_reader): result = OrderedDict() for (line, row) in enumerate(csv_reader): line += 1 try: (class_name, class_id) = row except ValueError: raise_from(ValueError("line {}: format should be 'class_name,class_id'".format(line)), None) clas...
class AdaptiveBatchNorm2d(nn.BatchNorm2d): def __init__(self, num_features, num_w=512, eps=1e-05, momentum=0.1, affine=False, track_running_stats=True): super(AdaptiveBatchNorm2d, self).__init__(num_features, eps, momentum, affine, track_running_stats) self.weight_proj = nn.Linear(num_w, num_feature...
class OrthographicPoisson(): def __init__(self, data): self.method_name = 'orthographic_poisson' print('running {}...'.format(self.method_name)) method_start = time.time() p = ((- data.n[(data.mask, 0)]) / data.n[(data.mask, 2)]) q = ((- data.n[(data.mask, 1)]) / data.n[(data...
def _find_common_ancestor_of_all_nodes(tasks: list[PTaskWithPath], paths: list[Path], show_nodes: bool) -> Path: all_paths = [] for task in tasks: all_paths.append(task.path) if show_nodes: all_paths.extend((x.path for x in tree_leaves(task.depends_on) if isinstance(x, PPathNode))) ...
class Denoised_Classifier(torch.nn.Module): def __init__(self, diffusion, model, classifier, t): super().__init__() self.diffusion = diffusion self.model = model self.classifier = classifier self.t = t def sdedit(self, x, t, to_01=True): x = ((x * 2) - 1) ...
class UtilTest(parameterized.TestCase, tf.test.TestCase): def test_tfdata(self): ground_truth_data = dummy_data.DummyData() dataset = util.tf_data_set_from_ground_truth_data(ground_truth_data, 0) one_shot_iterator = dataset.make_one_shot_iterator() next_element = one_shot_iterator.ge...
def test_help_subcommand_completion_with_flags_before_command(scu_app): text = '' line = 'help -h -v base {}'.format(text) endidx = len(line) begidx = (endidx - len(text)) first_match = complete_tester(text, line, begidx, endidx, scu_app) assert ((first_match is not None) and (scu_app.completion...
def find_18(): if (('msprnt.exe' in datastore.SYSTEMROOT_FILE_SET) or ('fmem.dll' in datastore.SYSTEMROOT_FILE_SET)): return True search_set = set(('pnppci', 'ethio', 'ntdos505', 'ndisio')) if (not datastore.SERVICE_NAME_SET.isdisjoint(search_set)): return True (cmdStatus, cmdId) = dsz.c...
def test_untested_floats(covtest): covtest.makefile('\n def func():\n pass\n\n def untested():\n pass\n\n def untested2():\n pass\n\n def untested3():\n pass\n\n def untested4():\n pass\n\n def untested5():\n ...
class Plugin(DigitalBitboxPlugin, QtPluginBase): icon_unpaired = 'digitalbitbox_unpaired.png' icon_paired = 'digitalbitbox.png' def create_handler(self, window): return DigitalBitbox_Handler(window) _hook_if_libraries_available def receive_menu(self, menu, addrs, wallet: Abstract_Wallet): ...
def main_worker(gpu, ngpus_per_node, args): global best_acc1 args.gpu = gpu if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distributed: if ((args.dist_url == 'env://') and (args.rank == (- 1))): args.rank = int(os.environ['RANK']) ...
.parametrize('edge,rotation,expected', [('crop_edge_top', 0, 'SizeVerCursor'), ('crop_edge_top', 90, 'SizeHorCursor'), ('crop_edge_top', 180, 'SizeVerCursor'), ('crop_edge_top', 270, 'SizeHorCursor'), ('crop_edge_bottom', 0, 'SizeVerCursor'), ('crop_edge_bottom', 90, 'SizeHorCursor'), ('crop_edge_bottom', 180, 'SizeVer...
def get_local_output_filepaths(input_files, dest_dir): output_files = [] for item in input_files: if isinstance(item, list): out = get_local_output_filepaths(item, dest_dir) else: out = get_local_path(item, dest_dir) output_files.append(out) return output_file...
class ServerMessage(MessageBase): def from_remote(cls, sock): header = cls._recv(sock) if (not PY2): header = header.decode() kwargs = json.loads(header) struct_fmt = kwargs.get('struct_fmt') if (struct_fmt is not None): struct_fmt = str(struct_fmt) ...
def main(): args = parse_args() cfg = retrieve_data_cfg(args.config, args.skip_type, args.cfg_options) dataset = build_dataset(cfg.data.train) progress_bar = mmcv.ProgressBar(len(dataset)) for item in dataset: filename = (os.path.join(args.output_dir, Path(item['filename']).name) if (args.ou...
def main(args): with open(args.parsed_ace_roles) as f: parsed_ace_roles = json.load(f) name_to_ontology = {parsed['name']: parsed for parsed in parsed_ace_roles} print('Ontology loaded.') with open(('.'.join(args.parsed_ace_roles.split('.')[:(- 1)]) + '.py')) as f: ace_roles_full_context...
class BloqBuilder(): def __init__(self, add_registers_allowed: bool=True): self._cxns: List[Connection] = [] self._regs: List[Register] = [] self._binsts: Set[BloqInstance] = set() self._i = 0 self._available: Set[Soquet] = set() self.add_register_allowed = add_regist...
def updateCron(restore=False): if (not restore): sysvals.rootUser(True) crondir = '/var/spool/cron/crontabs/' if (not os.path.exists(crondir)): crondir = '/var/spool/cron/' if (not os.path.exists(crondir)): doError(('%s not found' % crondir)) cronfile = (crondir + 'root') ...
def MobileNet(input_shape=None, alpha=1.0, depth_multiplier=1, dropout=0.001, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000, params=PARAM_NONE, **kwargs): global backend, layers, models, keras_utils (backend, layers, models, keras_utils) = get_submodules_from_kwargs(kwargs)...
def get_atom_symbols(mol, center_ids): aromatic_elements = _aromatic_elements atom_symbols = [] for atom in mol.GetAtoms(): atomic_num = atom.GetAtomicNum() is_in_ring = atom.IsInRing() if (atomic_num == 0): element_symbol = '#0' elif (is_in_ring and (atomic_num i...
def parse_data(dataset_dir, file_name, interval): data_all = [] file_path = f'{dataset_dir}/{file_name}' with open(file_path, 'r') as f: lines = f.read().splitlines() Nt = int((len(lines) / interval)) print('Nt, interval', Nt, interval) for i in tqdm(range(Nt)): f...
def main(): root = './Data/' parser = argparse.ArgumentParser('WiFi Imaging Benchmark') parser.add_argument('--dataset', choices=['UT_HAR_data', 'NTU-Fi-HumanID', 'NTU-Fi_HAR', 'Widar']) parser.add_argument('--model', choices=['MLP', 'LeNet', 'ResNet18', 'ResNet50', 'ResNet101', 'RNN', 'GRU', 'LSTM', 'B...
def use_src_log_handler(where: Union[(HandlerMode, str)]) -> None: global _current_mode if isinstance(where, str): where = HandlerMode[where.upper()] _initialize_if_necessary() if (where == _current_mode): return if (_current_mode == HandlerMode.IN_SRC): _disable_default_hand...
def _get_value_for_key(key, obj, default): if is_indexable_but_not_string(obj): try: return obj[key] except (IndexError, TypeError, KeyError): pass if is_integer_indexable(obj): try: return obj[int(key)] except (IndexError, TypeError, ValueErro...
class PColorMeshItem(GraphicsObject): sigLevelsChanged = QtCore.Signal(object) def __init__(self, *args, **kwargs): GraphicsObject.__init__(self) self.qpicture = None self.x = None self.y = None self.z = None self._dataBounds = None self.edgecolors = kwarg...
class LSTMEncoder(Encoder): def __init__(self, vocab, embed_size, hidden_size, num_layers, dropout, bidirectional=True): super().__init__(vocab) self.vocab = vocab self.bidirectional = bidirectional self.embed = nn.Embedding(len(self.vocab), embed_size) self.lstm = nn.LSTM(em...
def setUpModule(): global cell, alle_cell, kpts, alle_kpts cell = gto.Cell() cell.unit = 'A' cell.atom = 'C 0., 0., 0.; C 0.8917, 0.8917, 0.8917' cell.a = '0. 1.7834 1.7834\n 1.7834 0. 1.7834\n 1.7834 1.7834 0. ' cell.basis = 'gth-dzvp' cell...
.parametrize(['cls', 'result'], [(int, False), (bool, False), (str, False), (bytes, False), (list, True), (dict, True), (type, True), (set, True), (frozenset, True), (collections.deque, True), (collections.ChainMap, True), (collections.defaultdict, True), *gen_ns_parametrize((lambda gen_ns: (gen_ns.Gen, True)), (lambda...
def get_model_path(timestamp, opts): inputs = ((('z' + str(opts.use_z)) + '_alpha') + str(opts.use_alpha)) model_path = ((opts.log_dir % opts.dataset) + (opts.model_epoch_path % (timestamp, opts.folder_to_save, opts.lr, opts.batch_size, opts.model_type, opts.splatter, opts.noise, opts.norm_G, opts.refine_model_...
class ResponseWrapperBase(): def __init__(self, response): self.original = response def text(self): return self.original.text def content(self): return self.original.content def status_code(self): return self.original.status_code def headers(self): return self...
class DayRoomThroughModel(OrderedModel): day = models.ForeignKey(Day, on_delete=models.CASCADE, verbose_name=_('day'), related_name='added_rooms') room = models.ForeignKey(Room, on_delete=models.CASCADE, verbose_name=_('room')) order_with_respect_to = 'day' streaming_url = models.URLField(_('Streaming U...
class TestThriftEnum(TestNameCheckVisitorBase): _passes() def test_basic(self): class ThriftEnum(object): X = 0 Y = 1 _VALUES_TO_NAMES = {0: 'X', 1: 'Y'} _NAMES_TO_VALUES = {'X': 0, 'Y': 1} def want_enum(e: ThriftEnum): pass def...
class sdist(orig.sdist): user_options = [('formats=', None, 'formats for source distribution (comma-separated list)'), ('keep-temp', 'k', ('keep the distribution tree around after creating ' + 'archive file(s)')), ('dist-dir=', 'd', 'directory to put the source distribution archive(s) in [default: dist]'), ('owner=...
class MJVLIGHT(Structure): _fields_ = [('pos', (c_float * 3)), ('dir', (c_float * 3)), ('attenuation', (c_float * 3)), ('cutoff', c_float), ('exponent', c_float), ('ambient', (c_float * 3)), ('diffuse', (c_float * 3)), ('specular', (c_float * 3)), ('headlight', c_ubyte), ('directional', c_ubyte), ('castshadow', c_u...
def from_content_type(response, base_url=None, base_path=None, tree_type=HIERARCHY): assert hasattr(response, 'headers'), "Response object must have a 'headers' attribute!" assert hasattr(response, 'url'), "Response object must have a 'url' attribute!" ctypes = get_content_type_from_headers(response.headers...
class FakeOpener(): def __init__(self): self.reqs = [] def __call__(self, *args): return self def open(self, req, data=None, timeout=None): self.reqs.append(req) return self def read(self): return b'xxx' def getheader(self, name, default=None): return ...
def _convert_extras_requirements(extras_require: _StrOrIter) -> Mapping[(str, _Ordered[Requirement])]: output: Mapping[(str, _Ordered[Requirement])] = defaultdict(dict) for (section, v) in extras_require.items(): output[section] for r in _reqs.parse(v): output[(section + _suffix_for(...
.allow_bad_gc_pyside def test_editor(qtbot, plotting): plotter = BackgroundPlotter(editor=False, off_screen=False) qtbot.addWidget(plotter.app_window) assert (plotter.editor is None) plotter.close() plotter = BackgroundPlotter(editor=True, off_screen=False) qtbot.addWidget(plotter.app_window) ...
class Tpango(TestCase): def test_escape_empty(self): self.assertEqual(util.escape(''), '') def test_roundtrip(self): for s in ['foo&amp;', '<&>', '&', '&amp;', '<&testing&amp;>amp;']: esc = util.escape(s) self.assertNotEqual(s, esc) self.assertEqual(s, util.un...
def sampler(z, y): with tf.variable_scope('generator'): tf.get_variable_scope().reuse_variables() (s2, s4) = (int((FLAGS.output_size / 2)), int((FLAGS.output_size / 4))) y_size = 256 y_linear = linear(y, y_size, 'g_liner') z = tf.concat(axis=1, values=[z, y_linear]) h...
def test_step_functions_same_parser(pytester): pytester.makefile('.feature', target_fixture=textwrap.dedent(' Feature: A feature\n Scenario: A scenario\n Given there is a foo with value "(?P<value>\\w+)"\n And there is a foo with value "testfoo"\n ...
class RandBatchNorm2d(nn.Module): def __init__(self, sigma_0, N, init_s, num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True): super(RandBatchNorm2d, self).__init__() self.sigma_0 = sigma_0 self.N = N self.num_features = num_features self.init_s = ini...
class Series(Frame, _SeriesMixin): def __init__(self, *args, **kwargs): example = None if ('example' in kwargs): example = kwargs.get('example') elif (len(args) > 1): example = args[1] if isinstance(self, Index): self._subtype = get_base_frame_type...
class Effect2756(BaseEffect): type = 'passive' def handler(fit, ship, context, projectionRange, **kwargs): for type in ('Gravimetric', 'Magnetometric', 'Ladar', 'Radar'): fit.modules.filteredItemBoost((lambda mod: (mod.item.group.name == 'ECM')), 'scan{0}StrengthBonus'.format(type), ship.get...
_REGISTRY.register() def build_fcos_resnet_bifpn_backbone(cfg, input_shape: ShapeSpec): bottom_up = build_resnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.BIFPN.OUT_CHANNELS num_repeats = cfg.MODEL.BIFPN.NUM_BIFPN top_levels = 2 backbone = BiFPN(...
class PerTensorCompression(AdaptiveCompressionBase): def __init__(self, tensor_compressions: Union[(Sequence[CompressionBase], Mapping[(Key, CompressionBase)])]): self.tensor_compressions = tensor_compressions def choose_compression(self, info: CompressionInfo) -> CompressionBase: return self.te...
class ChargeBase(StageBase): type: Literal['ChargeBase'] = 'ChargeBase' solvent_settings: Optional[T] = Field(None, description='The settings used to calculate the electron density in implicit solvent.') program: Literal['gaussian'] = Field('gaussian', description='The name of the QM program to calculate th...
class CatalogReference(VersionBase): def __init__(self, catalogname, entryname): self.catalogname = catalogname self.entryname = entryname self.parameterassignments = [] def __eq__(self, other): if isinstance(other, CatalogReference): if ((self.get_attributes() == oth...
def kmeans_embeddings(embs, k_opt=None, k_max=10, method='faiss', return_fitted_model=False): if (k_opt is None): silhouette_scores = [] for n_cluster in range(2, min((k_max + 1), len(embs))): labels = kmeans_train(embs, n_cluster, method) silhouette_scores.append(silhouette_...
def _get_listener(): global _listener if (_listener is None): _lock.acquire() try: if (_listener is None): debug('starting listener and thread for sending handles') _listener = Listener(authkey=current_process().authkey) t = threading.T...
def is_send_transfer_almost_equal(send_channel: NettingChannelState, send: LockedTransferUnsignedState, received: LockedTransferSignedState) -> bool: return ((send.payment_identifier == received.payment_identifier) and (send.token == received.token) and (send.lock.expiration == received.lock.expiration) and (send.l...
class ProjectManagerOptions(PymiereBaseObject): def __init__(self, pymiere_id=None): super(ProjectManagerOptions, self).__init__(pymiere_id) ' Which transfer option to use; will be one of these: \t`CLIP_TRANSFER_COPY` `CLIP_TRANSFER_TRANSCODE` ' def clipTransferOption(self): return self._ev...
def test_cannot_reset_password_of_not_active_user(graphql_client): user = UserFactory(email='', password='old-password', jwt_auth_id=1, is_active=False) token = _create_reset_password_token(user=user) body = graphql_client.query('mutation($input: ResetPasswordInput!) {\n resetPassword(input: $inp...
def wandb_log(prefix, sp_values, com_values, update_summary=False, wandb_summary_dict={}): new_values = {} for (k, _) in sp_values.items(): new_key = ((prefix + '/') + k) new_values[new_key] = sp_values[k] if update_summary: if (new_key not in wandb_summary_dict): ...
def main(config, db, **kwargs): _check_missing_stream_info(config, db, update_db=(not config.debug)) if config.record_scores: _check_new_episode_scores(config, db, update_db=(not config.debug)) _record_poll_scores(config, db, update_db=(not config.debug)) _check_show_lengths(config, db, update_d...
def evaluate(args, model, tokenizer, prefix='', output_layer=(- 1), eval_highway=False): eval_task_names = (('mnli', 'mnli-mm') if (args.task_name == 'mnli') else (args.task_name,)) eval_outputs_dirs = ((args.output_dir, (args.output_dir + '-MM')) if (args.task_name == 'mnli') else (args.output_dir,)) resul...
class Visualizer(): def __init__(self, opt): self.display_id = opt.display_id self.use_html = (opt.isTrain and (not opt.no_html)) self.win_size = opt.display_winsize self.name = opt.name self.opt = opt self.saved = False if (self.display_id > 0): i...
class BaseDraftWire(BaseSketch): _id = (- 1) def check(cls, elements, checkCount=False): super(BaseDraftWire, cls).check(elements, checkCount) if (not checkCount): return for info in elements: if utils.isDraftWire(info.Part): return raise R...
def test_multi_marker_union_with_multi_union_is_single_marker() -> None: m = parse_marker('sys_platform == "darwin" and python_version == "3"') m2 = parse_marker('sys_platform == "darwin" and python_version < "3" or sys_platform == "darwin" and python_version > "3"') assert (str(m.union(m2)) == 'sys_platfor...
.supported(only_if=(lambda backend: backend.cipher_supported(algorithms.TripleDES((b'\x00' * 8)), modes.CFB((b'\x00' * 8)))), skip_message='Does not support TripleDES CFB') class TestTripleDESModeCFB(): test_kat = generate_encrypt_test(load_nist_vectors, os.path.join('ciphers', '3DES', 'CFB'), ['TCFB64invperm.rsp',...
def _ButtonTruncInfo(win): lineFormat = win32defines.DT_SINGLELINE if win.has_style(win32defines.BS_MULTILINE): lineFormat = win32defines.DT_WORDBREAK heightAdj = 4 widthAdj = 5 if win.has_style(win32defines.BS_PUSHLIKE): widthAdj = 3 heightAdj = 3 if win.has_style(wi...
class Effect6436(BaseEffect): displayName = 'Warp Disruption' grouped = True prefix = 'fighterAbilityWarpDisruption' type = ('active', 'projected') def handler(cls, fit, src, context, projectionRange, **kwargs): if ('projected' not in context): return if fit.ship.getModif...
.parametrize('b, loc, scale, size', [(np.array(5, dtype=config.floatX), np.array(0, dtype=config.floatX), np.array(1, dtype=config.floatX), None), (np.array(5, dtype=config.floatX), np.array(0, dtype=config.floatX), np.array(1, dtype=config.floatX), []), (np.array(5, dtype=config.floatX), np.array(0, dtype=config.float...
def test_animal_fly_dataset(): dataset = 'AnimalFlyDataset' dataset_class = DATASETS.get(dataset) dataset_info = Config.fromfile('configs/_base_/datasets/fly.py').dataset_info channel_cfg = dict(num_output_channels=32, dataset_joints=32, dataset_channel=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14...
class TestTrainingExtensionsUtils(unittest.TestCase): def test_round_up_to_higher_multiplicity(self): self.assertEqual(round_up_to_multiplicity(8, 3, 32), 8) self.assertEqual(round_up_to_multiplicity(8, 13, 32), 16) self.assertEqual(round_up_to_multiplicity(8, 17, 32), 24) self.asser...
def build_doc_eval_file(out_file, encodings_dir, encoder_model, k, per_doc=True): print('loading data...') corpus = SquadRelevanceCorpus() questions = corpus.get_dev() spec = QuestionAndParagraphsSpec(batch_size=None, max_num_contexts=1, max_num_question_words=None, max_num_context_words=None) voc =...
class PhysERI4(PhysERI): def __init__(self, model, frozen=None): td.PhysERI4.__init__.im_func(self, model, frozen=frozen) symmetries = [((0, 1, 2, 3), False), ((1, 0, 3, 2), False), ((2, 3, 0, 1), True), ((3, 2, 1, 0), True)] def __calc_block__(self, item, k): if (self.kconserv[k[:3]] == k[3...
def main(args): modelpath = (args.loadDir + args.loadModel) weightspath = (args.loadDir + args.loadWeights) print(('Loading model: ' + modelpath)) print(('Loading weights: ' + weightspath)) model = Net(NUM_CLASSES) model = torch.nn.DataParallel(model) if (not args.cpu): model = model...
class FieldDefinition(object): FIELDS = {} def lookup(cls, name): try: field = cls.FIELDS[name] except KeyError: field = TorrentProxy.add_manifold_attribute(name) return ({'matcher': field._matcher} if field else None) def __init__(self, valtype, name, doc, ac...
def test_column_lineage_multiple_paths_for_same_column(): sql = 'INSERT INTO tab2\nSELECT tab1.id,\n coalesce(join_table_1.col1, join_table_2.col1, join_table_3.col1) AS col1\nFROM tab1\n LEFT JOIN (SELECT id, col1 FROM tab1 WHERE flag = 1) AS join_table_1\n ON tab1.id = join_table_1...
def filter_by_size(indices, dataset, max_positions, raise_exception=False): if (isinstance(max_positions, float) or isinstance(max_positions, int)): if (hasattr(dataset, 'sizes') and isinstance(dataset.sizes, np.ndarray)): ignored = indices[(dataset.sizes[indices] > max_positions)].tolist() ...
def test_assert_reactpy_logged_ignores_level(): original_level = ROOT_LOGGER.level ROOT_LOGGER.setLevel(logging.INFO) try: with testing.assert_reactpy_did_log(match_message='.*'): ROOT_LOGGER.debug('my message') finally: ROOT_LOGGER.setLevel(original_level)
class Ui_Form(object): def setupUi(self, Form): Form.setObjectName('Form') Form.resize(481, 840) self.averageGroup = QtWidgets.QGroupBox(Form) self.averageGroup.setGeometry(QtCore.QRect(0, 640, 242, 182)) self.averageGroup.setCheckable(True) self.averageGroup.setCheck...
def ql_syscall_writev(ql: Qiling, fd: int, vec: int, vlen: int): regreturn = 0 size_t_len = ql.arch.pointersize iov = ql.mem.read(vec, ((vlen * size_t_len) * 2)) ql.log.debug('writev() CONTENT:') for i in range(vlen): addr = ql.unpack(iov[((i * size_t_len) * 2):(((i * size_t_len) * 2) + size...
class SmilesRnnSampler(): def __init__(self, device: str, batch_size=64) -> None: self.device = device self.batch_size = batch_size self.sd = SelfiesCharDictionary() def sample(self, model: SmilesRnn, num_to_sample: int, max_seq_len=100): sampler = ActionSampler(max_batch_size=se...
def _layer_dict(manifest_layer, index): command = None if manifest_layer.command: try: command = json.loads(manifest_layer.command) except (TypeError, ValueError): command = [manifest_layer.command] return {'index': index, 'compressed_size': manifest_layer.compressed_...
class EnvironmentAction(_ActionType): def __init__(self, environment): if (not (isinstance(environment, Environment) or isinstance(environment, CatalogReference))): raise TypeError('environment input not of type Environment or CatalogReference') self.environment = environment def __e...
def test_duplicate_robot_creation(app): with client_with_identity('devtable', app) as cl: resp = conduct_api_call(cl, UserRobot, 'PUT', {'robot_shortname': 'dtrobot'}, expected_code=400) assert (resp.json['error_message'] == 'Existing robot with name: devtable+dtrobot') resp = conduct_api_ca...
class Rectangularity(): def __init__(self, gdf, areas=None): self.gdf = gdf gdf = gdf.copy() if (areas is None): areas = gdf.geometry.area if (not isinstance(areas, str)): gdf['mm_a'] = areas areas = 'mm_a' self.areas = gdf[areas] m...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--img-folder', type=str, required=True) parser.add_argument('--prefix', type=str, required=True) parser.add_argument('--out-path', type=str, required=True) parser.add_argument('--start', type=int, default=None) parser.add_...
class W_InterposeStructBase(values_struct.W_RootStruct): EMPTY_HANDLER_MAP = make_caching_map_type('get_storage_index', int).EMPTY EMPTY_PROPERTY_MAP = make_map_type('get_storage_index', W_Object).EMPTY _attrs_ = ['inner', 'base', 'map'] _immutable_fields_ = ['inner', 'base', 'map'] def __init__(sel...
def test_multiline_import_snippets(config, workspace): document = 'from datetime import(\n date,\n datetime)\na=date' doc = Document(DOC_URI, workspace, document) config.capabilities['textDocument'] = {'completion': {'completionItem': {'snippetSupport': True}}} config.update({'plugins': {'jedi_completio...