code
stringlengths
281
23.7M
def main(train_file, valid_file, test_file, embeddings_file, target_dir, hidden_size=300, dropout=0.5, num_classes=2, epochs=64, batch_size=32, lr=0.0004, patience=5, max_grad_norm=10.0, checkpoint=None, proportion=1, output=None): device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) print(...
class SASLexer(RegexLexer): name = 'SAS' aliases = ['sas'] filenames = ['*.SAS', '*.sas'] mimetypes = ['text/x-sas', 'text/sas', 'application/x-sas'] url = ' version_added = '2.2' flags = (re.IGNORECASE | re.MULTILINE) builtins_macros = ('bquote', 'nrbquote', 'cmpres', 'qcmpres', 'compst...
class PointwiseSamplerV2(Sampler): def __init__(self, dataset, batch_size=1024, shuffle=True, drop_last=False): super(Sampler, self).__init__() self.batch_size = batch_size self.drop_last = drop_last self.shuffle = shuffle self.item_num = dataset.num_items self.user_p...
class TimeSimulation(): def __init__(self, hamiltonian, method='split-step'): self.H = hamiltonian implemented_solvers = ('split-step', 'split-step-cupy', 'crank-nicolson', 'crank-nicolson-cupy') if (method == 'split-step'): if (self.H.potential_type == 'grid'): s...
def allow_access_to_confdir(confdir, allow): from errno import EEXIST if allow: try: os.makedirs(confdir) except OSError as err: if (err.errno != EEXIST): print('This configuration directory could not be created:') print(confdir) ...
class SampleClassIDsUniformlyTest(tf.test.TestCase): def test_num_ways_respected(self): num_classes = test_utils.MAX_WAYS_UPPER_BOUND num_ways = test_utils.MIN_WAYS for _ in range(10): class_ids = sampling.sample_class_ids_uniformly(num_ways, num_classes) self.assertL...
.requires_internet def test_pre_install_commands(hatch, helpers, temp_dir, config_file): config_file.model.template.plugins['default']['tests'] = False config_file.save() project_name = 'My.App' with temp_dir.as_cwd(): result = hatch('new', project_name) assert (result.exit_code == 0), resul...
def summary_bssids(pkts, res): table_data = [['SSID', 'BSSID', 'CHANNEL', 'DBM', 'ENCRYPTED', 'ENCRYPTION TYPE']] dot11beacon_packets_count = 0 for pkt in pkts: if pkt.haslayer(Dot11Beacon): dot11beacon_packets_count += 1 stats = packet[Dot11Beacon].network_stats() ...
.parametrize('sparse', [False, True], ids=['Dense', 'Sparse']) def test_eigen_transform(sparse): a = qutip.destroy(5) f = (lambda t: t) op = qutip.QobjEvo([(a * a.dag()), [(a + a.dag()), f]]) eigenT = _EigenBasisTransform(op, sparse=sparse) evecs_qevo = eigenT.as_Qobj() for t in [0, 1, 1.5]: ...
def _tensor_test_case(dtype: torch.dtype, shape: List[int], logical_path: str, rank: int, replicated: bool) -> Tuple[(torch.Tensor, Entry, List[WriteReq])]: tensor = rand_tensor(shape, dtype=dtype) (entry, wrs) = prepare_write(obj=tensor, logical_path=logical_path, rank=rank, replicated=replicated) return (...
class PipelineIterator(IterableDataset): def __init__(self, loader, infer, params, loader_batch_size=None): self.loader = loader self.infer = infer self.params = params if (loader_batch_size == 1): loader_batch_size = None self.loader_batch_size = loader_batch_siz...
class DepthToNormalNode(topic_tools.LazyTransport): def __init__(self): super().__init__() self._pub_normal = self.advertise('~output/normal', Image, queue_size=1) self._pub_jet = self.advertise('~output/jet', Image, queue_size=1) self._post_init() def subscribe(self): su...
_function('mypy_extensions.i16') def translate_i16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> (Value | None): if ((len(expr.args) != 1) or (expr.arg_kinds[0] != ARG_POS)): return None arg = expr.args[0] arg_type = builder.node_type(arg) if is_int16_rprimitive(arg_type): retu...
class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = "\n exec_stmt< 'exec' a=any 'in' b=any [',' c=any] >\n |\n exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any >\n " def transform(self, node, results): assert results syms = self.syms a = results['a'] ...
class TensorDictBase(MutableMapping): _safe = False _lazy = False _inplace_set = False is_meta = False _is_locked = False _cache = None def __bool__(self) -> bool: raise RuntimeError('Converting a tensordict to boolean value is not permitted') def __ne__(self, other: object) -> T...
class FixtureManager(): FixtureLookupError = FixtureLookupError FixtureLookupErrorRepr = FixtureLookupErrorRepr def __init__(self, session: 'Session') -> None: self.session = session self.config: Config = session.config self._arg2fixturedefs: Final[Dict[(str, List[FixtureDef[Any]])]]...
def show_array_list(array_list, title): (fig, ax) = plt.subplots(1, 1) if isinstance(array_list[0][0], str): integers = [] for array in array_list: integers.append(list(map((lambda s: ord(s)), array))) ax.imshow(np.array(integers), cmap=plt.cm.Oranges) else: ax.im...
class CheetahXmlLexer(DelegatingLexer): name = 'XML+Cheetah' aliases = ['xml+cheetah', 'xml+spitfire'] mimetypes = ['application/xml+cheetah', 'application/xml+spitfire'] url = ' version_added = '' def __init__(self, **options): super().__init__(XmlLexer, CheetahLexer, **options)
.parametrize('multi_optimziers, max_iters', [(True, 10), (True, 2), (False, 10), (False, 2)]) def test_one_cycle_runner_hook(multi_optimziers, max_iters): with pytest.raises(AssertionError): OneCycleLrUpdaterHook(max_lr=0.1, by_epoch=True) with pytest.raises(ValueError): OneCycleLrUpdaterHook(ma...
class Input(): def __init__(self, definition: (Definition | None)=None) -> None: self._definition: Definition self._stream: TextIO = None self._options: dict[(str, Any)] = {} self._arguments: dict[(str, Any)] = {} self._interactive: (bool | None) = None if (definition...
class RestrictedImageNet(DataSet): def __init__(self, data_path, **kwargs): name = 'restricted_imagenet' super(RestrictedImageNet, self).__init__(name) self.data_path = data_path self.mean = constants.IMAGENET_MEAN self.std = constants.IMAGENET_STD self.num_classes = ...
class FreshSeedPrioritizerWorklist(SeedScheduler): def __init__(self, manager: 'SeedManager'): self.manager = manager self.fresh = [] self.worklist = dict() def __len__(self) -> int: s = set() for seeds in list(self.worklist.values()): s.update(seeds) ...
.end_to_end() def test_parametrization_in_for_loop_from_decorator(tmp_path, runner): source = '\n import pytask\n\n for i in range(2):\n\n .task(name="deco_task", kwargs={"i": i, "produces": f"out_{i}.txt"})\n def example(produces, i):\n produces.write_text(str(i))\n ' tmp_path...
class TripletMarginLoss(BaseMetricLossFunction): def __init__(self, margin=0.05, swap=False, smooth_loss=False, triplets_per_anchor='all', **kwargs): super().__init__(**kwargs) self.margin = margin self.swap = swap self.smooth_loss = smooth_loss self.triplets_per_anchor = tri...
class AioClient(BaseClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, isasync=True) self._closed = False self._events = {} async def register_event(self, event: str, func: callable, args=None): if (args is None): args = {} if (not...
def test_direct(debug_ctx, debug_trail, extra_policy, trail_select): loader_getter = make_loader_getter(shape=shape(TestField('a', ParamKind.POS_OR_KW, is_required=True), TestField('b', ParamKind.POS_OR_KW, is_required=True)), name_layout=InputNameLayout(crown=InpDictCrown({'a': InpFieldCrown('a'), 'b': InpFieldCro...
def grokverify(input): storageSuccessFlag = True success = True if dsz.file.Exists('tm154d.da', ('%s\\..\\temp' % systemPath)): dsz.ui.Echo('tm154d.da dump file exists ... this should not be here', dsz.ERROR) if dsz.file.Exists('tm154p.da', ('%s\\..\\temp' % systemPath)): dsz.ui.Echo('tm...
class OpenExecutor(ActionExecutor): def __init__(self, close: bool): self.close = close def execute(self, script: Script, state: EnvironmentState, info: ExecutionInfo, char_index, modify=True, in_place=False): current_line = script[0] info.set_current_line(current_line) node = st...
class SDE(abc.ABC): def __init__(self, N): super().__init__() self.N = N def T(self): pass def sde(self, x, t): pass def marginal_prob(self, x, t): pass def prior_sampling(self, rng, shape): pass def prior_logp(self, z): pass def discre...
class TestExactCover(QiskitOptimizationTestCase): def setUp(self): super().setUp() input_file = self.get_resource_path('sample.exactcover') with open(input_file, encoding='utf8') as file: self.list_of_subsets = json.load(file) (self.qubit_op, _) = exact_cover.get_oper...
def _organize_tasks(tasks: list[PTaskWithPath]) -> dict[(Path, list[PTaskWithPath])]: dictionary: dict[(Path, list[PTaskWithPath])] = defaultdict(list) for task in tasks: dictionary[task.path].append(task) sorted_dict = {} for k in sorted(dictionary): sorted_dict[k] = sorted(dictionary[k...
def setUpModule(): global cell, kpts, disp cell = gto.Cell() cell.atom = [['C', [0.0, 0.0, 0.0]], ['C', [1., 1., 1.]]] cell.a = '\n 0., 3., 3.\n 3., 0., 3.\n 3., 3., 0.' cell.basis = [[0, [1.3, 1]], [1, [0.8, 1]]] cell.verbose = 5 cell.pseudo = 'gth-pade' cell.unit = 'bohr' ...
def test(): spi = SPI(1, baudrate=, sck=Pin(14), mosi=Pin(13)) display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17)) display.draw_image('images/RaspberryPiWB128x128.raw', 0, 0, 128, 128) sleep(2) display.draw_image('images/MicroPython128x128.raw', 0, 129, 128, 128) sleep(2) display.draw...
def ext_modules(): if have_c_files: source_extension = 'c' else: source_extension = 'pyx' ext_modules = [Extension('pymssql._mssql', [join('src', 'pymssql', ('_mssql.%s' % source_extension))], extra_compile_args=['-DMSDBLIB'], include_dirs=include_dirs, library_dirs=library_dirs), Extension(...
class ScaledDotAttention(nn.Module): def __init__(self): super(ScaledDotAttention, self).__init__() self.eps = np.finfo(float).eps self.max = torch.finfo().max self.act_fn = nn.Softmax(dim=(- 1)) def forward(self, Query, Key, Value, mask=None): hidden_size = Key.size()[1]...
def is_simple_literal(t: ProperType) -> bool: if isinstance(t, LiteralType): return (t.fallback.type.is_enum or (t.fallback.type.fullname == 'builtins.str')) if isinstance(t, Instance): return ((t.last_known_value is not None) and isinstance(t.last_known_value.value, str)) return False
class PenParameterItem(GroupParameterItem): def __init__(self, param, depth): self.defaultBtn = self.makeDefaultButton() super().__init__(param, depth) self.itemWidget = QtWidgets.QWidget() layout = QtWidgets.QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout....
(cc=STDCALL, params={'hWnd': HWND, 'lpdwProcessId': LPDWORD}) def hook_GetWindowThreadProcessId(ql: Qiling, address: int, params): target = params['hWnd'] if ((target == ql.os.profile.getint('KERNEL', 'pid')) or (target == ql.os.profile.getint('KERNEL', 'shell_pid'))): pid = ql.os.profile.getint('KERNEL...
class Effect6720(BaseEffect): type = 'passive' def handler(fit, src, context, projectionRange, **kwargs): fit.drones.filteredItemBoost((lambda mod: mod.item.requiresSkill('Drones')), 'shieldBonus', src.getModifiedItemAttr('shipBonusMC'), skill='Minmatar Cruiser', **kwargs) fit.drones.filteredIte...
class Isotope(Molecule): def __init__(self, molecule_name, isotope, isotope_name='', abundance=None, **kwargs): super(Isotope, self).__init__(name=molecule_name, **kwargs) if (not isinstance(isotope, int)): raise TypeError('Wrong format for isotope {0}: expected int, got {1}'.format(isot...
def render_pep8_errors_e116(msg, _node, source_lines=None): line = msg.line curr_idx = (len(source_lines[(line - 1)]) - len(source_lines[(line - 1)].lstrip())) (yield from render_context((line - 2), line, source_lines)) (yield (line, slice(0, curr_idx), LineType.ERROR, source_lines[(line - 1)])) (yi...
('pypyr.steps.filewriteyaml.Path') def test_filewriteyaml_pass_with_empty_payload(mock_path): context = Context({'k1': 'v1', 'fileWriteYaml': {'path': '/arb/blah', 'payload': ''}}) with io.StringIO() as out_text: with patch('pypyr.steps.filewriteyaml.open', mock_open()) as mock_output: mock_...
class TestBatchNormFoldToScale(): (autouse=True) def clear_sessions(self): tf.keras.backend.clear_session() (yield) (autouse=True) def set_random_seed(self): tf.compat.v1.reset_default_graph() tf.compat.v1.set_random_seed(43) if (version.parse(tf.version.VERSION) ...
def setUpModule(): global cell, auxcell, auxcell1, cell_sr, auxcell_sr, basis, auxbasis, kpts, nkpts basis = '\n He S\n 38.00 0.05\n 5.00 0.25\n 0.20 0.60\n He S\n 0.25 1.00\n He P\n 1.27 1.00\n ' auxbasis = '\n He S\n ...
.parametrize(['method', 'kwargs'], [pytest.param('direct', {}, id='direct'), pytest.param('direct', {'sparse': False}, id='direct_dense'), pytest.param('eigen', {'sparse': False}, id='eigen'), pytest.param('power', {'power_tol': 1e-05}, id='power'), pytest.param('iterative-lgmres', {'tol': 1e-07, 'atol': 1e-07}, id='it...
def get_list_of_files(dir_name): all_files = [] try: file_list = os.listdir(dir_name) for entry in file_list: full_path = os.path.join(dir_name, entry) if os.path.isdir(full_path): all_files = (all_files + get_list_of_files(full_path)) else: ...
class SplAtConv2d_dcn(Module): def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=True, radix=2, reduction_factor=4, rectify=False, rectify_avg=False, norm=None, dropblock_prob=0.0, deform_conv_op=None, deformable_groups=1, deform_modulated=False, *...
def _prepareconfig(args: Optional[Union[(List[str], 'os.PathLike[str]')]]=None, plugins: Optional[Sequence[Union[(str, _PluggyPlugin)]]]=None) -> 'Config': if (args is None): args = sys.argv[1:] elif isinstance(args, os.PathLike): args = [os.fspath(args)] elif (not isinstance(args, list)): ...
def _borders_touch(window, x, y, snap_dist): overlap_args = {'x': x, 'y': y} borders = _get_borders(window) for b in borders: if any(((i in [window.edges[0], (window.edges[2] + (2 * window.borderwidth))]) for i in [b[0], b[2]])): if ((window.edges[1] < b[3]) and (window.edges[3] > b[1]))...
def convert_list(items, ids, parent, attr_type, item_func, cdata): LOG.info('Inside convert_list()') output = [] addline = output.append item_name = item_func(parent) if ids: this_id = get_unique_id(parent) for (i, item) in enumerate(items): LOG.info(('Looping inside convert_list...
class COCOClsDataset(Dataset): def __init__(self, img_name_list_path, coco_root, label_file_path, train=True, transform=None, gen_attn=False): img_name_list_path = os.path.join(img_name_list_path, f"{('train' if (train or gen_attn) else 'val')}_id.txt") self.img_name_list = load_img_name_list(img_na...
class SerializerMixin(object): def handle_fk_field(self, obj, field): if isinstance(field, SingleTagField): self._current[field.name] = str(getattr(obj, field.name)) else: super(SerializerMixin, self).handle_fk_field(obj, field) def handle_m2m_field(self, obj, field): ...
def test_class_scope(fixture_path): result = fixture_path.runpytest('-v', '--order-scope=class') result.assert_outcomes(passed=10, failed=0) result.stdout.fnmatch_lines(['test_classes.py::Test1::test_one PASSED', 'test_classes.py::Test1::test_two PASSED', 'test_classes.py::Test2::test_one PASSED', 'test_cla...
def compare_avgplaycount(a1, a2): (a1, a2) = (a1.album, a2.album) if (a1 is None): return (- 1) if (a2 is None): return 1 if (not a1.title): return 1 if (not a2.title): return (- 1) return ((- cmp(a1('~#playcount:avg'), a2('~#playcount:avg'))) or cmpa(a1.date, a2....
class TestBinaryConfusionMatrix(unittest.TestCase): def _test_binary_confusion_matrix_with_input(self, input: torch.Tensor, target: torch.Tensor, normalize: Optional[str]=None) -> None: sklearn_result = torch.tensor(skcm(target, input, labels=[0, 1], normalize=normalize)).to(torch.float32) torch.tes...
class ProductDomain(): def __init__(self, domains): self.vals = list(it.product(*(d.vals for d in domains))) self.shape = ((len(domains),) + domains[0].shape) self.lower = [d.lower for d in domains] self.upper = [d.upper for d in domains] self.dtype = domains[0].dtype
(device=True) def imt_func_o21(value, other_value): return ((((((0 + ((1.0 * value[28]) * other_value[2])) + (((- 1.0) * value[10]) * other_value[31])) + (((- 1.0) * value[2]) * other_value[28])) + (((- 1.0) * value[3]) * other_value[29])) + (((- 1.0) * value[31]) * other_value[10])) + ((1.0 * value[29]) * other_va...
def _tbl_bldr(rows, cols): tblGrid_bldr = a_tblGrid() for i in range(cols): tblGrid_bldr.with_child(a_gridCol()) tbl_bldr = a_tbl().with_nsdecls().with_child(tblGrid_bldr) for i in range(rows): tr_bldr = _tr_bldr(cols) tbl_bldr.with_child(tr_bldr) return tbl_bldr
class Downsample(nn.Module): def __init__(self, in_embed_dim, out_embed_dim, patch_size): super().__init__() self.proj = nn.Conv2d(in_embed_dim, out_embed_dim, kernel_size=patch_size, stride=patch_size) def forward(self, x): x = x.permute(0, 3, 1, 2) x = self.proj(x) x = ...
def _find_line_qubits(size: int, origin: Tuple[(int, int)], rotation: int) -> Tuple[(List[cirq.GridQubit], List[cirq.GridQubit])]: if ((rotation % 90) != 0): raise ValueError('Layout rotation must be a multiple of 90 degrees') def generate(row, col, drow, dcol) -> List[cirq.GridQubit]: return [c...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--input_text', default='input_text.txt') parser.add_argument('--length', default=10, type=int) parser.add_argument('--batch_size', default=1, type=int) parser.add_argument('--temperature', default=1, type=float) parser.add...
class LxClkCoreLookup(gdb.Function): def __init__(self): super(LxClkCoreLookup, self).__init__('lx_clk_core_lookup') def lookup_hlist(self, hlist_head, name): for child in clk_core_for_each_child(hlist_head): if (child['name'].string() == name): return child ...
def ltout(label, n, x, key, im, doinp=False, **kwargs): if doinpprt(label, x, doinp=False, **kwargs): return if (key > 0): thresh = 0.0 else: thresh = (10.0 ** (key - 6)) ntt = ((n * (n + 1)) // 2) if (im > 0): print(('%s, matrix %6d:' % (label, im)), **kwargs) ...
.parametrize('version', [*stdlib_list.short_versions, *stdlib_list.long_versions]) def test_self_consistent(version): list_path = f'lists/{stdlib_list.get_canonical_version(version)}.txt' modules = pkgutil.get_data('stdlib_list', list_path).decode().splitlines() for mod_name in modules: assert stdli...
.parametrize('lower, upper', [(2, np.inf), (2, 5), ((- np.inf), 5)]) .parametrize('op_type', ['icdf', 'rejection']) def test_truncation_discrete_logcdf(op_type, lower, upper): p = 0.7 op = (icdf_geometric if (op_type == 'icdf') else rejection_geometric) x = op(p, name='x') xt = Truncated.dist(x, lower=l...
def gen_srcs_dep_taken_test(): return [gen_br2_srcs_dep_test(5, 'bne', 1, 2, True), gen_br2_srcs_dep_test(4, 'bne', 2, 3, True), gen_br2_srcs_dep_test(3, 'bne', 3, 4, True), gen_br2_srcs_dep_test(2, 'bne', 4, 5, True), gen_br2_srcs_dep_test(1, 'bne', 5, 6, True), gen_br2_srcs_dep_test(0, 'bne', 6, 7, True)]
def convert_bool(value): if isinstance(value, str): if ((value == 'true') or (value == '1')): return True elif ((value == 'false') or (value == '0')): return False elif (value[0] == '$'): return value else: raise ValueError((value + 'is...
class WhisperTokenizerTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = WhisperTokenizer rust_tokenizer_class = WhisperTokenizerFast test_rust_tokenizer = True test_sentencepiece = False test_seq2seq = False def setUp(self): super().setUp() tokenizer = WhisperToken...
.parametrize('reverse', (False, True)) def test_measurable_join_interdependent(reverse): x = pt.random.normal(name='x') y_rvs = [] prev_rv = x for i in range(3): next_rv = pt.random.normal((prev_rv + 1), name=f'y{i}', size=(1, 2)) y_rvs.append(next_rv) prev_rv = next_rv if re...
def main(): enhance_print() coords = symbols('x y z') (ex, ey, ez, grad) = MV.setup('ex ey ez', metric='[1,1,1]', coords=coords) mfvar = (u, v) = symbols('u v') eu = (ex + ey) ev = (ex - ey) (eu_r, ev_r) = ReciprocalFrame([eu, ev]) oprint('Frame', (eu, ev), 'Reciprocal Frame', (eu_r, ev_...
def _timed_hash_bucket(input: HashBucketInput): task_id = get_current_ray_task_id() worker_id = get_current_ray_worker_id() with (memray.Tracker(f'hash_bucket_{worker_id}_{task_id}.bin') if input.enable_profiler else nullcontext()): (delta_file_envelope_groups, total_record_count, total_size_bytes) ...
class LWLBoxActor(BaseActor): def __init__(self, net, objective, loss_weight=None): super().__init__(net, objective) if (loss_weight is None): loss_weight = {'segm': 1.0} self.loss_weight = loss_weight def __call__(self, data): train_imgs = data['train_images'] ...
def test_hypersphere_log_exp_maps(sphere_dim): sphere = HyperSphere(dim=sphere_dim) pt_a = sphere.project(torch.randn((sphere_dim + 1))) pt_b = sphere.project(torch.randn((sphere_dim + 1))) log_ab = sphere.log_map(pt_a, pt_b) assert torch.allclose(log_ab, sphere.to_tangent(pt_a, log_ab)), 'log map n...
class PyreTypeChecker(TypeChecker): def name(self) -> str: return 'pyre' def install(self) -> bool: try: run(f'{sys.executable} -m pip install pyre-check --upgrade', check=True, shell=True) pyre_config = '{"site_package_search_strategy": "pep561", "source_directories": ["...
def get_optimizer(cfg: DictConfig, model: nn.Module) -> Tuple[(Optimizer, Optional[LambdaLR])]: args = dict(cfg[__key__].args) args = {str(k).lower(): v for (k, v) in args.items()} optimizer = eval(f'{cfg[__key__].version}') param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'Layer...
def on_error(stop_on_error: bool, exception: BaseException, package: str) -> None: if isinstance(exception, KeyboardInterrupt): logger.info(('Cancelling, all downloads are forcibly stopped, data may be ' + 'corrupted.')) elif (isinstance(exception, TypeError) or isinstance(exception, ValueError)): ...
class _GenericOpMixin(): def op_numpy(self, *args): raise NotImplementedError atol = 1e-10 rtol = 1e-07 shapes = [] bad_shapes = [] specialisations = [] def generate_mathematically_correct(self, metafunc): parameters = ((['op'] + [x for x in metafunc.fixturenames if x.startsw...
def handle_holding_registers(client): _logger.info('### write holding register and read holding registers') client.write_register(1, 10, slave=SLAVE) rr = client.read_holding_registers(1, 1, slave=SLAVE) assert (not rr.isError()) assert (rr.registers[0] == 10) client.write_registers(1, ([10] * 8...
def open_with_os(path): sys = platform.system() if (sys == 'Darwin'): os.system(('open "%s"' % path)) elif (sys == 'Windows'): os.startfile(path) elif (sys == 'Linux'): os.system(('evince "%s"' % path)) else: raise NotImplementedError(('Unable to open files in this pa...
def fix_missing_fields(ds: Dataset) -> Dataset: ds = ds.drop_vars('call_genotype_phased') ds = ds.drop_vars('variant_filter') ds = ds.drop_vars('filter_id') del ds.attrs['filters'] del ds.attrs['max_alt_alleles_seen'] del ds.attrs['vcf_zarr_version'] del ds.attrs['vcf_header'] for var in...
def test_InterHand3D_dataset(): dataset = 'InterHand3DDataset' dataset_info = Config.fromfile('configs/_base_/datasets/interhand3d.py').dataset_info dataset_class = DATASETS.get(dataset) channel_cfg = dict(num_output_channels=42, dataset_joints=42, dataset_channel=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,...
class BaseModel(torch.nn.Module): def name(self): return 'BaseModel' def initialize(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.Tensor = (torch.cuda.FloatTensor if self.gpu_ids else torch.Tensor) self.save_dir = os.path.jo...
def test_check_cask(bf, caplog, tmp_path): os.chdir(tmp_path) if (not brew_file.is_mac()): with pytest.raises(RuntimeError) as excinfo: bf.check_cask() assert (str(excinfo.value) == 'Cask is not available on Linux!') return bf.check_cask() assert ('# Starting to c...
def clean_duplicates_mro(sequences: list[list[ClassDef]], cls: ClassDef, context: (InferenceContext | None)) -> list[list[ClassDef]]: for sequence in sequences: seen = set() for node in sequence: lineno_and_qname = (node.lineno, node.qname()) if (lineno_and_qname in seen): ...
def subdispatch_mediatortask(chain_state: ChainState, state_change: StateChange, token_network_address: TokenNetworkAddress, secrethash: SecretHash) -> TransitionResult[ChainState]: block_number = chain_state.block_number block_hash = chain_state.block_hash sub_task = chain_state.payment_mapping.secrethashe...
.parametrize('data, msg', [(b'\x80\n', 'invalid utf-8'), (b'\n', 'invalid json'), (b'{"is this invalid json?": true\n', 'invalid json'), (b'{"valid json without args": true}\n', 'Missing args'), (b'{"args": []}\n', 'Missing target_arg'), (((b'{"args": [], "target_arg": null, "protocol_version": ' + OLD_VERSION) + b'}\n...
class TxsBTCAPPRSpider(TxsBTCSpider): name = 'txs.btc.appr' def __init__(self, **kwargs): super().__init__(**kwargs) self.task_map = dict() self.alpha = float(kwargs.get('alpha', 0.15)) self.epsilon = float(kwargs.get('epsilon', 0.0001)) def start_requests(self): sour...
class ScreenFeatures(collections.namedtuple('ScreenFeatures', ['height_map', 'visibility_map', 'creep', 'power', 'player_relative', 'unit_type', 'unit_density', 'unit_density_aa'])): __slots__ = () def __new__(cls, **kwargs): feats = {} for (name, (scale, type_, palette, clip)) in six.iteritems(...
def test_bind_completion_no_binding(qtmodeltester, cmdutils_stub, config_stub, key_config_stub, configdata_stub, info): model = configmodel.bind('x', info=info) model.set_pattern('') qtmodeltester.check(model) _check_completions(model, {'Commands': [('open', 'open a url', ''), ('q', "Alias for 'quit'", ...
def get_wx_user_info(access_data: dict): openid = access_data.get('openid') access_token = access_data.get('access_token') try: fields = parse.urlencode({'access_token': access_token, 'openid': openid}) url = ' print(url) req = request.Request(url=url, method='GET') r...
def calculate_js_div(R1, R2): subset_overlap = [] for n in range(len(R1)): sim_per_pair = [] for i in range(len(R1[n])): s1 = R1[n][i] s2 = R2[n][i] try: sim = js_divergence(s1, s2) except TypeError: print(s1) ...
class TNSR(): def unfold(tensor, mode): lst = range(0, len(tensor.get_shape().as_list())) return tf.reshape(tensor=tf.transpose(tensor, (([mode] + lst[:mode]) + lst[(mode + 1):])), shape=[tensor.get_shape().as_list()[mode], (- 1)]) def fold(tensor, mode, shape): full_shape = list(shape) ...
class DrawMav(): def __init__(self, state, window): (self.mav_points, self.mav_meshColors) = self.get_points() mav_position = np.array([[state.north], [state.east], [(- state.altitude)]]) R = Euler2Rotation(state.phi, state.theta, state.psi) rotated_points = self.rotate_points(self.m...
def gcd(u, v): from rpython.rlib.rbigint import _v_isub, _v_rshift, SHIFT if (not u.tobool()): return v.abs() if (not v.tobool()): return u.abs() if ((v.sign == (- 1)) and (u.sign == (- 1))): sign = (- 1) else: sign = 1 if ((u.size == 1) and (v.size == 1)): ...
class Section(): def __init__(self, sectPr: CT_SectPr, document_part: DocumentPart): super(Section, self).__init__() self._sectPr = sectPr self._document_part = document_part def bottom_margin(self) -> (Length | None): return self._sectPr.bottom_margin _margin.setter def ...
def test_class_weights(): (X, Y) = make_blobs(n_samples=210, centers=3, random_state=1, cluster_std=3, shuffle=False) X = np.hstack([X, np.ones((X.shape[0], 1))]) (X, Y) = (X[:170], Y[:170]) pbl = MultiClassClf(n_features=3, n_classes=3) svm = OneSlackSSVM(pbl, C=10) svm.fit(X, Y) weights = ...
def test(test_episodes): tf.reset_default_graph() policy_nn = SupervisedPolicy() f = open(relationPath) test_data = f.readlines() f.close() test_num = len(test_data) test_data = test_data[(- test_episodes):] print(len(test_data)) success = 0 saver = tf.train.Saver() with tf.S...
class UtilsSplitStripTest(TestCase): def test_empty(self): split = tag_utils.split_strip(None) self.assertEqual(split, []) split = tag_utils.split_strip('') self.assertEqual(split, []) def test_spaceless(self): split = tag_utils.split_strip('adam,brian') self.asse...
class ClassifiersFactory(AbstractFactory): def add_classifier(self, name, classifier): if isinstance(classifier, Classifier): self[name] = classifier elif (isinstance(classifier, BaseEstimator) and isinstance(classifier, ClassifierMixin)): self[name] = SklearnClassifier(class...
class Accumulator(): def __init__(self): self._embeddings = [] self._filled = False def state(self) -> Dict[(str, torch.Tensor)]: return {'embeddings': self.embeddings} def filled(self) -> bool: return self._filled def set_filled(self): self._filled = True def...