code
stringlengths
281
23.7M
class TaskTestFunction(): def __init__(self) -> None: self.temp_dir: Optional[str] = None self.overrides: Optional[List[str]] = None self.calling_file: Optional[str] = None self.calling_module: Optional[str] = None self.config_path: Optional[str] = None self.config_na...
class Migration(migrations.Migration): initial = True dependencies = [('player', '0001_initial')] operations = [migrations.CreateModel(name='EmojiPack', fields=[('id', models.AutoField(help_text='ID', primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='', max_length=...
class RegressionPredictedVsActualPlot(Metric[ColumnScatterResult]): def __init__(self, options: AnyOptions=None): super().__init__(options=options) def calculate(self, data: InputData) -> ColumnScatterResult: dataset_columns = process_columns(data.current_data, data.column_mapping) targe...
class MockDelegate(QStyledItemDelegate): def __init__(self, parent=None) -> None: super().__init__(parent) self._size = QSize(50, 50) self._max_id = 0 def paint(self, painter, option: QStyleOptionViewItem, index: QModelIndex) -> None: self._max_id = max(int(index.internalPointer(...
class UsersEventsRoles(db.Model): __tablename__ = 'users_events_roles' __table_args__ = (db.UniqueConstraint('user_id', 'event_id', 'role_id', name='uq_uer_user_event_role'),) id = db.Column(db.Integer, primary_key=True) event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'), nu...
def check_server(cli_version: str, server_url: str, quiet: bool=False) -> None: health_response = check_server_health((str(server_url) or '')) if (health_response.status_code == 429): echo_red('Server ratelimit reached. Please wait one minute and try again.') raise SystemExit(1) server_versi...
def test_extractionschemanode_without_type_cannot_be_deserialized() -> None: json = '\n {\n "id": "root_object",\n "description": "Deserialization Example",\n "many": true,\n "attributes": [\n {\n "id": "number_attribute",\n "description": "Des...
class TestFigureTrainingTeiParser(): def test_should_parse_single_token_labelled_training_tei_lines(self): tei_root = _get_training_tei_with_figures([E('figure', E('head', TOKEN_1, E('lb')), '\n', E('figDesc', TOKEN_2, E('lb')), '\n')]) tag_result = get_training_tei_parser().parse_training_tei_to_ta...
def _compare_public_ids(component_configuration: ComponentConfiguration, package_directory: Path) -> None: if (component_configuration.package_type != PackageType.SKILL): return filename = '__init__.py' public_id_in_init = _get_public_id_from_file(component_configuration, package_directory, filename...
class AEATestWrapper(): def __init__(self, name: str='my_aea', components: List[Component]=None): self.components = (components or []) self.name = name self._fake_connection: Optional[FakeConnection] = None self.aea = self.make_aea(self.name, self.components) self._thread = N...
def test_transact_sending_ether_to_nonpayable_function(w3, payable_tester_contract, transact, call): initial_value = call(contract=payable_tester_contract, contract_function='wasCalled') assert (initial_value is False) with pytest.raises(Web3ValidationError): txn_hash = transact(contract=payable_tes...
class PageAboutStoryComposedBlock(AbstractObject): def __init__(self, api=None): super(PageAboutStoryComposedBlock, self).__init__() self._isPageAboutStoryComposedBlock = True self._api = api class Field(AbstractObject.Field): depth = 'depth' entity_ranges = 'entity_range...
def test_by_time(events, cue, ball1, ball2, ball3, cushion): assert (filter_time(events, 4) == [sliding_rolling_transition(ball2, 5), rolling_stationary_transition(ball2, 6), ball_ball_collision(ball1, ball3, 7), sliding_rolling_transition(ball1, 8), sliding_rolling_transition(ball3, 9), rolling_stationary_transiti...
def test_get_timeout_for_common_handshake_exceptions(): common_exc_types = (COMMON_PEER_CONNECTION_EXCEPTIONS + (HandshakeFailure, HandshakeFailureTooManyPeers, MalformedMessage, NoMatchingPeerCapabilities)) for exc_type in common_exc_types: assert (get_timeout_for_failure(exc_type()) <= (60 * 60))
class OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptionsMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsFunnel3dSonificationDefaultinstrumentoptions...
class EmojiExtension(Extension): def __init__(self, *args, **kwargs): self.config = {'emoji_index': [emojione, "Function that returns the desired emoji index. - Default: 'pymdownx.emoji.emojione'"], 'emoji_generator': [to_png, 'Emoji generator method. - Default: pymdownx.emoji.to_png'], 'title': ['short', "...
class PrintSelectorPatternTest(BowlerTestCase): def test_print_selector_pattern(self): node = self.parse_line('x + 1') expected = "arith_expr < 'x' '+' '1' > \n" print_selector_pattern(node) self.assertMultiLineEqual(expected, self.buffer.getvalue()) def test_print_selector_patte...
def test_average_regions_start(): outfile = NamedTemporaryFile(suffix='.npz', prefix='average_region', delete=False) matrix = (ROOT + 'small_test_matrix.cool') bed_file = (ROOT + 'hicAverageRegions/regions_multi.bed') args = '--matrix {} --regions {} -o {} --range 100000 100000 -cb {}'.format(matrix, be...
_os(*metadata.platforms) (MS_XSL, XML_FILE, XSL_FILE) def main(): common.log('MsXsl Beacon') (server, ip, port) = common.serve_web() common.clear_web_cache() new_callback = (' % (ip, port)) common.log(('Updating the callback to %s' % new_callback)) common.patch_regex(XSL_FILE, common.CALLBACK_RE...
def test_empty_search_finds_everything(data_client, es_version, commit_search_cls): cs = commit_search_cls() r = cs.execute() assert (r.hits.total.value == 52) assert ([('elasticsearch_dsl', 40, False), ('test_elasticsearch_dsl', 35, False), ('elasticsearch_dsl/query.py', 19, False), ('test_elasticsearc...
class RCR(Layout): cutlass_layout_a = 'cutlass::layout::RowMajor' cutlass_layout_b = 'cutlass::layout::ColumnMajor' cutlass_layout_c = 'cutlass::layout::RowMajor' stride_a = 'K' stride_b = 'K' stride_c = 'N' args_parser = '\n int64_t a_dim0 = M;\n int64_t a_dim1 = K;\n int64_t b_dim0 = N;...
def version_is_compatible(version: Union[(str, semver.Version)], other: Union[(str, semver.Version)], forgiving: bool=False) -> bool: version_is_semver = True try: if isinstance(version, str): version = semver.Version.parse(version) except ValueError: version_is_semver = forgivin...
.compilertest def test_errorresponse_onemapper_onstatuscode_textformat_contenttype(): _test_errorresponse_onemapper_onstatuscode_textformat_contenttype('503', 'oops', 'text/what') _test_errorresponse_onemapper_onstatuscode_textformat_contenttype('429', '<html>too fast, too furious on host %REQ(:authority)%</htm...
class IEEE802_15_4(object): def __init__(self, ioservers=[]): self.ioservers = [] self.host_socket = None for server in ioservers: self.add_server(server) def add_server(self, ioserver): self.ioservers.append(ioserver) ioserver.register_topic('Peripheral.IEEE8...
class BudgetEntryTestCase(BudgetTestBase): def test_budget_argument_is_skipped(self): with pytest.raises(TypeError) as cm: BudgetEntry(amount=10.0) assert (str(cm.value) == 'BudgetEntry.budget should be a Budget instance, not NoneType') def test_budget_argument_is_none(self): ...
def test_validate_yaml(): validator = Object(properties=Integer()) text = 'a: 123\nb: 456\n' value = validate_yaml(text, validator=validator) assert (value == {'a': 123, 'b': 456}) validator = Object(properties=Integer()) text = 'a: 123\nb: abc\n' with pytest.raises(ValidationError) as exc_i...
def cached_render(fn): (fn) def render(self, region, context=None): key = (self.cache_key(region) if self.cache_key else None) if key: result = cache.get(key) if (result is not None): return result result = fn(self, region, context) if key:...
def get_srpm(version): if (version in srpm_cache): return srpm_cache[version] assert (0 == os.system('set -e\n mkdir -p srpm_dir && cd srpm_dir\n export dummy_version={version}\n {script_dir}/generate_qiuck_package\n '.format(script_dir=scriptdir(), version=version))) srpm_path = os.path...
def _find_cast_subexpressions(expression: DataflowObject) -> Iterator[UnaryOperation]: todo = [expression] while (todo and (subexpression := todo.pop())): todo.extend(subexpression) if ((not (isinstance(expression, Assignment) and (expression.destination == subexpression))) and _is_cast(subexpre...
def create_user(date, cognito_id, email_address, character_set_preference): response = table.put_item(Item={'PK': ('USER#' + cognito_id), 'SK': ('USER#' + cognito_id), 'Email address': email_address, 'Date created': date, 'Last login': date, 'Character set preference': character_set_preference, 'User alias': 'Not s...
class bsn_debug_counter_desc_stats_reply(bsn_stats_reply): version = 5 type = 19 stats_type = 65535 experimenter = 6035143 subtype = 13 def __init__(self, xid=None, flags=None, entries=None): if (xid != None): self.xid = xid else: self.xid = None i...
class TrackTestCase(unittest.TestCase): def test_to_xml_method_is_working_properly(self): t = Track() t.enabled = True t.locked = False f = File() f.duration = 34 f.name = 'shot2' f.pathurl = 'file://localhost/home/eoyilmaz/maya/projects/default/data/shot2.mov...
def variate(oid, tag, value, **context): if ((not context['nextFlag']) and (not context['exactMatch'])): return (context['origOid'], tag, context['errorStatus']) if ('settings' not in recordContext): recordContext['settings'] = dict([split(x, '=') for x in split(value, ',')]) if ('vlist'...
class Locals(LimitedTestCase): def passthru(self, *args, **kw): self.results.append((args, kw)) return (args, kw) def setUp(self): self.results = [] super().setUp() def tearDown(self): self.results = [] super().tearDown() def test_assignment(self): ...
class TypeMutualAuthentication(ModelSimple): allowed_values = {('value',): {'MUTUAL_AUTHENTICATION': 'mutual_authentication'}} validations = {} additional_properties_type = None _nullable = False _property def openapi_types(): return {'value': (str,)} _property def discriminator(...
('/chat', methods=['POST']) def chat(): message = request.form['message'] parse = nltk_stanford_parse(message) (response, terms) = question_type(parse) if (response == 'default'): answer = 'Sorry, did you have a question about measurements \n or recipes?\n ' elif (response == '...
def test_asyncio_thread1(): r = [] r.append(asyncio.get_event_loop()) t = threading.Thread(target=append_current_loop, args=(r, False)) t.start() t.join() t = threading.Thread(target=append_current_loop, args=(r, True)) t.start() t.join() r.append(asyncio.get_event_loop()) assert...
def extractSugaminnyjpWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('The Eternal World', 'The Eternal World', 'translated'), ('PRC', 'PRC', 'translated'), ('Loite...
def enable_mxnet(): warn_msg = 'Built-in MXNet support will be removed in Thinc v9. If you need MXNet support in the future, you can transition to using a custom copy of the current MXNetWrapper in your package or project.' warnings.warn(warn_msg, DeprecationWarning) global mxnet, has_mxnet import mxnet...
def execute(mh, options, extra_options, back_end, process_slx=True, process_tests=False): assert isinstance(mh, errors.Message_Handler) assert isinstance(back_end, MISS_HIT_Back_End) try: if options.entry_point: cfg_tree.register_item(mh, pathutil.abspath('.'), options) prj_r...
class AinneveTestMixin(): def setUp(self): super().setUp() self.account.permissions.remove('Developer') self.helmet = create.create_object(Helmet, key='helmet') self.shield = create.create_object(Shield, key='shield') self.armor = create.create_object(ArmorObject, key='armor'...
def validate_deserialize(cls_body): print('Starting process') mqueue = multiprocessing.Queue() proc = multiprocessing.Process(target=client_thread, args=(mqueue,)) proc.start() proc.join() print('Process generated class') message_bytes = mqueue.get() print('Retrieved bytes:', len(message...
def power_spectral_density_von_karman(r0, L0): def func(grid): u = (grid.as_('polar').r + 1e-10) u0 = ((2 * np.pi) / L0) res = ((0.0229 * ((((u ** 2) + (u0 ** 2)) / ((2 * np.pi) ** 2)) ** ((- 11) / 6.0))) * (r0 ** ((- 5) / 3))) res[(u < 1e-09)] = 0 return Field(res, grid) ...
class Required(BranchPattern): def match(self, left: List['Pattern'], collected: List['Pattern']=None) -> Any: collected = ([] if (collected is None) else collected) original_collected = collected original_left = left for pattern in self.children: (matched, left, collecte...
def main(): parser = argparse.ArgumentParser(description='LiteEth Bench on ColorLight 5A-75B') parser.add_argument('--build', action='store_true', help='Build bitstream') parser.add_argument('--load', action='store_true', help='Load bitstream') args = parser.parse_args() soc = BenchSoC() builder...
.parametrize('primitive, hexstr, text, validator_address, expected_signable', ((b'', None, None, (b'\xff' * 20), SignableMessage(b'\x00', (b'\xff' * 20), b'')), (b'', None, None, '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF', SignableMessage(b'\x00', (b'\xff' * 20), b'')), (None, '0x', None, (b'\xff' * 20), SignableMess...
def go_to_goal(goal): global robot_location, robot_rotation d = Distance_compute(robot_location, goal) theta = robot_rotation[2] kl = 1 ka = 4 vx = 0 va = 0 heading = math.atan2((goal[1] - robot_location[1]), (goal[0] - robot_location[0])) err_theta = (heading - theta) if (d > 0....
def test_matcher_set_value_operator(en_vocab): matcher = Matcher(en_vocab) pattern = [{'ORTH': {'IN': ['a', 'the']}, 'OP': '?'}, {'ORTH': 'house'}] matcher.add('DET_HOUSE', [pattern]) doc = Doc(en_vocab, words=['In', 'a', 'house']) matches = matcher(doc) assert (len(matches) == 1) doc = Doc(...
_group.command('remove-model') ('model-id', required=False) _context def remove_model(ctx: click.Context, model_id): es_client = MlClient(ctx.obj['es']) model_ids = MachineLearningClient.get_existing_model_ids(ctx.obj['es']) if (not model_id): model_id = click.prompt('Model ID to remove', type=click...
def test_kronos_devices_list_devices(client: TestClient, with_registered_device: None): from tests.test_database_models import SAMPLE_DEVICE_HID response = client.get('/api/v1/kronos/devices') assert (response.status_code == 200) gateways = response.json()['data'] assert (len(gateways) == 1) ass...
def test_agent_configuration_dump_multipage(): loader = ConfigLoaders.from_package_type(PackageType.AGENT) agent_config = loader.load(Path(CUR_PATH, 'data', 'aea-config.example_multipage.yaml').open()) assert (agent_config.agent_name == 'myagent') assert (agent_config.author == 'fetchai') assert (le...
.parallel(nprocs=3) def test_poisson_mixed_parallel_fieldsplit(): x = poisson_mixed(3, parameters={'ksp_type': 'fgmres', 'pc_type': 'fieldsplit', 'pc_fieldsplit_type': 'schur', 'fieldsplit_schur_fact_type': 'diag', 'fieldsplit_0_ksp_type': 'preonly', 'fieldsplit_1_ksp_type': 'cg', 'fieldsplit_0_pc_type': 'bjacobi',...
def is_azure_chat(kwargs): if (not ('api_config' in kwargs)): return False api_config = kwargs['api_config'] if (not ('api_type' in api_config)): return (os.environ.get('OPENAI_API_TYPE', 'azure') == 'azure-chat') return (('api_type' in api_config) and ('azure-chat' in api_config.get('ap...
class OptionPlotoptionsNetworkgraphSonificationDefaultspeechoptionsMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, ...
class OptionSeriesPyramid3dAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def descriptionFormat(self): return self._config_get(None) def descriptionFormat(self, text: str): s...
def extract_tar_file(path: PathIn, dest: PathIn, *, autodelete: bool=False, content_paths: (Iterable[tarfile.TarInfo] | None)=None) -> None: path = _get_path(path) dest = _get_path(dest) assert_file(path) assert_not_file(dest) make_dirs(dest) with tarfile.TarFile(path, 'r') as file: file...
class FileEntry(): __slots__ = ('path', 'size', 'mtime') def __init__(self, path, stat_cache=None): self.path = path stat_function = (os.stat if (stat_cache is None) else stat_cache.__getitem__) stat = self.stat_regular_file(path, stat_function) self.size = stat.st_size s...
class ButtonMenu(Html.Html): name = 'Button Menu' _option_cls = OptButton.OptionsButtonMenu tag = 'div' def __init__(self, page: primitives.PageModel, record, text: str, icon: Optional[str], width: Optional[tuple], height: Optional[tuple], html_code: Optional[str], tooltip: Optional[str], profile: Optio...
class SimulationConfigPanel(QWidget): simulationConfigurationChanged = Signal() def __init__(self, simulation_model): QWidget.__init__(self) self.setContentsMargins(10, 10, 10, 10) self.__simulation_model = simulation_model def getSimulationModel(self): return self.__simulati...
def get_model(model_type: str) -> BaseEstimator: models_map = {'lr': LinearRegression, 'svc': partial(SVC, kernel='linear')} x = np.random.normal(size=(10, 2)) y = np.random.randint(2, size=(10,)) while (len(set(y)) < 2): y = np.random.randint(2, size=(10,)) model = models_map[model_type]() ...
class OptionPlotoptionsSplineSonificationDefaultinstrumentoptionsPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, fla...
class TestDailyAggQuarterFeatures(): .parametrize('data', datas) .parametrize(['tickers', 'columns', 'agg_day_counts', 'max_back_quarter', 'min_back_quarter'], [(['AAPL', 'TSLA'], ['marketcap'], [100], 10, 0), (['NVDA', 'TSLA'], ['marketcap'], [100, 200], 5, 2), (['AAPL', 'NVDA', 'TSLA', 'WORK'], ['marketcap', ...
class TestPostHooks(): def test_return_raise(self, monkeypatch, tmp_path): with monkeypatch.context() as m: m.setattr(sys, 'argv', ['']) with pytest.raises(_SpockInstantiationError): class FailReturnConfig(): val_1: float = 0.5 ...
class GetBlockBodiesV65Exchange(BaseGetBlockBodiesV65Exchange): _normalizer = GetBlockBodiesNormalizer() tracker_class = GetBlockBodiesTracker _request_command_type = GetBlockBodiesV65 _response_command_type = BlockBodiesV65 async def __call__(self, headers: Sequence[BlockHeaderAPI], timeout: float=...
def test_get_elasticsearch_awards_csv_sources(db): original = VALUE_MAPPINGS['elasticsearch_awards']['filter_function'] VALUE_MAPPINGS['elasticsearch_awards']['filter_function'] = MagicMock(returned_value='') csv_sources = download_generation.get_download_sources({'download_types': ['elasticsearch_awards'],...
class OptionPlotoptionsOrganizationSonificationDefaultspeechoptionsActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(se...
def echo_body(environ: Environ, start_response: StartResponse) -> List[bytes]: status = '200 OK' output = environ['wsgi.input'].read() headers = [('Content-Type', 'text/plain; charset=utf-8'), ('Content-Length', str(len(output)))] start_response(status, headers, None) return [output]
def test_xcom_push(): ctx = FlyteContextManager.current_context() ctx.user_space_params._attrs = {} execution_state = ctx.execution_state.with_params(user_space_params=ctx.user_space_params.new_builder().add_attr('GET_ORIGINAL_TASK', True).add_attr('XCOM_DATA', {}).build()) with FlyteContextManager.with...
def gripper_test(mc): print('Start check IO part of api\n') flag = mc.is_gripper_moving() print('Is gripper moving: {}'.format(flag)) time.sleep(1) mc.set_encoder(7, 2048) time.sleep(3) mc.set_encoder(7, 1300) time.sleep(3) mc.set_gripper_value(2048, 70) time.sleep(5) mc.set_...
('pyscf') .parametrize('fn, geom, charge, mult, ref_energy', BakerTSBm.geom_iter) def test_baker_ts_dimer(fn, geom, charge, mult, ref_energy, results_bag): N_init_dict = make_N_init_dict() calc_kwargs = {'charge': charge, 'mult': mult, 'pal': 2, 'base_name': Path(fn).stem} def calc_getter(): return ...
class Command(BaseCommand): args = '' help = 'Imports practice dispensing status.' def add_arguments(self, parser): parser.add_argument('--filename') parser.add_argument('--date') def handle(self, *args, **options): self.IS_VERBOSE = False if (options['verbosity'] > 1): ...
def test_flags(): instance = HostBase() mac_df = pd.DataFrame.from_dict({'test_col': [1, 2, 4]}) assert (instance._get_flags(mac_df, 'test_col', {0: 'foo', 1: 'baz', 2: 'blah'}, suffix=None, field_name=None) == {'tshark_test_col_foo': 1, 'tshark_test_col_baz': 1, 'tshark_test_col_blah': 1}) mac_df = pd....
class FailingAuthAccessedInRenderer(TestCase): def setUp(self): class AuthAccessingRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, media_type=None, renderer_context=None): request = renderer_context['reques...
(name='generate-bundles') def generate_bundles(): for platform in PLATFORMS: bundle_dir = os.path.join('bundle', platform) if (not os.path.exists(bundle_dir)): os.makedirs(bundle_dir) bundle_file = os.path.join(bundle_dir, BUNDLE_NAME) click.echo('Generating bundle {}'.fo...
class Systray(widget.Systray): _qte_compatibility = True def draw(self): offset = self.padding self.drawer.clear((self.background or self.bar.background)) self.drawer.draw(offsetx=self.offset, offsety=self.offsety, width=self.length) for (pos, icon) in enumerate(self.tray_icons):...
.parametrize('points_shape', [(3,), (3, 10)]) def test_rotate_points(points_shape): points = np.random.random(points_shape) points_rotated = td.Geometry.rotate_points(points=points, axis=(0, 0, 1), angle=(2 * np.pi)) assert np.allclose(points, points_rotated) points_rotated = td.Geometry.rotate_points(p...
class OptionSeriesSolidgaugeSonificationTracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def _check_is_parent_folders_are_aea_projects_recursively() -> None: current = Path('.').resolve() root = Path('/').resolve() home = current.home() while (current not in (home, root)): files = set(map((lambda x: x.name), current.iterdir())) if (DEFAULT_AEA_CONFIG_FILE in files): ...
class OptionSeriesScatter3dSonificationContexttracksMappingGapbetweennotes(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str...
class SysTrayApp(object): WM_NOTIFY = None WNDCLASS = None CLASS_ATOM = None _instance = None def initialize(klass): WM_RESTART = win32gui.RegisterWindowMessage('TaskbarCreated') klass.WM_NOTIFY = (win32con.WM_USER + 1) klass.WNDCLASS = win32gui.WNDCLASS() klass.WNDCL...
def setCbText(txt): txt = wx.TextDataObject(txt) while True: try: if (not wx.TheClipboard.IsOpened()): if wx.TheClipboard.Open(): wx.TheClipboard.SetData(txt) wx.TheClipboard.Close() break pass ...
def _setup_ensemble_experiment(config: ErtConfig, storage: StorageAccessor, args: Namespace, experiment_id: UUID) -> EnsembleExperiment: min_realizations_count = config.analysis_config.minimum_required_realizations active_realizations = _realizations(args, config.model_config.num_realizations) active_realiz...
class CrossAttention(nn.Module): def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0, dtype='float16'): super().__init__() inner_dim = (dim_head * heads) context_dim = default(context_dim, query_dim) self.scale = (dim_head ** (- 0.5)) self.heads ...
class OptionPlotoptionsErrorbarSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self...
class OptionPlotoptionsOrganizationSonificationContexttracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text...
class CharactersHandler(): def __init__(self, owner: 'DefaultAccount'): self.owner = owner self._ensure_playable_characters() self._clean() def _ensure_playable_characters(self): if (self.owner.db._playable_characters is None): self.owner.db._playable_characters = [] ...
class OptionSeriesSunburstSonificationDefaultspeechoptions(Options): def activeWhen(self) -> 'OptionSeriesSunburstSonificationDefaultspeechoptionsActivewhen': return self._config_sub_data('activeWhen', OptionSeriesSunburstSonificationDefaultspeechoptionsActivewhen) def language(self): return sel...
class AppManager(event.Component): total_sessions = 0 def __init__(self): super().__init__() self._appinfo = {} self._session_map = weakref.WeakValueDictionary() self._last_check_time = time.time() def register_app(self, app): assert isinstance(app, App) name ...
class FreeCompoundChapterFragmentToken(CompoundToken): def valid_chapter(self, parse_ascii): return self.is_valid_1(parse_ascii) def valid_fragment(self, parse_ascii): return self.is_valid_2(parse_ascii) def get_chapter(self, parse_ascii): return self.to_number_1(parse_ascii) def...
class RichStatus(): def __init__(self, ok, **kwargs): self.ok = ok self.info = kwargs self.info['hostname'] = SystemInfo.MyHostName self.info['version'] = Version def __getattr__(self, key): return self.info.get(key) def __bool__(self): return self.ok def ...
def test_hdiv_area(RT2): f = project(as_vector([0.8, 0.6]), RT2) assert (abs((assemble((dot(f, f) * ds_t)) - 1.0)) < 1e-07) assert (abs((assemble((dot(f, f) * ds_b)) - 1.0)) < 1e-07) assert (abs((assemble((dot(f, f) * ds_tb)) - 2.0)) < 1e-07) assert (abs((assemble((dot(f, f) * ds_v)) - 2.0)) < 1e-07...
def insert_observation(selected, sample_collection, component_observations=None, child_name=None): try: sample_col_doc = frappe.db.get_value('Sample Collection', sample_collection, ['reference_name', 'patient', 'referring_practitioner'], as_dict=1) selected = json.loads(selected) if (compone...
class LiteSATABISTUnitCSR(Module, AutoCSR): def __init__(self, bist_unit): self._start = CSR() self._sector = CSRStorage(48) self._count = CSRStorage(16) self._loops = CSRStorage(8) self._random = CSRStorage() self._done = CSRStatus() self._aborted = CSRStatus...
def split_channels(color: str): color = color.zfill(8) if (len(color) == 8): return ((parse.norm_hex_channel(color[6:]), parse.norm_hex_channel(color[4:6]), parse.norm_hex_channel(color[2:4])), (1 - parse.norm_hex_channel(color[:2]))) raise RuntimeError('Something is wrong in code logics.')
def exec_wait(_cmd, _output_capture=False, _timeout=0): _output = '' if (_timeout != 0): _cmd = (((_CMD_TIMEOUT + str(_timeout)) + ' ') + _cmd) _logger.debug('{func} - Executing command using the timeout |{timeout}| '.format(func='exec_wait', timeout=_timeout)) _logger.debug('{func} - cmd |{...
class TAInstance(): def __init__(self, logPtr=None): self._logPtr = logPtr def _log(self, name, *args): if (self._logPtr is not None): self._logPtr(name, safe_str(','.join(map(str, args)))) def Highest(records, n, attr=None): return Std._filt(records, n, attr, 5e-324, max...
class OptionPlotoptionsVennSonificationDefaultinstrumentoptionsActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, ...
.parametrize('ops', XP_OPS) .parametrize('depth,dirs,nO,batch_size,nI', [(1, 1, 1, 1, 1), (1, 1, 2, 1, 1), (1, 1, 2, 1, 2), (2, 1, 1, 1, 1), (2, 1, 2, 2, 2), (1, 2, 2, 1, 1), (2, 2, 2, 2, 2)]) def test_lstm_forward_training(ops, depth, dirs, nO, batch_size, nI): reference_ops = Ops() (params, H0, C0, X, size_at...
def test_invalid_toml(tmp_path, capsys): config_path = (tmp_path / '.mdformat.toml') config_path.write_text(']invalid TOML[') file_path = (tmp_path / 'test_markdown.md') file_path.write_text('some markdown\n') assert (run((str(file_path),)) == 1) captured = capsys.readouterr() assert ('Inval...
.compilertest def test_set_max_request_header_v3(): yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Module\nmetadata:\n name: ambassador\n namespace: default\nspec:\n config:\n max_request_headers_kb: 96\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\n name: ambassador\n n...