code
stringlengths
281
23.7M
def test_broken_plugin(testbot): borken_plugin_dir = path.join(path.dirname(path.realpath(__file__)), 'borken_plugin') try: tempd = mkdtemp() tgz = os.path.join(tempd, 'borken.tar.gz') with tarfile.open(tgz, 'w:gz') as tar: tar.add(borken_plugin_dir, arcname='borken') ...
def get_version_from_git(): import subprocess for opts in [['--first-parent'], []]: try: p = subprocess.Popen((['git', 'describe', '--long', '--always'] + opts), cwd=package_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: return if (p.wait() ...
class FlinkRowWriter(): def __init__(self, context: Context): self.java_file = JavaFile(context.from_java(), context.to_java()) def write(self, row: Row): csv_str = row_to_csv(row) data_len = len(csv_str) res = self.java_file.write(struct.pack('<i', data_len), 4) if (not ...
def main(): print('-- Classification Tree --') data = datasets.load_iris() X = data.data y = data.target (X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.4) clf = ClassificationTree() clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = accuracy_sc...
('delete', cls=FandoghCommand) ('--name', '-n', 'secret_name', help='name of the secret to delete', prompt='Name for the secret') def delete(secret_name): if click.confirm("You are about to delete a secret named '{}', you cannot undo this action. Are sure?".format(secret_name)): result = delete_secret(secre...
def firewall_access_proxy_ssh_client_cert(data, fos): vdom = data['vdom'] state = data['state'] firewall_access_proxy_ssh_client_cert_data = data['firewall_access_proxy_ssh_client_cert'] filtered_data = underscore_to_hyphen(filter_firewall_access_proxy_ssh_client_cert_data(firewall_access_proxy_ssh_clie...
class LoggingCommonResponseAllOf1(ModelNormal): allowed_values = {('format_version',): {'v1': '1', 'v2': '2'}} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_ty...
def test_custom_field_definition_duplicate_name_different_resource_type_accepted(db): definition1 = CustomFieldDefinition.create(db=db, data={'name': 'test1', 'description': 'test', 'field_type': 'string', 'resource_type': 'system', 'field_definition': 'string'}) definition2 = CustomFieldDefinition.create(db=db...
def test_require5(evmtester, branch_results): evmtester.requireBranches(5, True, True, True, False) results = branch_results() for i in [1626, 1660, 1703, 1708, 1713, 1737, 1742, 1747]: assert ([i, (i + 1)] in results[True]) with pytest.raises(VirtualMachineError): evmtester.requireBranc...
def test_stalecheck_adds_block_to_cache(request_middleware, allowable_delay): with patch('web3.middleware.stalecheck._is_fresh', side_effect=[False, True, True]) as fresh_spy: block = object() request_middleware.web3.eth.get_block.return_value = block request_middleware('', []) (cach...
class DarkStyle(QtWidgets.QProxyStyle): def __init__(self, *args, **kwargs): super(DarkStyle, self).__init__(*args, **kwargs) def standardPalette(self): palette = super(DarkStyle, self).standardPalette() print('DarkStyle.standardPalette is working 1') palette.setColor(QtGui.QPale...
class AbstractAccount(): _str_template = None __slots__ = ('_attrs',) def __init__(self, attributes): self._attrs = attributes def __getattr__(self, name): value = self._attrs.get(name) if ((not value) and (name not in self._attrs)): raise AttributeError(f"'{type(self...
class BlacklistRulesEngine(bre.BaseRulesEngine): def __init__(self, rules_file_path, snapshot_timestamp=None): super(BlacklistRulesEngine, self).__init__(rules_file_path=rules_file_path) self.rule_book = None def build_rule_book(self, global_configs=None): self.rule_book = BlacklistRuleB...
def random_transform_as_dual_quaternion(enforce_positive_non_dual_scalar_sign=True): T_rand = rand_transform() dq_rand = DualQuaternion.from_transformation_matrix(T_rand) if enforce_positive_non_dual_scalar_sign: if (dq_rand.q_rot.w < 0): dq_rand.dq = (- dq_rand.dq.copy()) return dq_...
def mark(editor: sublime.View, tracker: AbbreviationTracker): scope = get_settings('marker_scope', 'region.accent') editor.erase_regions(ABBR_REGION_ID) if tracker.valid_candidate: mark_opt = ((sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_NO_FILL) | sublime.DRAW_NO_OUTLINE) editor.add_regions...
def test_get_connection_types(): data = get_connection_types() assert (len(data) == ((len(ConnectionType) + len(ConnectorRegistry.connector_types())) - 4)) assert ({'identifier': ConnectionType.postgres.value, 'type': SystemType.database.value, 'human_readable': 'PostgreSQL', 'encoded_icon': None, 'authoriz...
class FaucetSingleStackAclControlTest(FaucetMultiDPTestBase): NUM_DPS = 3 NUM_HOSTS = 3 def acls(self): return {1: [{'rule': {'dl_type': IPV4_ETH, 'nw_dst': '10.1.0.2', 'actions': {'output': {'port': self.host_port_maps[1][0][0]}}}}, {'rule': {'dl_type': IPV4_ETH, 'dl_dst': 'ff:ff:ff:ff:ff:ff', 'act...
def get_class_definition(name, base='Object', docstring=''): code = [] code.append(('%s = function () {' % name)) for line in docstring.splitlines(): code.append((' // ' + line)) code.append((' %sop_instantiate(this, arguments);' % stdlib.FUNCTION_PREFIX)) code.append('}') if (base...
def broadcast_fnc(input_size: Size, target_size: Size) -> typing.Optional[Callable]: if (input_size == target_size): return identity_fnc input_project_size = _normalize_size(input_size, target_size) assert (len(input_project_size) == len(target_size)) for i in range(0, len(target_size)): ...
class StatsD(object): SECTION = 'secrets' HOST = ConfigEntry(LegacyConfigEntry(SECTION, 'host')) PORT = ConfigEntry(LegacyConfigEntry(SECTION, 'port', int)) DISABLED = ConfigEntry(LegacyConfigEntry(SECTION, 'disabled', bool)) DISABLE_TAGS = ConfigEntry(LegacyConfigEntry(SECTION, 'disable_tags', bool...
def extractNoobtransWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type)...
def classify_identity_type_for_privacy_center_consent_reporting(db: Session, provided_identity: ProvidedIdentity, browser_identity: Identity) -> Tuple[(Optional[ProvidedIdentity], Optional[ProvidedIdentity])]: if (not provided_identity.hashed_value): raise HTTPException(status_code=HTTP_404_NOT_FOUND, detai...
def extractConvallariaslibraryCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type...
def action_to_fdeep(argc, argv): args = parse_args(argv) prj = Project(args.path) err = prj.load() if (err is not None): log.error('error while loading project: %s', err) quit() elif (not prj.is_trained()): log.error('no trained model found for this project') quit() ...
class Model(object): def __init__(self, phase, visualize, output_dir, batch_size, initial_learning_rate, steps_per_checkpoint, model_dir, target_embedding_size, attn_num_hidden, attn_num_layers, clip_gradients, max_gradient_norm, session, load_model, gpu_id, use_gru, use_distance=True, max_image_width=160, max_imag...
def test_nan_default_value(): ' schema = {'namespace': 'namespace', 'name': 'name', 'type': 'record', 'fields': [{'name': 'some_field', 'type': 'float', 'default': 'nan'}]} test_record = {} result_value = roundtrip(schema, [test_record])[0]['some_field'] assert math.isnan(result_value)
class CatalogDrawer(Catalog.CatalogGroup): def drawer(self) -> CssStylesDivDrawers.CssDrawer: return self._set_class(CssStylesDivDrawers.CssDrawer) def nav(self) -> CssStylesDivDrawers.CssDrawerNav: return self._set_class(CssStylesDivDrawers.CssDrawerNav) def handle(self) -> CssStylesDivDraw...
def test_perf_clip(repeat=10): exec_time_vals = np.zeros(repeat) for i in range(repeat): start_time = time.time() utils.clip(np.random.uniform(low=(- 10), high=10, size=[1000, 2]), val_min=(- 5), val_max=5) exec_time_vals[i] = (time.time() - start_time) print('\nutils.clip execution ...
def test_instance_location_mix(map_doc): inst = InstanceDescriptor(designLocation={'Weight': (60, 61)}, userLocation={'Width': 180}) assert (inst.getFullUserLocation(map_doc) == {'Weight': 600, 'Width': 180, 'Custom': 1.5}), 'instance location is a mix of design and user locations' assert (inst.getFullDesig...
('flytekit.clients.friendly.SynchronousFlyteClient') ('click.get_current_context') def test_get_client(click_current_ctx, mock_flyte_client): class FlexiMock(mock.MagicMock): def __init__(self, *args, **kwargs): super(FlexiMock, self).__init__(*args, **kwargs) self.__getitem__ = (lam...
class ConvTranspose2dBias(ConvTranspose2dBiasAct): def __init__(self, in_channels, out_channels, kernel_size, stride, padding=0, dilation=1, groups=1, dtype='float16'): super().__init__('transposed_conv2d_bias', in_channels, out_channels, kernel_size, stride, padding, dilation, groups, dtype)
def filter_log_syslogd4_override_setting_data(json): option_list = ['certificate', 'custom_field_name', 'enc_algorithm', 'facility', 'format', 'interface', 'interface_select_method', 'max_log_rate', 'mode', 'override', 'port', 'priority', 'server', 'source_ip', 'ssl_min_proto_version', 'status', 'syslog_type'] ...
class TestPatternsPass(unittest.TestCase): base_path = (os.path.dirname(os.path.abspath(__file__)) + '**/') frame = inspect.currentframe() for filename in glob.iglob(f'{base_path}**/*.sol', recursive=True): path = Path(filename) test_name = str(path.relative_to(Path(os.path.abspath(__file__)...
class OptionPlotoptionsTilemapSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsTilemapSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsTilemapSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionPlotoptionsTilemapSo...
def _config_from_hf(hf_config: Mapping[(str, Any)]) -> FalconConfig: model_type = hf_config['model_type'] if ('RefinedWeb' in model_type): return _config_from_hf_refined_web_model(hf_config) elif (model_type == 'falcon'): return _config_from_hf_falcon(hf_config) else: raise Value...
def run_async_bwd(folder_name: str, path_dir: str, callback_url: str, verbose: bool, num_workers: int, res: tuple, batch_data_vjp: Tuple[(JaxSimulationData, ...)]) -> Tuple[Dict[(str, JaxSimulation)]]: fwd_task_ids = res[0].fwd_task_ids sims_adj = [] jax_infos_adj = [] parent_tasks_adj = [] for (sim...
.provider(fields.Dictionary({}, description='The default coroutine middleware has no constructor arguments')) class DefaultCoroutineMiddleware(CoroutineMiddleware): def coroutine(self, coroutine: MiddlewareCoroutine) -> MiddlewareCoroutine: async def handler(): try: return (await...
def find_item_locally(ctx: Context, item_type: str, item_public_id: PublicId) -> Tuple[(Path, ComponentConfiguration)]: item_type_plural = (item_type + 's') item_name = item_public_id.name try: registry_path = ctx.registry_path except ValueError as e: raise click.ClickException(str(e)) ...
_util.copy_func_kwargs(DatabaseOptions) def on_value_written(**kwargs) -> _typing.Callable[([_C1], _C1)]: options = DatabaseOptions(**kwargs) def on_value_written_inner_decorator(func: _C1): ref_pattern = _path_pattern.PathPattern(options.reference) instance_pattern = _path_pattern.PathPattern((...
class BaseSoC(SoCSDRAM): def __init__(self): platform = arty.Platform() sys_clk_freq = int(.0) SoCSDRAM.__init__(self, platform, clk_freq=sys_clk_freq, ident='Minimal Arty DDR3 Design for tests with Project X-Ray', ident_version=True, cpu_type=None, l2_size=16, uart_name='bridge') se...
class EmbeddingOpenAI(Embedding): def __init__(self, model_name='openai'): super().__init__(model_name) self.instance = None if (openai.__version__ < '1.0.0'): self.instance = EmbeddingOpenAI_0x() else: self.instance = EmbeddingOpenAI_1x() print(f'Init...
def cache_secret(masking_secret_cache: MaskingSecretCache, request_id: str) -> None: cache: FidesopsRedis = get_cache() cache.set_with_autoexpire(get_masking_secret_cache_key(request_id, masking_strategy=masking_secret_cache.masking_strategy, secret_type=masking_secret_cache.secret_type), FidesopsRedis.encode_o...
.parametrize('state', [AccountDB(MemoryDB())]) def test_balance(state): assert (state.get_balance(ADDRESS) == 0) state.set_balance(ADDRESS, 1) assert (state.get_balance(ADDRESS) == 1) assert (state.get_balance(OTHER_ADDRESS) == 0) with pytest.raises(ValidationError): state.get_balance(INVALI...
class OptionPlotoptionsAreasplineSonificationTracksMappingTime(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): s...
def block_detail(block_name, config, color=True): blocks_to_show = {} iterable_types = set([set, list, tuple, frozenset]) if (block_name not in config): try: next_block = [x.lstrip('') for x in config.get('genetree_meta_workflow', {})[block_name]] metaworkflow = True ...
('rocm.gemm_rcr_bias_add_add.gen_function') def gen_function(func_attrs, exec_cond_template, dim_info_dict): return common.gen_function(func_attrs, exec_cond_template, dim_info_dict, 'bias_add_add', extra_code=EXTRA_CODE.render(), input_addr_calculator=common.INPUT_ADDR_CALCULATOR.render(accessor_a=func_attrs['inpu...
class OptionPanelSliding(Options): component_properties = ('title_align',) def expanded(self): return self.get(True) def expanded(self, flag: bool): self.set(flag) def icon_expanded(self): if ('material-design-icons' in self.component.requirements): return self.get('m...
def test_fixedlength(): s = BigEndianInt(4) for i in (0, 1, 255, 256, (256 ** 3), ((256 ** 4) - 1)): assert (len(s.serialize(i)) == 4) assert (s.deserialize(s.serialize(i)) == i) for i in ((256 ** 4), ((256 ** 4) + 1), (256 ** 5), (- 1), (- 256), 'asdf'): with pytest.raises(Serializa...
('app_mention') def handle_mention(client, event, say): logging.info(f'handle_mention called: {event}') try: channel = event['channel'] session = sessions.get(channel, None) if (not session): session = Session(fixie_client) sessions[channel] = session clie...
def test_repr(): assert (repr(UnaryOperation(neg, [BinaryOperation(add, [a, b])])) == 'negate [plus [a#0 (type: int aliased: False),b#1 (type: int aliased: False)] int] int') assert (repr(UnaryOperation(neg, [BinaryOperation(udiv, [a, b])])) == 'negate [divide_us [a#0 (type: int aliased: False),b#1 (type: int a...
class SmartSymbolsPattern(HtmlInlineProcessor): def __init__(self, pattern, replace, md): super(SmartSymbolsPattern, self).__init__(pattern, md) self.replace = replace def handleMatch(self, m, data): return (self.md.htmlStash.store(m.expand((self.replace(m) if callable(self.replace) else...
(tags=['audit'], description=docs.NAME_SEARCH) class AuditCommitteeNameSearch(utils.Resource): filter_fulltext_fields = [('q', models.AuditCommitteeSearch.fulltxt)] _kwargs(args.names) _with(schemas.AuditCommitteeSearchListSchema()) def get(self, **kwargs): query = filters.filter_fulltext(models...
def main(): v = viz.Visualizer() v.add_bounding_box('Box_1', position=np.array([0.0, 0.0, 1.0]), size=np.array([1, 1, 2])) v.add_bounding_box('Box_2', position=np.array([1, 0, 0.05]), size=np.array([2, 1, 0.1]), orientation=np.array([(math.pi / 6.0), 0.0, 0.0, 1.0]), color=np.array([0, 0, 255]), alpha=0.5, ...
def test_comp_import_host_association(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = (test_dir / 'test_import.f90') string += comp_request(file_path, 15, 20) (errcode, results) = run_request(string, ['--use_signature_help', '-n1']) assert (errcode == 0) e...
.MeshTools .Archiver .Domain class TestInterpolatedBathy(object): def setup_class(cls): pass def teardown_class(cls): pass def setup_method(self, method): self.aux_names = [] def teardown_method(self, method): filenames = [] for aux_name in self.aux_names: ...
class OptionPlotoptionsColumnSonificationDefaultinstrumentoptionsMappingNoteduration(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,...
def test_align_concatenate_fasta_to_phylip(o_dir, e_dir, request): program = 'bin/align/phyluce_align_concatenate_alignments' output = os.path.join(o_dir, 'mafft-gblocks-clean-fasta-concat') cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft-gblocks-clean-fasta'...
class ConfirmationAW2TestCase(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'confirmation_aw2') def setup(cls): cls.aw1_aea = 'some_aw1_aea' config_overrides = {'models': {'strategy': {'args': {'aw1_aea': cls.aw1_aea}}}} super().setup(config_override...
class MessageFrame(QFrame): accept_signal = Signal(int, MessageData) cancel_signal = Signal(int, MessageData) TYPE_INVALID = 0 TYPE_EMPTY = 1 TYPE_QUESTION = 2 TYPE_LAUNCH_FILE = 3 TYPE_DEFAULT_CFG = 4 TYPE_NODELET = 5 TYPE_TRANSFER = 6 TYPE_BINARY = 7 TYPE_NOSCREEN = 8 T...
class AggregateTest(unittest.TestCase): def test_min(self): event = Event.sequence(array).min() self.assertEqual(event.run(), ([0] * 10)) def test_max(self): event = Event.sequence(array).max() self.assertEqual(event.run(), array) def test_sum(self): event = Event.seq...
class OptionPlotoptionsWaterfallSonificationContexttracksMappingGapbetweennotes(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...
def test_partitioned_analyses_init_initialize_accumulators(): d = DumbPartDistinguisher() d.update(traces=np.random.randint(0, 255, (500, 200), dtype='int16'), data=np.random.randint(0, 9, (500, 4096), dtype='uint8')) assert np.array_equal(d.partitions, np.arange(9)) assert (d.sum.shape == (200, 4096, 9...
class table__h_h_e_a(DefaultTable.DefaultTable): dependencies = ['hmtx', 'glyf', 'CFF ', 'CFF2'] def ascender(self): return self.ascent def ascender(self, value): self.ascent = value def descender(self): return self.descent def descender(self, value): self.descent = v...
('rocm.gemm_rcr_bias_permute_m2n3.gen_profiler') def gemm_gen_profiler(func_attrs, workdir, dim_info_dict): return common.gen_profiler(func_attrs=func_attrs, workdir=workdir, dim_info_dict=dim_info_dict, args_parse=ARGS_PARSER_TEMPLATE.render(), gemm_flag='bias_permute_m2n3', extra_shape_template=permute_common.EXT...
def make_stalecheck_middleware(allowable_delay: int, skip_stalecheck_for_methods: Collection[str]=SKIP_STALECHECK_FOR_METHODS) -> Middleware: if (allowable_delay <= 0): raise ValueError('You must set a positive allowable_delay in seconds for this middleware') def stalecheck_middleware(make_request: Call...
class TestSaveOverride(BodhiClientTestCase): def test_save_override(self, mocker): client = bindings.BodhiClient() client.send_request = mocker.MagicMock(return_value='return_value') client.csrf_token = 'a token' now = datetime.utcnow() response = client.save_override(nvr='py...
class Type_Inference(): MASKS = build_masks() def __init__(self): self.options = copy(Type_Inference.MASKS['leafs']) def is_resolved(self): return (len(self.options) == 1) def is_conflicted(self): return (len(self.options) == 0) def assert_positive(self, choice): asse...
def get_read(delta_days: int) -> Dict[(int, Tuple[(int, str)])]: assert (delta_days >= 0) stamp = utility.date.date_x_days_ago_stamp(abs(delta_days)) conn = _get_connection() res = conn.execute(f"select counts.c, counts.nid, notes.title from notes join (select count(*) as c, nid from read where page > -...
class EnumerationValidator(object): def __init__(self, valid_values, case_sensitive=False) -> None: self.case_sensitive = case_sensitive if case_sensitive: self.valid_values = {s: s for s in valid_values} else: self.valid_values = {s.lower(): s for s in valid_values} ...
def _pop_frame(): prev_frame = _current_frame() stack = _stack.get() del stack[(- 1)] if is_active(): current_frame = _current_frame() db_versions = {db: prev_frame.db_versions[db] for db in current_frame.db_versions.keys()} _update_frame(user=prev_frame.user, comment=prev_frame....
def test_full_drop_table_volume_anomalies(test_id: str, dbt_project: DbtProject): utc_today = datetime.utcnow().date() data = [{TIMESTAMP_COLUMN: cur_date.strftime(DATE_FORMAT)} for cur_date in generate_dates(base_date=utc_today) if (cur_date < (utc_today - timedelta(days=1)))] test_result = dbt_project.tes...
class TestAITModule(unittest.TestCase): def setUpClass(cls) -> None: torch.manual_seed(0) def _test_fx2ait_impl(self, test_serialization=False, test_cuda_graph=False): mod = torch.nn.Sequential(torch.nn.Linear(3, 4), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.Re...
class TestUnpackerBase(): def setup_method(self): self.config = ConfigParser() self.ds_tmp_dir = TemporaryDirectory(prefix='fact_tests_') self.tmp_dir = TemporaryDirectory(prefix='fact_tests_') self.config.add_section('unpack') self.config.set('unpack', 'data_folder', self.ds...
.django_db def test_tas_multiple_program_activity_belonging_one_object_class(client, monkeypatch, tas_mulitple_pas_per_oc, helpers): helpers.mock_current_fiscal_year(monkeypatch) tas = '001-X-0000-000' resp = client.get(url.format(tas=tas, query_params='')) expected_result = {'fiscal_year': helpers.get_...
class JsFileData(): def __init__(self, js_code: str): self.varName = js_code def raw(self): return JsObjects.JsObjects.get(self.varName) def headers(self) -> JsObjects.JsArray.JsArray: return JsObjects.JsArray.JsArray.get(self.varName)[0].keys() def records(self) -> JsObjects.JsA...
(tags=['filings'], description=docs.OPERATIONS_LOG) class OperationsLogView(ApiResource): model = models.OperationsLog schema = schemas.OperationsLogSchema page_schema = schemas.OperationsLogPageSchema filter_multi_fields = [('candidate_committee_id', models.OperationsLog.candidate_committee_id), ('begi...
class intArray(_object): __swig_setmethods__ = {} __setattr__ = (lambda self, name, value: _swig_setattr(self, intArray, name, value)) __swig_getmethods__ = {} __getattr__ = (lambda self, name: _swig_getattr(self, intArray, name)) __repr__ = _swig_repr def __init__(self, nelements): this...
class OptionPlotoptionsOrganizationSonificationContexttracksMappingRate(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 RouteFormatterMixin(object): fmtstr = ' {0:<3s} {1:<32s} {2:<8s} {3:<20s} {4:<15s} {5:<6s} {6:<6s} {7:<}\n' def _format_family_header(cls): ret = '' ret += 'Status codes: * valid, > best\n' ret += 'Origin codes: i - IGP, e - EGP, ? - incomplete\n' ret += cls.fmtstr.format('...
() _migration_options ('revision', required=True) def show(alembic_ini_path: str, script_location: str, revision: str): from alembic.script import ScriptDirectory (alembic_cfg, db_manager) = _get_migration_config(alembic_ini_path, script_location) script = ScriptDirectory.from_config(alembic_cfg) rev = ...
def process_tagscript(content: str, seed_variables: Dict[(str, tse.Adapter)]={}) -> Dict[(str, Any)]: output: tse.Response = tagscript_engine.process(content, seed_variables) kwargs: Dict[(str, Any)] = {} if output.body: kwargs['content'] = output.body[:2000] if (embed := output.actions.get('emb...
class ModifyL2Dst(base_tests.SimpleDataPlane): def runTest(self): logging.info('Running Modify_L2_Dst test') of_ports = config['port_map'].keys() of_ports.sort() self.assertTrue((len(of_ports) > 1), 'Not enough ports for test') delete_all_flows(self.controller) loggin...
class MocapViewerOffline(animation.FuncAnimation): def __init__(self, motion, cam_pos, v_up_str, play_speed=1.0, scale=1.0, thickness=1.0, hide_origin=False): animation.FuncAnimation.__init__(self, fig=plt.figure(figsize=(5, 5)), func=self.animate, frames=len(motion.poses), interval=50, blit=False) ...
def make_all(layout, subdir): def out_path(ext=''): return os.path.join(subdir, (layout.meta['fileName'] + ext)) if (not os.path.exists(subdir)): os.makedirs(subdir) klc_path = out_path('.klc') with open(klc_path, 'w', encoding='utf-16le', newline='\r\n') as file: file.write(layo...
('cuda.gemm_rrr.config') def gemm_rrr_config(func_attrs, dtype='float16'): common.make_fproc(func_attrs, RRR, include_cutlass_3x_ops=True) import cutlass_lib for op in func_attrs['op_instance'].values(): if (op.gemm_kind == cutlass_lib.library.GemmKind.Universal3x): op.C.element = cutlas...
_converter(acc_ops.exp) def acc_ops_exp(target: Target, args: Tuple[(Argument, ...)], kwargs: Dict[(str, Argument)], name: str) -> ConverterOutput: input_val = kwargs['input'] if (not isinstance(input_val, AITTensor)): raise RuntimeError(f'Unexpected input for {name}: {input_val}') return elementwis...
def get_lm_line(data, lm_mapping): line = [] lm_log = {'Active Bucket Counter': {'Read': 'na', 'Write': 'na'}, 'Active Measured Latency': {'Read': 'na', 'Write': 'na'}} if isinstance(data, dict): map = lm_mapping elif all([(data is None), lm_mapping]): map = {} elif all([(data is Non...
class TestExecuteScriptsCommands(EfuseTestCase): def setup_class(self): self.stored_dir = os.getcwd() def teardown_class(self): os.chdir(self.stored_dir) .skipif((arg_chip in ['esp32c2', 'esp32p4']), reason='These chips do not have eFuses used in this test') def test_execute_scripts_with...
def test_rounding(): x = Fxp(None, True, 8, 2, rounding='trunc') vi = [0.0, 1.0, 1.24, 1.25, 1.26, 1.49, 1.5] vo = [0.0, 1.0, 1.0, 1.25, 1.25, 1.25, 1.5] for (i, o) in zip(vi, vo): assert (x(i) == o) assert (x((- i)) == (- o)) x = Fxp(None, True, 8, 2, rounding='ceil') vi = [0.0,...
class CoverPhoto(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isCoverPhoto = True super(CoverPhoto, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): cover_id = 'cover_id' id = 'id' offset_x = 'offset_x' ...
def test_flexx_multiprocessing(): t0 = time.time() processes = [] for i in range(10): p = multiprocessing.Process(target=multiprocessing_func) p.daemon = True p.start() processes.append(p) for p in processes: p.join() t1 = time.time() assert True
def retry_stream_api(num_retries: int=10, backoff_base: float=2.0, warn_user: bool=True): retry_limit_msg = f'Error: Reached rate limit, passing...' backoff_msg = f'Error: API Bad gateway. Waiting {{backoff}} seconds...' def _wrapper(func): (func) def _wrapped(*args, **kwargs): u...
class OptionSeriesBellcurveSonificationTracksMappingRate(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): self._c...
def protect_options(p): p.add_argument('--no-write-protect', help='Disable write-protecting of the key. The key remains writable. (The keys use the RS coding scheme that does not support post-write data changes. Forced write can damage RS encoding bits.) The write-protecting of keypurposes does not depend on the op...
.parametrize('pathdef, expected', [('M 100 100 L 300 100 L 200 300 z', [('moveTo', ((100.0, 100.0),)), ('lineTo', ((300.0, 100.0),)), ('lineTo', ((200.0, 300.0),)), ('lineTo', ((100.0, 100.0),)), ('closePath', ())]), ('M 0 0 L 50 20 M 100 100 L 300 100 L 200 300 z', [('moveTo', ((0.0, 0.0),)), ('lineTo', ((50.0, 20.0),...
class ForumIndex(MethodView): def get(self): categories = Category.get_all(user=real(current_user)) user_count = User.query.count() topic_count = Topic.query.count() post_count = Post.query.count() newest_user = User.query.order_by(User.id.desc()).first() if (not curr...
class DistributionRestClientTestCase(TestCase): def test_CommunityPool(): content = {'pool': [{'denom': 'string', 'amount': '123'}]} mock_client = MockRestClient(json_encode(content).encode('utf8')) expected_response = ParseDict(content, QueryCommunityPoolResponse()) distribution = D...
def test_custom_config_values(): for (chunker_class, _) in chunker_common_config.items(): chunker = chunker_class(config=chunker_config) assert (chunker.text_splitter._chunk_size == 500) assert (chunker.text_splitter._chunk_overlap == 0) assert (chunker.text_splitter._length_function...
(schema=CartSchema, validators=(marshmallow_body_validator,), content_type='application/json') def create_sale(request): cart = Cart() for product in request.json.get('products'): cart.products.append(Product(**product)) request.dbsession.add(cart) request.dbsession.flush() schema = CartSche...
def test_generic_data_model(): GenericDataModel('test', {'attr1': {'name': 'attr1', 'type': 'str', 'is_required': True}}) with pytest.raises(AEAEnforceError): GenericDataModel('test', {'attr1': {'name': 'attr1', 'type': 'bad type', 'is_required': True}}) with pytest.raises(AEAEnforceError): ...