code
stringlengths
281
23.7M
def test_octahedron(): octahedron = Octahedron(12.0, name='octahedron', color='purple') assert (octahedron.name == 'octahedron') assert (octahedron.__str__() == 'Octahedron octahedron color:purple material:default radius:12.0') assert (octahedron.__repr__() == 'Octahedron') assert (octahedron.radius...
class NetworkDescription(Description): ('NetworkDescription', rus.optional(dict)) (rus.nothing) def __init__(self, d=None): if d: if ((c.RTYPE in d) and (d[c.RTYPE] != c.NETWORK)): raise se.BadParameter(("Cannot create NetworkResource type '%s'" % d[c.RTYPE])) sel...
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer): def __init__(self, cfg: DictConfig, params, fp32_optimizer, fp32_params, **kwargs): super().__init__(cfg.optimizer) self.fp16_params = params self.fp32_optimizer = fp32_optimizer self.fp32_params = fp32_params ...
class SponsorshipQuerySetTests(TestCase): def setUp(self): self.user = baker.make(settings.AUTH_USER_MODEL) self.contact = baker.make('sponsors.SponsorContact', user=self.user) def test_visible_to_user(self): visible = [baker.make(Sponsorship, submited_by=self.user, status=Sponsorship.AP...
def get_mesh_for_testing(xpts=None, rpts=10, Rpts=10, ypts=15, zpts=15, rcellpts=15, geometry=None, cc_submesh=None): param = pybamm.ParameterValues(values={'Electrode width [m]': 0.4, 'Electrode height [m]': 0.5, 'Negative tab width [m]': 0.1, 'Negative tab centre y-coordinate [m]': 0.1, 'Negative tab centre z-coo...
def create(feedback, device_uuid): device = Device.objects.get(uuid=device_uuid) schedule_item_id = feedback.validated_data['schedule_item_id'] try: with transaction.atomic(): (text, choices) = ([], []) if feedback.validated_data.get('text'): text = create_tex...
def test_should_follow_specification_comparison(): chain = ['1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-beta.2', '1.0.0-beta.11', '1.0.0-rc.1', '1.0.0', '1.3.7+build'] versions = zip(chain[:(- 1)], chain[1:]) for (low_version, high_version) in versions: assert (compare(low_version, high_version) == (- 1)...
class CustomRouterMixin(CreateDataMixin): router_class = 'rapidsms.router.blocking.BlockingRouter' backends = {} handlers = None def _pre_rapidsms_setup(self): self._RAPIDSMS_HANDLERS = getattr(settings, 'RAPIDSMS_HANDLERS', None) self.set_handlers() self._INSTALLED_BACKENDS = ge...
class BackupDB(ProductionCommand): keyword = 'backupdb' def assemble(self): super().assemble() self.parser.add_argument('-d', '--directory', dest='directory', default='/tmp', help='the directory to back up to') self.parser.add_argument('-U', '--super-user-name', dest='super_user_name', d...
class FollowedBy(ParseElementEnhance): def __init__(self, expr): super().__init__(expr) self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): (_, ret) = self.expr._parse(instring, loc, doActions=doActions) del ret[:] return (loc, ret)
class TreeConstraintsSize(TreeConstraints): def branch(self, spec: TreeSpec) -> TreeSpec: depth = (spec.depth + 1) leaves = (spec.leaves * self.branch_factor) size = (spec.size + leaves) leaf_size = (self.total // leaves) return TreeSpec(depth=depth, size=size, leaves=leaves,...
class BaseOptions(): def __init__(self): self.initialized = False def initialize(self, parser): g_data = parser.add_argument_group('Data') g_data.add_argument('--dataset_path', type=str, default='/BS/xxie-3/static00/newdata', help='path to dataset') g_data.add_argument('--exp_nam...
def draw_plot(model, train_x, train_y, test_x, test_y, inducing_x, inducing_f, ax, color, show_legend=False): inducing_x = inducing_x.detach().cpu() inducing_f = inducing_f.detach().cpu() (train_x, train_y) = (train_x.cpu().squeeze((- 1)), train_y.cpu().squeeze((- 1))) (test_x, test_y) = (test_x.cpu().s...
def when_program_starts_5(self): self.wait(3.0) self.add_value_to_list('elle', 'bob') if ((5.0 % 'NO TRANSLATION: data_lengthoflist') > 4): self.create_clone_of('NO TRANSLATION: control_create_clone_of_menu') self.create_clone_of('NO TRANSLATION: control_create_clone_of_menu')
class HallucinationOrigin(nn.Module): def __init__(self, scala=8, features=64, n_residual_blocks=9, big_short_connect=False, output_channel=1): super(HallucinationOrigin, self).__init__() self.n_residual_blocks = n_residual_blocks self.scala = scala self.connect = big_short_connect ...
class ResNet18(Module): def __init__(self): super(ResNet18, self).__init__() self.conv1 = Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.ratl = Rational(approx_func='relu', cuda=False) se...
class MixedInt8TestPipeline(BaseMixedInt8Test): def setUp(self): super().setUp() def tearDown(self): del self.pipe gc.collect() torch.cuda.empty_cache() def test_pipeline(self): self.pipe = pipeline('text-generation', model=self.model_name, model_kwargs={'device_map':...
class RequestInterceptor(QWebEngineUrlRequestInterceptor): def __init__(self, parent=None): super().__init__(parent) self._resource_types = {QWebEngineUrlRequestInfo.ResourceType.ResourceTypeMainFrame: interceptors.ResourceType.main_frame, QWebEngineUrlRequestInfo.ResourceType.ResourceTypeSubFrame: ...
def unlinearize_term(index, n_orbitals): if (not index): return () elif (0 < index < (1 + (n_orbitals ** 2))): shift = 1 new_index = (index - shift) q = (new_index // n_orbitals) p = (new_index - (q * n_orbitals)) assert (index == ((shift + p) + (q * n_orbitals)))...
class NetworkBlock(nn.Module): def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0, constr_activation=None): super(NetworkBlock, self).__init__() self.constr_activation = constr_activation self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, str...
def simplex_projection(v, b=1): v = np.asarray(v) p = len(v) v = ((v > 0) * v) u = np.sort(v)[::(- 1)] sv = np.cumsum(u) rho = np.where((u > ((sv - b) / np.arange(1, (p + 1)))))[0][(- 1)] theta = np.max([0, ((sv[rho] - b) / (rho + 1))]) w = (v - theta) w[(w < 0)] = 0 return w
def main(): parser = argparse.ArgumentParser() parser.add_argument('--input_dir', help='Location of LLaMA weights, which contains tokenizer.model and model folders') parser.add_argument('--model_size', choices=['7B', '13B', '30B', '65B', 'tokenizer_only']) parser.add_argument('--output_dir', help='Locat...
def aead_test(backend, cipher_factory, mode_factory, params): if ((mode_factory is GCM) and backend._fips_enabled and (len(params['iv']) != 24)): pytest.skip('Non-96-bit IVs unsupported in FIPS mode.') tag = binascii.unhexlify(params['tag']) mode = mode_factory(binascii.unhexlify(params['iv']), tag,...
def print_table(table: List[List[str]]): col_lens = ([0] * len(table[0])) for row in table: for (i, cell) in enumerate(row): col_lens[i] = max(len(cell), col_lens[i]) formats = [('{0:<%d}' % x) for x in col_lens] for row in table: print(' '.join((formats[i].format(row[i]) for...
class RevUnit(nn.Module): def __init__(self, in_channels, out_channels, stride, bottleneck, preactivate): super(RevUnit, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) body_class = (RevResBottleneck if bottleneck else RevResBlock) if ((not se...
def Darken(color, factor): (r, g, b, a) = color factor = min(max(factor, 0), 1) factor = (1 - factor) r *= factor g *= factor b *= factor r = min(max(r, 0), 255) b = min(max(b, 0), 255) g = min(max(g, 0), 255) return wx.Colour(round(r), round(g), round(b), round(a))
def test_edge_edge_degenerate_second_edge(test, device): p1_h = np.array([[1, 0, 0]]) q1_h = np.array([[0, 1, 0]]) p2_h = np.array([[1, 1, 0]]) q2_h = np.array([[1, 1, 0]]) res = run_closest_point_edge_edge(p1_h, q1_h, p2_h, q2_h, device) st0 = res[0] test.assertAlmostEqual(st0[0], 0.5) ...
class RPCA_gpu(): def __init__(self, D, mu=None, lmbda=None): self.D = D self.S = torch.zeros_like(self.D) self.Y = torch.zeros_like(self.D) self.mu = (mu or (np.prod(self.D.shape) / (4 * self.norm_p(self.D, 2))).item()) self.mu_inv = (1 / self.mu) self.lmbda = (lmbda...
(3, 'tokens', 'where', 'join') def searchItemsRegex(tokens, where=None, join=None, eager=None): if ((not isinstance(tokens, (tuple, list))) or (not all((isinstance(t, str) for t in tokens)))): raise TypeError('Need tuple or list of strings as argument') if (join is None): join = tuple() if (...
.parametrize(('yanked', 'expected_yanked', 'expected_yanked_reason'), [(True, True, ''), (False, False, ''), ('the reason', True, 'the reason'), ('', True, '')]) def test_package_pep592_yanked(yanked: (str | bool), expected_yanked: bool, expected_yanked_reason: str) -> None: package = Package('foo', '1.0', yanked=y...
class ColorTest(unittest.TestCase): def test_constructor_should_accept_integer(self): color = Color(12345) self.assertEqual(12345, color.rgb_val) def test_constructor_should_accept_integer_string(self): color = Color('12345') self.assertEqual(12345, color.rgb_val) def test_co...
class BlogEntry(models.Model): title = models.CharField(max_length=200) summary = models.TextField(blank=True) pub_date = models.DateTimeField() url = models.URLField('URL') feed = models.ForeignKey('Feed', on_delete=models.CASCADE) class Meta(): verbose_name = 'Blog Entry' verbo...
class BlockDataset(torch.utils.data.Dataset): def __init__(self, dataset: torch.utils.data.Dataset, batch_size: int=100, block_size: int=10000) -> None: assert (block_size >= batch_size), 'Block size should be > batch size.' self.block_size = block_size self.batch_size = batch_size s...
def install_pypy(tmp: Path, url: str) -> Path: pypy_tar_bz2 = url.rsplit('/', 1)[(- 1)] extension = '.tar.bz2' assert pypy_tar_bz2.endswith(extension) installation_path = (CIBW_CACHE_PATH / pypy_tar_bz2[:(- len(extension))]) with FileLock((str(installation_path) + '.lock')): if (not installa...
def preprocess(csv_file, json_file): with open(json_file, 'w') as fout: with open(csv_file, 'rb') as fin: lines = csv.reader(fin) for items in lines: text_data = convert_multi_slots_to_single_slots(items[1:]) text_data = clean_str(text_data) ...
class TimeMeter(Meter): def __init__(self, init: int=0, n: int=0, round: Optional[int]=None): self.round = round self.reset(init, n) def reset(self, init=0, n=0): self.init = init self.start = time.time() self.n = n def update(self, val=1): self.n += val d...
class TestVSCFInitialPoint(QiskitNatureTestCase): def setUp(self) -> None: super().setUp() self.vscf_initial_point = VSCFInitialPoint() self.ansatz = Mock(spec=UVCC) self.ansatz.reps = 1 self.excitation_list = [((0,), (1,))] self.ansatz.excitation_list = self.excitati...
.parametrize('method', [CGA.round, pytest.param(CGA.flat, marks=pytest.mark.xfail(raises=AssertionError, reason='gh-100'))]) def test_from_points_construction(cga, method): blades = cga.layout.blades e1 = blades['e1'] e2 = blades['e2'] e3 = blades['e3'] assert (method(cga, e1, e2, e3).mv == method(c...
def windowed_groupby_accumulator(acc, new, diff=None, window=None, agg=None, grouper=None, with_state=False): if ((agg.grouper is None) and isinstance(new, tuple)): (new, grouper) = new else: grouper = None size = GroupbySize(agg.columns, agg.grouper) if (acc is None): acc = {'df...
class AsyncCallbackManagerForLLMRun(AsyncRunManager, LLMManagerMixin): async def on_llm_new_token(self, token: str, **kwargs: Any) -> None: (await _ahandle_event(self.handlers, 'on_llm_new_token', 'ignore_llm', token, run_id=self.run_id, parent_run_id=self.parent_run_id, **kwargs)) async def on_llm_end(...
class MobileHairNetV2(nn.Module): def __init__(self, decode_block=LayerDepwiseDecode, *args, **kwargs): super(MobileHairNetV2, self).__init__() self.mobilenet = mobilenet_v2(*args, **kwargs) self.decode_block = decode_block self.make_layers() self._init_weight() def make_...
class _SklearnSVMMulticlass(_SklearnSVMABC): def __init__(self, training_dataset, test_dataset, datapoints, gamma, multiclass_classifier): super().__init__(training_dataset, test_dataset, datapoints, gamma) self.multiclass_classifier = multiclass_classifier self._qalgo = None def train(s...
def get_summary_and_prune(model: torch.nn.Module, *, max_depth: int, module_args: Optional[Tuple[(object, ...)]]=None, module_kwargs: Optional[Dict[(str, Any)]]=None) -> ModuleSummary: module_summary = get_module_summary(model, module_args=module_args, module_kwargs=module_kwargs) prune_module_summary(module_su...
class ProphetNetTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names: List[str] = ['...
class CustomBenchUsedDistributions(SphinxDirective): required_arguments = 0 def get_list_table(self) -> str: distributions: Dict[(str, str)] = {} for hub_description in BENCHMARK_HUBS: with ZipFile((RELEASE_DATA / f'{hub_description.key}.zip')) as release_zip: index =...
class ResNet(SimpleNet): def __init__(self, block, layers, num_classes=1000, name=None, created_time=None): self.inplanes = 64 super(ResNet, self).__init__(name, created_time) self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) ...
def _union_primary_key_indices(hash_bucket_index: int, df_envelopes_list: List[List[DeltaFileEnvelope]]) -> pa.Table: logger.info(f'[Hash bucket index {hash_bucket_index}] Reading dedupe input for {len(df_envelopes_list)} delta file envelope lists...') hb_tables = [] df_envelopes = [d for dfe_list in df_env...
_fixtures(ReahlSystemFixture, PartyAccountFixture) def test_create_account(reahl_system_fixture, party_account_fixture): fixture = party_account_fixture login_email = '' mailer_stub = fixture.mailer account_management_interface = fixture.account_management_interface account_management_interface.emai...
def test_inheritance_overriden_types_functional_parent(): Parent = namedtuple('Parent', 'a b') class Child(Parent): a: bool c: str assert (get_named_tuple_shape(Child) == Shape(input=InputShape(constructor=Child, kwargs=None, fields=(InputField(type=bool, id='a', default=NoDefault(), is_requ...
class QuantLinear(nn.Module): def __init__(self, in_features, out_features, bias=True, weight_bit=8, bias_bit=32, per_channel=False, quant_mode=False): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.zeros([out_featu...
def prepare_parser(): usage = 'Parser for all scripts.' parser = ArgumentParser(description=usage) parser.add_argument('--G_path', type=str, default=None, help='Path to pre-trained BigGAN checkpoint folder (default: auto-download checkpoint)') parser.add_argument('--A_lr', type=float, default=0.01, help...
class SessionManager(QObject): def __init__(self, base_path, parent=None): super().__init__(parent) self.current: Optional[str] = None self._base_path = base_path self._last_window_session = None self.did_load = False self.save_autosave = throttle.Throttle(self._save_...
def lisp_to_nested_expression(lisp_string): stack: List = [] current_expression: List = [] tokens = lisp_string.split() for token in tokens: while (token[0] == '('): nested_expression: List = [] current_expression.append(nested_expression) stack.append(current...
def gen_src1_dep_taken_test(): return [gen_br2_src1_dep_test(5, 'bne', 7, 1, True), gen_br2_src1_dep_test(4, 'bne', 7, 2, True), gen_br2_src1_dep_test(3, 'bne', 7, 3, True), gen_br2_src1_dep_test(2, 'bne', 7, 4, True), gen_br2_src1_dep_test(1, 'bne', 7, 5, True), gen_br2_src1_dep_test(0, 'bne', 7, 6, True)]
def load_env_from_file(filename): if (not os.path.exists(filename)): raise FileNotFoundError('Environment file {} does not exist.'.format(filename)) with open(filename) as f: for (lineno, line) in enumerate(f): line = line.strip() if ((not line) or line.startswith('#')): ...
class DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10, deconv=None, delinear=None, channel_deconv=None): super(DenseNet, self).__init__() self.growth_rate = growth_rate num_planes = (2 * growth_rate) if (not deconv): s...
def get_data(name): data = [] sents = get_sents(((final_dir + name) + '.txt')) final_data.append(sents) user_files = ['PGN_both', 'PGN_only', 'fast_rl_both', 'fast_rl_only'] for name in user_files: sents = get_sents(((user_dir + name) + '.txt')) user_data.append(sents) agent_file...
class ScarletC(nn.Module): def __init__(self, n_class=1000, input_size=224): super(ScarletC, self).__init__() assert ((input_size % 32) == 0) mb_config = [[3, 32, 5, 2, True], [3, 32, 3, 1, True], [3, 40, 5, 2, True], 'identity', 'identity', [3, 40, 3, 1, False], [6, 80, 7, 2, True], [3, 80,...
def _parse_output(pipe: Optional[IO[bytes]]) -> tuple[(str, list[str])]: failed_tests = [] conformance = '' test_name = '' for line in iter(pipe.readline, b''): line = line.decode('utf-8').strip('\r\n') if (not line): continue if ('Test [' in line): test_n...
class Label(object): def __init__(self, x, y, label_str, anchor='BL', style=None, keep_inside=None, head=None): if (style is None): style = TextStyle() text = qg.QTextDocument() font = style.qt_font if font: text.setDefaultFont(font) color = style.colo...
def check_kill(session): conn = get_database_conn() curs = query_execute_wrapper(conn, query_string='SELECT kill FROM scansweep_metadata WHERE session=?', query_list=[session], no_return=False) kill_data = curs.fetchone() if (kill_data['kill'] == 'True'): return True else: return Fal...
class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, expand_ratio): super(InvertedResidual, self).__init__() self.stride = stride assert (stride in [1, 2]) hidden_dim = round((inp * expand_ratio)) self.use_res_connect = ((self.stride == 1) and (inp == oup))...
def sample_from_model(sample, model, device, categories_num, diffusion): shape = sample['box_cond'].shape model.eval() noisy_batch = {'box': torch.randn(*shape, dtype=torch.float32, device=device), 'cat': ((categories_num - 1) * torch.ones((shape[0], shape[1]), dtype=torch.long, device=device))} for i i...
class RepositoryGCWorker(QueueWorker): def process_queue_item(self, job_details): try: with GlobalLock('LARGE_GARBAGE_COLLECTION', lock_ttl=(REPOSITORY_GC_TIMEOUT + LOCK_TIMEOUT_PADDING)): self._perform_gc(job_details) except LockNotAcquiredException: logger.d...
class PythonFileRunnerTest(unittest.TestCase): def setUp(self): super().setUp() self.project = testutils.sample_project() self.pycore = self.project.pycore def tearDown(self): testutils.remove_project(self.project) super().tearDown() def make_sample_python_file(self, ...
def _test(): import torch pretrained = False models = [channelnet] for model in models: net = model(pretrained=pretrained) net.eval() weight_count = _calc_width(net) print('m={}, {}'.format(model.__name__, weight_count)) assert ((model != channelnet) or (weight_co...
class ItemDependents(wx.Panel): def __init__(self, parent, stuff, item): wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL) self.romanNb = ['0', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] self.skillIdHistory = [] mainSizer = wx.BoxSizer(wx.VERTICAL) sel...
def test_contextmerge_list(): context = Context({'ctx1': 'ctxvalue1', 'ctx2': 'ctxvalue2', 'ctx3': 'ctxvalue3', 'ctx4': [1, 2, 3], 'contextMerge': {'ctx4': ['k1', 'k2', '{ctx3}', True, False, 44]}}) pypyr.steps.contextmerge.run_step(context) assert (context['ctx1'] == 'ctxvalue1') assert (context['ctx2'...
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=DEFAULT_SAVE_DIR, delay=15, downloader_factory=get_best_downloader): to_dir = os.path.abspath(to_dir) zip_name = ('setuptools-%s.zip' % version) url = (download_base + zip_name) saveto = os.path.join(to_dir, zip_name) ...
class FBNetInitBlock(nn.Module): def __init__(self, in_channels, out_channels, bn_eps): super(FBNetInitBlock, self).__init__() self.conv1 = conv3x3_block(in_channels=in_channels, out_channels=out_channels, stride=2, bn_eps=bn_eps) self.conv2 = FBNetUnit(in_channels=out_channels, out_channels...
def test_fixed_shape_convert_variable(): t1 = TensorType('float64', shape=(1, 1)) t2 = TensorType('float64', shape=(1, 1)) assert (t1 == t2) assert (t1.shape == t2.shape) t2_var = t2() res = t2.convert_variable(t2_var) assert (res is t2_var) res = t1.convert_variable(t2_var) assert (...
class TestDIORRR3Det(TestDIORR): def eval(self): r3det = build_whole_network.DetectionNetworkR3Det(cfgs=self.cfgs, is_training=False) all_boxes_r = self.eval_with_plac(img_dir=self.args.img_dir, det_net=r3det, image_ext=self.args.image_ext) imgs = os.listdir(self.args.img_dir) real_t...
def test_cinsk1_control(): cinsk = new_corpse_in_sk1_control(rabi_rotation=(np.pi / 2), azimuthal_angle=0.5, maximum_rabi_rate=(2 * np.pi)) segments = np.vstack((cinsk.amplitude_x, cinsk.amplitude_y, cinsk.detunings, cinsk.durations)).T _segments = np.array([[5., 3.0123195, 0.0, 1.], [(- 5.), (- 3.0123195),...
def test_AssertionError_message(pytester: Pytester) -> None: pytester.makepyfile('\n def test_hello():\n x,y = 1,2\n assert 0, (x,y)\n ') result = pytester.runpytest() result.stdout.fnmatch_lines('\n *def test_hello*\n *assert 0, (x,y)*\n *AssertionError:...
def RegQuery(hive, subkey, searchterms, searchvalues=True, searchkeys=False, haltonerror=False, **kwargs): subkeys = None values = None regdata = GetRegistryQuery(hive, subkey, **kwargs) ret = dict() if (regdata is not None): try: if searchkeys: subkeys = regdata....
class MopidyPlayer(player.Player): def __init__(self): self.playback_started = Event() with mopidy_command(important=True): PLAYER.playback.stop() PLAYER.tracklist.clear() PLAYER.tracklist.set_consume(True) _event('track_playback_started') def _on_...
def test(epoch, checkpoint, data_test, label_test, n_classes): net = ModelFedCon(args.model, args.out_dim, n_classes=n_classes) if (len(args.gpu.split(',')) > 1): net = torch.nn.DataParallel(net, device_ids=[i for i in range(round((len(args.gpu) / 2)))]) model = net.cuda() model.load_state_dict(...
class IBFIGItoIBContractMapper(): def __init__(self, clientId: int=0, host: str='127.0.0.1', port: int=7497): self.logger = ib_logger.getChild(self.__class__.__name__) self.lock = Lock() self.waiting_time = 30 self.action_event_lock = Event() self.wrapper = IBWrapper(self.act...
def renameUser(username, new_name): if (username == new_name): raise Exception('Must give a new username') check = model.user.get_user_or_org(new_name) if (check is not None): raise Exception(('New username %s already exists' % new_name)) existing = model.user.get_user_or_org(username) ...
class SshPw_TestCase(unittest.TestCase): def runTest(self): data1 = F13_SshPwData() data2 = F13_SshPwData() self.assertEqual(data1, data2) self.assertFalse((data1 != data2)) self.assertNotEqual(data1, None) self.assertFalse(data1.isCrypted) self.assertFalse(da...
class SEResNeXt(nn.Module): def __init__(self, channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(224, 224), num_classes=1000): super(SEResNeXt, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() ...
class DeepLabV3PlusDecoder(nn.Module): def __init__(self, encoder_channels, out_channels=256, atrous_rates=(12, 24, 36), output_stride=16): super().__init__() if (output_stride not in {8, 16}): raise ValueError('Output stride should be 8 or 16, got {}.'.format(output_stride)) sel...
def test_convert_variable(): test_type = TensorType(config.floatX, shape=(None, None)) test_var = test_type() test_type2 = TensorType(config.floatX, shape=(1, None)) test_var2 = test_type2() res = test_type.convert_variable(test_var) assert (res is test_var) res = test_type.convert_variable(...
.unit() .parametrize(('expr', 'expected'), [(' true ', True), (' ((((((true)))))) ', True), (' ( ((\t (((true))))) \t \t)', True), ('( true and (((false))))', False), ('not not not not true', True), ('not not not not not true', False)]) def test_...
.skipif((not _aead_supported(AESCCM)), reason='Does not support AESCCM') class TestAESCCM(): .skipif((sys.platform not in {'linux', 'darwin'}), reason='mmap required') def test_data_too_large(self): key = AESCCM.generate_key(128) aesccm = AESCCM(key) nonce = (b'0' * 12) large_dat...
class TMid3Iconv(_TTools): TOOL_NAME = u'mid3iconv' def setUp(self): super(TMid3Iconv, self).setUp() self.filename = get_temp_copy(os.path.join(DATA_DIR, 'silence-44-s.mp3')) def tearDown(self): super(TMid3Iconv, self).tearDown() os.unlink(self.filename) def test_noop(sel...
def swap_network(qubits: Sequence[cirq.Qid], operation: Callable[([int, int, cirq.Qid, cirq.Qid], cirq.OP_TREE)]=(lambda p, q, p_qubit, q_qubit: ()), fermionic: bool=False, offset: bool=False) -> List[cirq.Operation]: n_qubits = len(qubits) order = list(range(n_qubits)) swap_gate = (FSWAP if fermionic else ...
class TestIncrementDisplay(unittest.TestCase): def test_loop_count(self): def some_loop(): for i in range(12): a = 1 profiler = LineProfiler() wrapped = profiler(some_loop) wrapped() show_results(profiler) for_line = list(list(profiler.code...
def markdown_statistics(file_names): total = collections.Counter() for file_name in sorted(file_names): total.update(get_types(file_name)) result = ['|Field|Class|Empty|Count|', '|---|---|---|---|'] for (field, class_, void) in sorted(total, key=str): result.append('|{}|{}|{}|{}|'.format...
class LvmFileSystem(LoopbackFileSystemMixin, FileSystem): type = 'lvm' aliases = ['0x8e', 'lvm2'] guids = ['E6D6D379-F507-44C2-A23C-238F2A3DF928', '79D3D6E6-07F5-C244-A23C-238F2A3DF928'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.vgname = None (depend...
class MergeResolveTestCase(unittest.TestCase): def test_merge_items(self): d = {1: 'foo', 3: 'baz'} localedata.merge(d, {1: 'Foo', 2: 'Bar'}) assert (d == {1: 'Foo', 2: 'Bar', 3: 'baz'}) def test_merge_nested_dict(self): d1 = {'x': {'a': 1, 'b': 2, 'c': 3}} d2 = {'x': {'a...
class OrgAddUserViewTest(TestCase): def setUpTestData(cls): add_default_data() def login(self, name, password=None): self.client.login(username=name, password=(password if password else name)) self.pu = PytitionUser.objects.get(user__username=name) return self.pu def test_Org...
class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='JobListing', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.time...
def parse_args(): parser = argparse.ArgumentParser(description='Upload models to OSS') parser.add_argument('model_zoo', type=str, help='model_zoo input') parser.add_argument('--dst-folder', type=str, default='mmsegmentation/v0.5', help='destination folder') args = parser.parse_args() return args
def _iter_fixes(testcase: DataDrivenTestCase, actual: list[str], *, incremental_step: int) -> Iterator[DataFileFix]: reports_by_line: dict[(tuple[(str, int)], list[tuple[(str, str)]])] = defaultdict(list) for error_line in actual: comment_match = re.match('^(?P<filename>[^:]+):(?P<lineno>\\d+): (?P<seve...
def ddpOrient(node_a: Node, node_b: Node, node_c: Node, graph: Graph, maxPathLength: int, data: ndarray, independence_test_method, alpha: float, sep_sets: Dict[(Tuple[(int, int)], Set[int])], change_flag: bool, bk: (BackgroundKnowledge | None), verbose: bool=False) -> bool: Q = Queue() V = set() e = None ...
def z1_pre_encoder(x, z2, hus=[1024, 1024]): with tf.variable_scope('z1_pre_enc'): (T, F) = x.get_shape().as_list()[1:] x = tf.reshape(x, ((- 1), (T * F))) out = tf.concat([x, z2], axis=(- 1)) for (i, hu) in enumerate(hus): out = fully_connected(out, hu, activation_fn=tf....
class RestrictChatMember(): async def restrict_chat_member(self: 'pyrogram.Client', chat_id: Union[(int, str)], user_id: Union[(int, str)], permissions: 'types.ChatPermissions', until_date: datetime=utils.zero_datetime()) -> 'types.Chat': r = (await self.invoke(raw.functions.channels.EditBanned(channel=(awa...
class TestMakeClass(): .parametrize('ls', [list, tuple]) def test_simple(self, ls): C1 = make_class('C1', ls(['a', 'b'])) class C2(): a = attr.ib() b = attr.ib() assert (C1.__attrs_attrs__ == C2.__attrs_attrs__) def test_dict(self): C1 = make_class('C1...
class Migration(migrations.Migration): dependencies = [('adserver', '0042_add_keyword_impressions')] operations = [migrations.AlterField(model_name='publisher', name='render_pixel', field=models.BooleanField(default=False, help_text='Render ethical-pixel in ad templates. This is needed for users not using the a...