code
stringlengths
281
23.7M
def index() -> pc.Component: return pc.center(pc.vstack(navbar(State), pc.text('Enter a stock symbol', background_image='linear-gradient(271.68deg, #EE756A 0.75%, #756AEE 88.52%)', background_clip='text', font_weight='bold', font_size='2em'), pc.text(State.ticker2, font_family='Silkscreen'), pc.input(on_change=Stat...
class TransfoXLModelTester(): def __init__(self, parent, batch_size=14, seq_length=7, mem_len=30, clamp_len=15, is_training=False, use_labels=True, vocab_size=99, cutoffs=[10, 50, 80], hidden_size=32, d_embed=32, num_attention_heads=4, d_head=8, d_inner=128, div_val=2, num_hidden_layers=5, scope=None, seed=1, eos_t...
def get_configs_from_pipeline_file(): pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() with tf.gfile.GFile(FLAGS.pipeline_config_path, 'r') as f: text_format.Merge(f.read(), pipeline_config) model_config = pipeline_config.model.ssd train_config = pipeline_config.train_config input_co...
def process_data(csv_file): results = [] name = csv_file.split('.')[0] df_file = pd.read_csv(csv_file) num = len(df_file) for i in range(num): json_file = (((name + '_') + str(i)) + '.json') if os.path.exists(json_file): with open(json_file) as f: results....
class UffdOAuth2(BaseOAuth2): name = 'uffd' ACCESS_TOKEN_METHOD = 'POST' REFRESH_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' STATE_PARAMETER = True REDIRECT_STATE = False EXTRA_DATA = [('id', 'id')] def get_user_details(self, response): (fullname, first_name, last_name) = self.ge...
class TestReadmeSample(QiskitChemistryTestCase): def setUp(self): super().setUp() try: from qiskit.chemistry.drivers import PySCFDriver PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to...
def create_H(kaldi_root: Path, fst_dir: Path, disambig_out_units_file: Path, in_labels: str, vocab: Dictionary, blk_sym: str, silence_symbol: Optional[str]) -> (Path, Path, Path): h_graph = (fst_dir / f"H.{in_labels}{(('_' + silence_symbol) if silence_symbol else '')}.fst") h_out_units_file = (fst_dir / f'kaldi...
class EvoqueHtmlLexer(DelegatingLexer): name = 'HTML+Evoque' aliases = ['html+evoque'] filenames = ['*.html'] mimetypes = ['text/html+evoque'] url = ' version_added = '1.1' def __init__(self, **options): super().__init__(HtmlLexer, EvoqueLexer, **options) def analyse_text(text): ...
class Projection(nn.Module): def __init__(self, dim, projection_size, hidden_size): super().__init__() self.net = nn.Sequential(nn.Linear(dim, hidden_size, bias=False), nn.ReLU(inplace=True), nn.Linear(hidden_size, projection_size, bias=False)) def forward(self, x): return self.net(x)
class SignalDispatcher(object): def __init__(self): self._signals = {} def signal_clear(self): for handler_list in self._signals.values(): for handler in handler_list: handler.function = None self._signals = {} def signal_bind(self, signal_name, function, ...
(scope='class') def aviary_testing_model(): test_model_path = get_test_model_path() test_model_runner = os.environ.get('AVIARY_TEST_MODEL_LAUNCH_MODULE_PATH', 'rayllm.backend.server.run').lower() test_model_patch_target = os.environ.get('AVIARY_TEST_VLLM_PATCH_TARGET', test_model_runner) launch_fn = 'ru...
.parametrize(('test_input', 'expected'), [(' ' not a link to a recognized domain to prettify'), (' ' not a link to a list, message or thread'), (' ' not a link to a Discourse thread or category')]) def test_process_pretty_url_invalid(test_input, expected): with pytest.raises(ValueError, match=expected): pep...
class MyType(Type): def __init__(self, thingy): self.thingy = thingy def __eq__(self, other): return ((type(other) == type(self)) and (other.thingy == self.thingy)) def __str__(self): return str(self.thingy) def __repr__(self): return str(self.thingy) def filter(self,...
class ImageList(MutableList): __item_type__ = Image def observe_item(self, item): item = self.__item_type__.coerce(None, item) item._parents = self._parents return item def __setitem__(self, index, value): list.__setitem__(self, index, self.observe_item(value)) self.c...
class _SpecialForm(typing._Final, _root=True): __slots__ = ('_name', '__doc__', '_getitem') def __init__(self, getitem): self._getitem = getitem self._name = getitem.__name__ self.__doc__ = getitem.__doc__ def __getattr__(self, item): if (item in {'__name__', '__qualname__'})...
def _has_main_check(line: str) -> bool: if (line.strip() == ''): return False (keyword, *condition) = line.split() spaceless_condition = ''.join(condition) return ((keyword == 'if') and line.startswith(keyword) and ((spaceless_condition == "__name__=='__main__':") or (spaceless_condition == '__n...
def copy(rpin, rpout, compress=0): log.Log('Regular copying input path {ip} to output path {op}'.format(ip=rpin, op=rpout), log.DEBUG) if (not rpin.lstat()): if rpout.lstat(): rpout.delete() return if rpout.lstat(): if (rpin.isreg() or (not cmp(rpin, rpout))): ...
def plotly_plt(scatters, title, ylabel, output_file, limits=None, show=False, figsize=None): del figsize try: import plotly.graph_objs as go import plotly.io as pio except ImportError: raise SystemExit('Unable to import plotly, install with: pip install pandas plotly') fig = go.F...
def test_get_recompute(verbose=True, *args, **kwargs): s = load_spec(getTestFile('CO_Tgas1500K_mole_fraction0.01.spec'), binary=True) assert (s.get_vars() == ['abscoeff']) assert s.conditions['thermal_equilibrium'] assert (set(get_recompute(s, ['radiance_noslit'])) == set(('radiance_noslit', 'abscoeff')...
class GroupBox(_GroupBase): orientations = base.ORIENTATION_HORIZONTAL defaults = [('block_highlight_text_color', None, 'Selected group font colour'), ('active', 'FFFFFF', 'Active group font colour'), ('inactive', '404040', 'Inactive group font colour'), ('highlight_method', 'border', "Method of highlighting ('...
class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() self.action_repeat = max(1, int(((0.5 * state_dim) // action_dim))) action_dim = (action_dim * self.action_repeat) self.l1 = nn.Linear((state_dim + action_dim), 400) self.l2 = n...
class RelativePositionGraph(object): def __init__(self, stopword_ids, tokenizer): self.stopword_ids = stopword_ids self.tokenizer = tokenizer self.word2id = self.tokenizer.get_vocab() def update_node_dict(self, b, new_sentence): if (str(new_sentence) not in self.sentence2id[b]): ...
_fixtures(WebFixture, SqlAlchemyFixture, OptimisticConcurrencyWithAjaxFixture) def test_optimistic_concurrency_with_ajax(web_fixture, sql_alchemy_fixture, concurrency_fixture): fixture = concurrency_fixture with sql_alchemy_fixture.persistent_test_classes(fixture.ModelObject): model_object = fixture.mod...
def test_no_capture_preserves_custom_excepthook(testdir): testdir.makepyfile('\n import pytest\n import sys\n from pytestqt.qt_compat import qt_api\n\n def custom_excepthook(*args):\n sys.__excepthook__(*args)\n\n sys.excepthook = custom_excepthook\n\n .qt_no_exc...
class Migration(migrations.Migration): dependencies = [('adserver', '0053_add_regiontopic_index')] operations = [migrations.AddField(model_name='publisherpayout', name='end_date', field=models.DateField(help_text='Last day of paid period', null=True, verbose_name='End Date')), migrations.AddField(model_name='pu...
class CreateSignatureViewTest(TestCase): def setUpTestData(cls): add_default_data() def test_CreateSignaturePOSTOk(self): data = {'first_name': 'Alan', 'last_name': 'John', 'email': '', 'phone': '', 'subscribed_to_mailinglist': False} petition = Petition.objects.filter(published=True).fi...
class MultiLineFormatter(logging.Formatter): def __init__(self, fmt): super().__init__(fmt) match = _re.search('%\\(levelname\\)-(\\d+)s', fmt) self.level_length = (int(match.group(1)) if match else 0) def format(self, record): original = super().format(record) lines = or...
class OpenFitInNewTab(ContextMenuSingle): def __init__(self): self.mainFrame = gui.mainFrame.MainFrame.getInstance() def display(self, callingWindow, srcContext, mainItem): if (srcContext not in ('projectedFit', 'commandFit', 'graphFitListMisc', 'graphTgtListMisc')): return False ...
def main(): enhance_print() basic_multivector_operations() check_generalized_BAC_CAB_formulas() derivatives_in_rectangular_coordinates() derivatives_in_spherical_coordinates() rounding_numerical_components() conformal_representations_of_circles_lines_spheres_and_planes() properties_of_ge...
def run_test(case, m): m.elaborate() m.apply(BehavioralRTLIRGenPass(m)) m.apply(BehavioralRTLIRTypeCheckPass(m)) visitor = YosysBehavioralRTLIRToVVisitorL2((lambda x: (x in verilog_reserved))) upblks = m.get_metadata(BehavioralRTLIRGenPass.rtlir_upblks) m_all_upblks = m.get_update_blocks() a...
def init_guess_by_chkfile(cell, chkfile_name, project=None, kpt=None): from pyscf import gto (chk_cell, scf_rec) = chkfile.load_scf(chkfile_name) if (project is None): project = (not gto.same_basis_set(chk_cell, cell)) mo = scf_rec['mo_coeff'] mo_occ = scf_rec['mo_occ'] if (kpt is None):...
class Bookmarks(SongsMenuPlugin): PLUGIN_ID = 'Go to Bookmark' PLUGIN_NAME = _('Go to Bookmark') PLUGIN_DESC = _('Manages bookmarks in the selected files.') PLUGIN_ICON = Icons.GO_JUMP plugin_handles = any_song(has_bookmark) def __init__(self, songs, *args, **kwargs): super().__init__(so...
class AttendeeTicket(): id: strawberry.ID hashid: strawberry.ID name: Optional[str] email: Optional[str] secret: str variation: Optional[strawberry.ID] item: TicketItem _conference: strawberry.Private[Conference] _data: strawberry.Private[Any] def role(self, info: Info) -> (Confe...
class SparseMaxPool(SparseModule): def __init__(self, ndim, kernel_size, stride=1, padding=0, dilation=1, subm=False): super(SparseMaxPool, self).__init__() if (not isinstance(kernel_size, (list, tuple))): kernel_size = ([kernel_size] * ndim) if (not isinstance(stride, (list, tup...
class TestProposers(unittest.TestCase): def setUp(self) -> None: topology = Topology(world_size=2, compute_device='cuda') self.enumerator = EmbeddingEnumerator(topology=topology, batch_size=BATCH_SIZE) self.greedy_proposer = GreedyProposer() self.uniform_proposer = UniformProposer() ...
def test_connect_wr_As_wr_x_conn_At_disjoint(): class Top(ComponentLevel3): def construct(s): s.x = Wire(Bits24) s.A = Wire(Bits32) connect(s.x, s.A[8:32]) def up_wr_As(): s.A[0:4] = Bits4(15) def up_wr_x(): s.x = Bi...
class BaseSignalExpr(): def __init__(s, rtype): assert isinstance(rtype, rt.BaseRTLIRType), f'non-RTLIR type {rtype} encountered!' s.rtype = rtype def get_rtype(s): return s.rtype def __eq__(s, other): return ((type(s) is type(other)) and (s.rtype == other.rtype)) def __h...
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() fileMenu = QMenu('&File', self) newAction = fileMenu.addAction('&New...') newAction.setShortcut('Ctrl+N') self.printAction = fileMenu.addAction('&Print...', self.printFile) self.prin...
class RHCPEnv(CEnv): def __init__(self): super().__init__() self.agent_names = ['agent1', 'agent2', 'agent3'] def prepare(self): super().prepare() self.lord = self.agent_names[self.get_current_idx()] self.controller = self.lord def curr_player(self): return se...
def check_haskell_requirements(): if (which('ghc') is None): print('GHC is not installed!\n') return False if (which('cabal') is None): print('cabal is not installed!\n') return False if (which('c2hs') is None): print('c2hs is not installed!\n') return False ...
def get_SVHN(augment, dataroot, download): image_shape = (32, 32, 3) num_classes = 10 if augment: transformations = [transforms.RandomAffine(0, translate=(0.1, 0.1))] else: transformations = [] transformations.extend([transforms.ToTensor(), preprocess]) train_transform = transfor...
def test_object(): object1 = xodr.Object(s=10.0, t=(- 2), dynamic=xodr.Dynamic.no, orientation=xodr.Orientation.positive, zOffset=0.0, id='1', height=1.0, Type=xodr.ObjectType.pole) object2 = xodr.Object(s=20.0, t=(- 2), dynamic=xodr.Dynamic.no, orientation=xodr.Orientation.positive, zOffset=0.0, height=10, id=...
def mol_transform(mols, model, prop, largest_molecule_len, alphabet, upperbound_dr, lr_dream, dreaming_parameters, plot=False): for (i, mol) in enumerate(mols): mol = torch.reshape(mol, (1, mol.shape[0], mol.shape[1])) (track_prop, track_mol, percent_valid_interm, track_loss, epoch_transformed) = dr...
def test_gaussian_solvent_template(tmpdir, water): with tmpdir.as_cwd(): charge_engine = DDECCharges() solvent_settings = charge_engine._get_calculation_settings() task = AtomicInput(molecule=water.to_qcschema(), driver='energy', model={'method': 'b3lyp-d3bj', 'basis': '6-311G'}, keywords=so...
class TestSimpleColumns(BaseTestColumns): def test_SimpleColumnInt64(self) -> None: data = [1, 2, None, 3, 4, None] col = infer_column(data) self.assertEqual(col[0], 1) self.assertEqual(col[1], 2) self.assertEqual(col[3], 3) self.assertEqual(col[4], 4) self.as...
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))...
class ReversibleBlock(nn.Module): def __init__(self, fm, gm): super(ReversibleBlock, self).__init__() self.gm = gm self.fm = fm self.rev_funct = ReversibleBlockFunction.apply def forward(self, x): assert ((x.shape[1] % 2) == 0) params = ([w for w in self.fm.parame...
def ql_syscall_connect_attach(ql: Qiling, nd, pid, chid, index, flags, *args, **kw): assert ((nd, flags) == (ND_LOCAL_NODE, connect_attach_flags['_NTO_COF_CLOEXEC'])), 'syscall_connect_attach parameters are wrong' ql.log.debug(f'syscall_connect_attach(nd = ND_LOCAL_NODE, pid = {pid}, chid = {chid}, index = 0x{i...
() ('--random-seed', envvar='SEED', default=0) ('--test-on-gt', type=bool, default=True) ('--only-test', type=bool, default=False) ('--overfit', type=bool, default=False) ('--fusion', type=click.Choice(choices=['none', 'avg']), default='none') ('--weighted-aggregation', type=bool, default=True) def main(random_seed, te...
class WildernessExit(DefaultExit): def wilderness(self): return self.location.wilderness def mapprovider(self): return self.wilderness.mapprovider def at_traverse_coordinates(self, traversing_object, current_coordinates, new_coordinates): return True def at_traverse(self, travers...
def attach(parser): add_input(parser, pages=False) parser.add_argument('--output', '-o', required=True, type=Path, help='Target path for the new document') parser.add_argument('--rows', '-r', type=int, required=True, help='Number of rows (horizontal tiles)') parser.add_argument('--cols', '-c', type=int,...
def test_add_ord_range_2() -> None: assert (add_ord_range([(1, 2), (11, 12)], (5, 6)) == [(1, 2), (5, 6), (11, 12)]) assert (add_ord_range([(1, 2), (11, 12)], (3, 6)) == [(1, 6), (11, 12)]) assert (add_ord_range([(1, 2), (11, 12)], (2, 6)) == [(1, 6), (11, 12)]) assert (add_ord_range([(1, 2), (11, 12)],...
class LocationLimit(IntEnum): __slots__ = () MIN_CHAT_LOCATION_ADDRESS = 1 MAX_CHAT_LOCATION_ADDRESS = 64 HORIZONTAL_ACCURACY = 1500 MIN_HEADING = 1 MAX_HEADING = 360 MIN_LIVE_PERIOD = 60 MAX_LIVE_PERIOD = 86400 MIN_PROXIMITY_ALERT_RADIUS = 1 MAX_PROXIMITY_ALERT_RADIUS = 100000
class UtilRegexHandler(BaseHandler): async def get(self): Rtv = {} try: data = self.get_argument('data', '') p = self.get_argument('p', '') temp = {} ds = re.findall(p, data, re.IGNORECASE) for cnt in range(0, len(ds)): temp...
def version_info(): import importlib def update_version_info(version_info, library): if importlib.util.find_spec(library): version = importlib.import_module(library).__version__ else: version = 'not installed' version_info[library] = version version_info = {'p...
def _create_selecsls(variant, pretrained, **kwargs): cfg = {} feature_info = [dict(num_chs=32, reduction=2, module='stem.2')] if variant.startswith('selecsls42'): cfg['block'] = SelecSLSBlock cfg['features'] = [(32, 0, 64, 64, True, 2), (64, 64, 64, 128, False, 1), (128, 0, 144, 144, True, 2...
class ModelHandler(object): def __init__(self, config): self._train_loss = AverageMeter() self._dev_loss = AverageMeter() if (config['task_type'] == 'classification'): self._train_metrics = {'nloss': AverageMeter(), 'acc': AverageMeter()} self._dev_metrics = {'nloss':...
def _migrate_v21(data: dict) -> dict: game_modifications = data['game_modifications'] for game in game_modifications: game_name = game['game'] if (game_name != 'dread'): continue dock_weakness = game.get('dock_weakness') if (dock_weakness is None): continu...
class WizardOTPDialogBase(WizardDialog): def get_otp(self): otp = self.ids.otp.text if (len(otp) != 6): return try: return int(otp) except: return def on_text(self, dt): self.ids.next.disabled = (self.get_otp() is None) def on_enter...
class BasicBlock3d(nn.Module): expansion = 1 def __init__(self, inplanes, planes, spatial_stride=1, temporal_stride=1, dilation=1, downsample=None, style='pytorch', inflate=True, inflate_style='3x1x1', non_local=False, non_local_cfg=dict(), conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='BN3d'), act_cfg=dict(...
class OptionSchema(marshmallow.Schema): param_decls = OptionNameField(data_key='name', metadata={'description': 'Name of the option. Usually prefixed with - or --.'}) type = TypeField(metadata={'description': f"Name of the type. {', '.join(TYPES)} accepted."}) is_flag = fields.Boolean(default=False, metadat...
def test_render_debug_better_error_message_recursion_error() -> None: io = BufferedIO() io.set_verbosity(Verbosity.DEBUG) try: recursion.recursion_error() except RecursionError as e: trace = ExceptionTrace(e) lineno = 83 trace.render(io) expected = f'''^ Stack trace: \d+ ...
class ElixirOpenIdConnect(OpenIdConnectAuth): name = 'elixir' OIDC_ENDPOINT = ' EXTRA_DATA = [('expires_in', 'expires_in', True), ('refresh_token', 'refresh_token', True), ('id_token', 'id_token', True), ('other_tokens', 'other_tokens', True)] DEFAULT_SCOPE = ['openid', 'email'] JWT_DECODE_OPTIONS =...
def two_way_teleporter_connections(rng: Random, teleporter_database: tuple[(TeleporterHelper, ...)], between_areas: bool) -> TeleporterConnection: if ((len(teleporter_database) % 2) != 0): raise ValueError('Two-way teleporter shuffle, but odd number of teleporters to shuffle.') if between_areas: ...
class GCNLayer(nn.Module): def __init__(self, input_dim: int, output_dim: int, A: torch.Tensor): super(GCNLayer, self).__init__() self.A = A self.BN = nn.BatchNorm1d(input_dim) self.Activition = nn.LeakyReLU() self.sigma1 = torch.nn.Parameter(torch.tensor([0.1], requires_grad...
def logdir2df(logdir): if issubclass(type(logdir), Path): logdir = str(logdir) ea = EventAccumulator(path=logdir) ea.Reload() scalar_tags = ea.Tags()['scalars'] dfs = {} for scalar_tag in scalar_tags: dfs[scalar_tag] = pd.DataFrame(ea.Scalars(scalar_tag), columns=['wall_time', 's...
class FakeStatResult(): def __init__(self, is_windows: bool, user_id: int, group_id: int, initial_time: Optional[float]=None): self.st_mode: int = 0 self.st_ino: Optional[int] = None self.st_dev: int = 0 self.st_nlink: int = 0 self.st_uid: int = user_id self.st_gid: i...
def _init_weights(module, name=None, head_init_scale=1.0): if isinstance(module, nn.Conv2d): trunc_normal_(module.weight, std=0.02) if (module.bias is not None): nn.init.zeros_(module.bias) elif isinstance(module, nn.Linear): trunc_normal_(module.weight, std=0.02) nn....
class UrlFetcher(BinFetcher): def __fetch_impl__(self, bin_info, bin_file): self.app.print('DL {}'.format(bin_file)) if ('url' not in bin_info): raise Exception('Missing URL for bin') download_url = bin_info['url'] self.app.detail(download_url) urllib.request.urlr...
def fold_high_bias_next_conv_qt(activation_is_relu, beta, gamma, weight, bias_curr_layer, bias_prev_layer): curr_layer_bias = bias_curr_layer prev_layer_bias = bias_prev_layer if (not activation_is_relu): absorb_bias = beta else: abs_gamma = np.abs(gamma) absorb_bias = np.maximum...
def get_reorient_poses(env): if env._real: bounds = ((0.15, (- 0.5), (env.TABLE_OFFSET + 0.001)), (0.3, (- 0.35), (env.TABLE_OFFSET + 0.001))) else: bounds = ((0.25, (- 0.55), (env.TABLE_OFFSET + 0.001)), (0.75, (- 0.25), (env.TABLE_OFFSET + 0.001))) if 0: pp.draw_aabb(bounds) XY...
class InitiatorMixin(): address_to_client: dict block_number: BlockNumber def __init__(self): super().__init__() self.used_secrets: Set[Secret] = set() self.processed_secret_request_secrethashes: Set[SecretHash] = set() self.initiated: Set[Secret] = set() def _available_a...
.pydicom def test_copy(): dont_change_string = "don't change me" to_be_changed_string = 'do change me' new_manufacturer = 'george' dataset_to_be_copied = dicom_dataset_from_dict({'Manufacturer': dont_change_string}) dataset_to_be_viewed = dicom_dataset_from_dict({'Manufacturer': to_be_changed_string...
def pooling_type_to_pooling_mode(pooling_type: PoolingType) -> PoolingMode: if (pooling_type.value == PoolingType.SUM.value): return PoolingMode.SUM elif (pooling_type.value == PoolingType.MEAN.value): return PoolingMode.MEAN elif (pooling_type.value == PoolingType.NONE.value): retur...
def eval_one_epoch(cfg, model, dataloader, epoch_id, logger, dist_test=False, save_to_file=False, result_dir=None): result_dir.mkdir(parents=True, exist_ok=True) final_output_dir = ((result_dir / 'final_result') / 'data') if save_to_file: final_output_dir.mkdir(parents=True, exist_ok=True) metri...
def test_majorana_operator_divide(): a = (MajoranaOperator((0, 1, 5), 1.5) + MajoranaOperator((1, 2, 7), (- 0.5))) assert ((a / 2).terms == {(0, 1, 5): 0.75, (1, 2, 7): (- 0.25)}) a /= 2 assert (a.terms == {(0, 1, 5): 0.75, (1, 2, 7): (- 0.25)}) with pytest.raises(TypeError): _ = (a / 'a') ...
def qflags_key(base: Type[sip.simplewrapper], value: _EnumValueType, klass: Type[_EnumValueType]=None) -> str: if (klass is None): klass = value.__class__ if (klass == int): raise TypeError("Can't guess enum class of an int!") if (not value): return qenum_key(base, value, kla...
def generate_texture_mipmaps(target): if (isinstance(target, Texture) and (target.dim == 2) and (target.size[2] > 1)): for i in range(target.size[2]): generate_texture_mipmaps(GfxTextureView(target, layer_range=(i, (i + 1)))) return if isinstance(target, Texture): texture = t...
(Infraction) class InfractionAdmin(admin.ModelAdmin): fieldsets = (('Members', {'fields': ('user', 'actor')}), ('Action', {'fields': ('type', 'hidden', 'active')}), ('Dates', {'fields': ('inserted_at', 'expires_at')}), ('Reason', {'fields': ('reason',)})) readonly_fields = ('user', 'actor', 'type', 'inserted_at...
def model_with_reused_layer(): relu = tf.keras.layers.ReLU() inp = tf.keras.layers.Input(shape=(5,)) x = relu(inp) x = tf.keras.layers.Dense(units=2)(x) x = relu(x) x = tf.keras.layers.Softmax()(x) model = tf.keras.Model(inputs=inp, outputs=x, name='model_with_reused_layer') return model
def given(name: (str | StepParser), converters: (dict[(str, Callable[([str], Any)])] | None)=None, target_fixture: (str | None)=None, stacklevel: int=1) -> Callable[([Callable[(P, T)]], Callable[(P, T)])]: return step(name, GIVEN, converters=converters, target_fixture=target_fixture, stacklevel=stacklevel)
def test(): if (implementation.name != 'circuitpython'): print() print('This demo is for CircuitPython only!') exit() try: cs_pin = DigitalInOut(board.P0_15) dc_pin = DigitalInOut(board.P0_17) rst_pin = DigitalInOut(board.P0_20) spi = SPI(clock=board.P0_24...
class main(list): def __init__(self, campaign, mod, project_id): global campaign_list global module campaign_list = campaign if (mod is not None): module = mod i = cmd_main() i.prompt = (((((('(' + cmd2.ansi.style('Overlord', fg=Fg.RED, bg=None, bold=True,...
class InlineTest(unittest.TestCase): def setUp(self): super().setUp() self.project = testutils.sample_project() self.pycore = self.project.pycore self.mod = testutils.create_module(self.project, 'mod') self.mod2 = testutils.create_module(self.project, 'mod2') def tearDown...
class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, expand_ratio, dilation=1): super(InvertedResidual, self).__init__() self.stride = stride self.use_res_connect = ((self.stride == 1) and (inp == oup)) padding = (2 - stride) if (dilation > 1): ...
def test_td(dataloader, model, loss_fn): size = len(dataloader.dataset) num_batches = len(dataloader) model.eval() (test_loss, correct) = (0, 0) with torch.no_grad(): for batch in dataloader: (X, y) = (batch['images'].contiguous(), batch['targets'].contiguous()) pred ...
def test_system_task_crash_ExceptionGroup() -> None: async def crasher1() -> NoReturn: raise KeyError async def crasher2() -> NoReturn: raise ValueError async def system_task() -> None: async with _core.open_nursery() as nursery: nursery.start_soon(crasher1) n...
def _n(solver, partInfo, subname, shape, retAll=False): if (not solver): if ((not utils.isPlanar(shape)) and (not utils.isCylindricalPlane(shape))): return 'an edge or face with a planar or cylindrical surface' if utils.isDraftWire(partInfo): logger.warn(translate('asm3', 'Us...
class RayRetriever(): def __init__(self): self.initialized = False def create_rag_retriever(self, config, question_encoder_tokenizer, generator_tokenizer, index): if (not self.initialized): self.retriever = RagRetriever(config, question_encoder_tokenizer=question_encoder_tokenizer, g...
class PlPgsqlLexer(PostgresBase, RegexLexer): name = 'PL/pgSQL' aliases = ['plpgsql'] mimetypes = ['text/x-plpgsql'] url = ' version_added = '1.5' flags = re.IGNORECASE tokens = {name: state[:] for (name, state) in PostgresLexer.tokens.items()} for (i, pattern) in enumerate(tokens['root'...
def learn_embeddings(split=10): _data = (args.rescale * utils.load_emb(args.temp_dir, args.data_name, args.pre_train_path, int((args.dimensions / 2)), config['nodes'])) _network = tdata.TensorDataset(t.LongTensor(np.vstack([pickle.load(open((((args.temp_dir + args.data_name) + '_input.p.') + str(i)))) for i in ...
(7) def real_code(source): collector = codeanalyze.ChangeCollector(source) for (start, end, matchgroups) in ignored_regions(source): if (source[start] == '#'): replacement = (' ' * (end - start)) elif ('f' in matchgroups.get('prefix', '').lower()): replacement = None ...
.end_to_end() .parametrize('definition', [" = PythonNode(value=data['dependency'], hash=True)", ": Annotated[Any, PythonNode(value=data['dependency'], hash=True)]"]) def test_task_with_hashed_python_node(runner, tmp_path, definition): source = f''' import json from pathlib import Path from pytask import...
def _parse_panond(fbuf): component_info = {} dict_levels = [component_info] lines = fbuf.read().splitlines() for i in range(0, (len(lines) - 1)): if (lines[i] == ''): continue indent_lvl_1 = ((len(lines[i]) - len(lines[i].lstrip(' '))) // 2) indent_lvl_2 = ((len(lines...
class TwitterShell(Action): def render_prompt(self, prompt): prompt = prompt.strip("'").replace("\\'", "'") for colour in ansi.COLOURS_NAMED: if (('[%s]' % colour) in prompt): prompt = prompt.replace(('[%s]' % colour), ansiFormatter.cmdColourNamed(colour)) prompt ...
class _buffer_reader(): def __init__(self, buffer): self.buffer = buffer def __call__(self, _, position, p_buf, size): c_buf = ctypes.cast(p_buf, ctypes.POINTER((ctypes.c_char * size))) self.buffer.seek(position) self.buffer.readinto(c_buf.contents) return 1
class TextEncoder(torch.nn.Module): def __init__(self, bert_model, word_embedding_dim, num_attention_heads, query_vector_dim, dropout_rate, enable_gpu=True): super(TextEncoder, self).__init__() self.bert_model = bert_model self.dropout_rate = dropout_rate self.multihead_attention = M...
def test_scene_to_pixmap_exporter_default_size_and_margin(view): item1 = BeePixmapItem(QtGui.QImage(100, 100, QtGui.QImage.Format.Format_RGB32)) item1.setPos(QtCore.QPointF(0, 0)) view.scene.addItem(item1) item2 = BeePixmapItem(QtGui.QImage(100, 100, QtGui.QImage.Format.Format_RGB32)) item1.setPos(Q...
.parametrize('username,password', users) .parametrize('project_id', projects) def test_create_email(db, client, username, password, project_id): client.login(username=username, password=password) url = reverse(urlnames['list'], args=[project_id]) data = {'email': '', 'role': 'guest'} response = client.p...
def test_parametrize_with_shared(testdir): testdir.makepyfile("\n import pytest\n from pytest import fixture\n from pytest_describe import behaves_like\n\n def a_duck():\n def it_quacks(sound):\n assert sound == int(sound)\n\n\n .parametrize('foo', (1, 2,...