code
stringlengths
281
23.7M
def _expand_array_paths_to_preserve(paths: List[DetailedPath]) -> Dict[(str, List[int])]: expanded: List[DetailedPath] = [] for path in paths: while ((path != []) and (not isinstance(path[(- 1)], int))): path.pop() new_path: DetailedPath = [] for elem in path: new...
class DummyAsyncTransport(): def __init__(self, hosts, responses=None, **_): self.hosts = hosts self.responses = responses self.call_count = 0 self.calls = defaultdict(list) async def perform_request(self, method, target, **kwargs): (status, resp) = (200, {}) if s...
class OptionSeriesVariablepieSonificationTracksMappingPitch(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('y') def mapTo(self, text: str): self....
(tags=['financial'], description=docs.REPORTS, params={'entity_type': {'description': 'Committee groupings based on FEC filing form. Choose one of: `presidential`, `pac-party`, `house-senate`, or `ie-only`', 'enum': ['presidential', 'pac-party', 'house-senate', 'ie-only']}}) class ReportsView(views.ApiR...
class OptionPlotoptionsDumbbellLowmarkerStatesHover(Options): def animation(self) -> 'OptionPlotoptionsDumbbellLowmarkerStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsDumbbellLowmarkerStatesHoverAnimation) def enabled(self): return self._config_get(True) de...
class Test_CreateObject(ut.TestCase): def test_progid(self): obj = comtypes.client.CreateObject('Scripting.Dictionary') self.assertTrue(isinstance(obj, POINTER(Scripting.IDictionary))) def test_clsid(self): obj = comtypes.client.CreateObject(Scripting.Dictionary) self.assertTrue(...
def extractJyudo05XxWordpressCom(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)...
class TestMrtlibUnknownMrtRecord(unittest.TestCase): def test_parse(self): body = b'test' buf = (b'\x11\x11\x11\x11""33\x00\x00\x00\x04' + body) (record, rest) = mrtlib.MrtRecord.parse(buf) eq_(, record.timestamp) eq_(8738, record.type) eq_(13107, record.subtype) ...
('flytekit.core.python_customized_container_task.PythonCustomizedContainerTask.get_config') ('flytekit.core.python_customized_container_task.PythonCustomizedContainerTask.get_custom') def test_serialize_to_model(mock_custom, mock_config): mock_custom.return_value = {'a': 'custom'} mock_config.return_value = {'a...
def get_max_cat_level_special(save_stats: dict[(str, Any)], cat_id: int) -> int: legend = is_legend(cat_id) acient_curse_clear = uncanny.is_ancient_curse_clear(save_stats) user_rank = helper.calculate_user_rank(save_stats) catseyes = catseyes_unlocked(save_stats) eoc_cleared_2 = main_story.has_clear...
def get_wordmap_fieldnames(): return ['upos', 'lemma', 'homonym', 'new_para', 'kotus_tn', 'kotus_av', 'plurale_tantum', 'possessive', 'clitics', 'is_proper', 'proper_noun_class', 'style', 'stub', 'gradestem', 'twolstem', 'grade_dir', 'harmony', 'is_suffix', 'is_prefix', 'stem_vowel', 'stem_diphthong', 'sem', 'parti...
class ExposureBoundsLever(): def __init__(self, exposure_control_system=None): self.exposure_control_system = exposure_control_system def activate(self): if (not self.exposure_control_system): return elif self.exposure_control_system.ee_lever.locked(): return 'Blo...
class RedisCache(): PREFIX = 'asgilook:' INVALIDATE_ON = frozenset({'DELETE', 'POST', 'PUT'}) CACHE_HEADER = 'X-ASGILook-Cache' TTL = 3600 def __init__(self, config): self._config = config self._redis = self._config.redis_from_url(self._config.redis_host) async def _serialize_res...
def _load_project_config(project_path: Path) -> None: config_path = project_path.joinpath('brownie-config') config_data = _load_config(config_path) config_vars = _load_project_envvars(project_path) if ('dotenv' in config_data): if (not isinstance(config_data['dotenv'], str)): raise V...
def diag_quadrupole3d_10(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 3, 1), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + R[0]) x4 = (x2 + A[0]) x5 = (0.5 * x0) x6 = ((ax * bx) * x0) x7 = ((((5. * da) * db) * numpy.sqrt...
def emotion_caculate(text): positive = 0 negative = 0 anger = 0 disgust = 0 fear = 0 sad = 0 surprise = 0 good = 0 happy = 0 anger_list = [] disgust_list = [] fear_list = [] sad_list = [] surprise_list = [] good_list = [] happy_list = [] wordlist = txt...
def get_jinja_environment(): jinja_template_paths_obj = [] if TEMPLATES_PATH: external_templates = pathlib.Path(TEMPLATES_PATH).expanduser().resolve() assert os.path.isdir(external_templates), 'External template path "{0}" not found'.format(external_templates) jinja_template_paths_obj.ap...
_register_parser _set_msg_type(ofproto.OFPT_ECHO_REPLY) class OFPEchoReply(MsgBase): def __init__(self, datapath, data=None): super(OFPEchoReply, self).__init__(datapath) self.data = data def parser(cls, datapath, version, msg_type, msg_len, xid, buf): msg = super(OFPEchoReply, cls).pars...
def PlaylistsTab(playlists, accent_color, text_color, background_color, vertical_gui: bool, show_album_art: bool): playlists_names = list(playlists.keys()) default_pl_name = (playlists_names[0] if playlists_names else None) playlist_selector = [[IconButton(PLUS_ICON, 'new_pl', t('new playlist'), background_...
class AdsInsightsMixin(): class Increment(object): monthly = 'monthly' all_days = 'all_days' class Operator(object): all = 'ALL' any = 'ANY' contain = 'CONTAIN' equal = 'EQUAL' greater_than = 'GREATER_THAN' greater_than_or_equal = 'GREATER_THAN_OR_...
class PartialRoutes(): async def async_endpoint(cls, arg, request): return JSONResponse({'arg': arg}) async def async_ws_endpoint(cls, websocket: WebSocket): (await websocket.accept()) (await websocket.send_json({'url': str(websocket.url)})) (await websocket.close())
def parse_args(argv): parser = argparse.ArgumentParser(prog='ergo encode', description='Encode one or more files to vectors and create or update a csv dataset for training.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('project', help='The path containing the model definition.') ...
class TestGetDefaultMessagingConfig(): (scope='function') def url(self, messaging_config: MessagingConfig) -> str: return (V1_URL_PREFIX + MESSAGING_DEFAULT_BY_TYPE).format(service_type=messaging_config.service_type.value) (scope='function') def url_uppercase(self, messaging_config: MessagingCon...
def format_timestamp(timestamp_str, datetime_formatter): try: if (('"' in timestamp_str) or ("'" in timestamp_str)): timestamp_str = timestamp_str.replace('"', '') timestamp_str = timestamp_str.replace("'", '') formatted_timestamp = dateutil_parser.parse(timestamp_str).strfti...
class Config(dict): def __init__(self, root_path=None, data_path=None, defaults=default_config): dict.__init__(self, (defaults or {})) if root_path: self.root_path = root_path else: self.root_path = os.path.dirname(os.path.realpath(__file__)) if data_path: ...
def test_boundary_from_points_more_data(testpath): points = xtgeo.points_from_file((testpath / POINTSET2)) boundary = xtgeo.Polygons.boundary_from_points(points, alpha=2000) assert (boundary.dataframe[boundary.xname].values[0:5].tolist() == pytest.approx([460761.571, 461325.128, 461325.128, 462452.241, 4624...
class PaymentManager(models.Manager): def booking_payments_by_location(self, location): booking_payments = Payment.objects.filter(bill__in=BookingBill.objects.filter(booking__use__location=location)) return booking_payments def subscription_payments_by_location(self, location): subscript...
def max_ff_f(gen, t, srcs): l = srcs[0] r = srcs[1] right_larger = gen.symbols.newLabel() done = gen.symbols.newLabel() dst = gen.newTemp(Float) right_greater = gen.emit_binop('>', [r, l], Float) gen.emit_cjump(right_greater, right_larger) gen.emit_move(l, dst) gen.emit_jump(done) ...
class FaucetUntaggedMeterAddTest(FaucetUntaggedMeterParseTest): NUM_FAUCET_CONTROLLERS = 1 def test_untagged(self): super().test_untagged() conf = self._get_faucet_conf() conf['meters']['lossymeter2'] = {'meter_id': 2, 'entry': {'flags': ['PKTPS'], 'bands': [{'rate': '1000', 'type': 'DRO...
def nextCmd(snmpDispatcher, authData, transportTarget, *varBinds, **options): def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx): if (not cbFun): return if errorIndication: cbFun(errorIndication, pMod.Integer(0), pMod.Integer(0), None, cbCtx=cbCtx, snmpD...
def _filter_out_variables_not_in_dataframe(X, variables): if (variables is None): return None if (not isinstance(variables, list)): variables = [variables] filtered_variables = [var for var in variables if (var in X.columns)] if (len(filtered_variables) == 0): raise ValueError('A...
((not has_traitsui()), 'TraitsUI not installed') ((toolkit.toolkit == 'wx'), 'wxPython not supported') class TestTraitsUIWidgetAction(unittest.TestCase, UnittestTools): def setUp(self): self.gui = GUI() self.parent = Window() self.parent.create() self.parent.open() self.addCl...
class UrlInput(QLineEdit): def __init__(self, cb, parent=None): QLineEdit.__init__(self, parent) self.cb = cb self.suggestions = [] self.completer = QCompleter(self.suggestions, self) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.setCompleter(self.complet...
class Uint(int): __slots__ = () def from_be_bytes(cls: Type, buffer: 'Bytes') -> 'Uint': return cls(int.from_bytes(buffer, 'big')) def from_le_bytes(cls: Type, buffer: 'Bytes') -> 'Uint': return cls(int.from_bytes(buffer, 'little')) def __init__(self, value: int) -> None: if (not...
class EvenniaPasswordValidator(): def __init__(self, regex="^[\\w. +\\-',]+$", policy="Password should contain a mix of letters, spaces, digits and /./+/-/_/'/, only."): self.regex = regex self.policy = policy def validate(self, password, user=None): if (not re.findall(self.regex, passwo...
class Grid(object): def __init__(self, color_grid, name_grid, grid_size): if (not isinstance(color_grid, (tuple, list))): raise ValueError('Color grid is not a list: {}'.format(color_grid)) if (not isinstance(name_grid, (tuple, list))): raise ValueError('Name grid is not a li...
def extractRaisingmytailBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=f...
def is_using_pyqt5(): if hasattr(idaapi, 'get_kernel_version'): (_ida_version_major, _ida_version_minor) = map(int, idaapi.get_kernel_version().split('.')) return ((_ida_version_major > 6) or ((_ida_version_major == 6) and (_ida_version_minor >= 9))) else: return False
class AbstractJaxStructure(Structure, JaxObject): geometry: Union[(JaxGeometryType, GeometryType)] medium: Union[(JaxMediumType, MediumType)] _differentiable_fields = () ('medium', always=True) def _check_2d_geometry(cls, val, values): return val def jax_fields(self): return dict...
def test_stride_with_config(golden): ConfigLoad = new_config_ld() def bar(n: size, src: [i8][n]): assert (stride(src, 0) == ConfigLoad.src_stride) pass def foo(n: size, src: [i8][n]): assert (stride(src, 0) == ConfigLoad.src_stride) bar(n, src) assert (f'''{bar} {foo}''' ...
class Debug(): def __init__(self, config: Config): self.config = config def run(self) -> bool: dbt_runner = DbtRunner(dbt_project_utils.PATH, self.config.profiles_dir, self.config.profile_target) try: dbt_runner.run_operation('elementary_cli.test_conn', quiet=True) ex...
class OptionSeriesDumbbellSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionSeriesDumbbellSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionSeriesDumbbellSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) -> 'OptionSeriesD...
class USLiteSATAPHYCRG(Module): def __init__(self, refclk, pads, gth, gen): self.tx_reset = Signal() self.rx_reset = Signal() self.clock_domains.cd_sata_tx = ClockDomain() self.clock_domains.cd_sata_rx = ClockDomain() if isinstance(refclk, (Signal, ClockSignal)): ...
def test_ge_checkpoint_params(): task_object = GreatExpectationsTask(name='test8', datasource_name='data', inputs=kwtypes(dataset=str), expectation_suite_name='test.demo', data_connector_name='data_example_data_connector', checkpoint_params={'site_names': ['local_site']}) task_object(dataset='yellow_tripdata_sa...
.param_file((FIXTURE_PATH / 'docutil_syntax_extensions.txt')) def test_syntax_extensions(file_params): settings = settings_from_cmdline(file_params.description) report_stream = StringIO() settings['warning_stream'] = report_stream doctree = publish_doctree(file_params.content, parser=Parser(), settings_...
class RRLSeriesPageFilter(WebMirror.OutputFilters.FilterBase.FilterBase): wanted_mimetypes = ['text/html'] want_priority = 55 loggerPath = 'Main.Filter.RoyalRoad.Page' match_re = re.compile('^ flags=re.IGNORECASE) def wantsUrl(cls, url): if cls.match_re.search(url): print(("RRLSe...
class NodeExecutionGetDataResponse(_CommonDataResponse): def __init__(self, *args, dynamic_workflow: typing.Optional[DynamicWorkflowNodeMetadata]=None, **kwargs): super().__init__(*args, **kwargs) self._dynamic_workflow = dynamic_workflow def dynamic_workflow(self) -> typing.Optional[DynamicWork...
.parametrize('gas_limit', (True, False, None, 'auto')) .parametrize('gas_buffer', (1, 1.25)) def test_gas_limit_automatic(tester, accounts, config, gas_limit, gas_buffer): config.active_network['settings']['gas_limit'] = gas_limit config.active_network['settings']['gas_buffer'] = gas_buffer tx = tester.doNo...
class OptionsChartistBar(OptionsChartistLine): def seriesBarDistance(self): return self._config_get() def seriesBarDistance(self, num: int): self._config(num) def reverseData(self): return self._config_get() def reverseData(self, flag: bool): self._config(flag) def ho...
def test(): assert Doc.has_extension('autor'), "Hast du die Doc-Erweiterung 'autor' registriert?" ext = Doc.get_extension('autor') assert all(((v is None) for v in ext)), "Hast du den default-Wert der Erweiterung 'autor' angegeben?" assert Doc.has_extension('buch'), "Hast du die Doc-Erweiterung 'buch' r...
def extractStattuceBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('() with you for thirteen years (eng', 'With you for thirteen years', 'translated'), ('() love in ...
def get_info_from_internet(user_chat_text, settings): answer_with_search = settings['answer_with_search'] additional_searches = settings['additional_searches'] specify_sources = settings['specify_sources'].split(', ') consult_search_history = settings['consult_search_history'] num_of_excerpts = sett...
def extractBellonertBlogspotCom(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) ...
class PagesTestCase(TestCase): def setUp(self): u = User(username='test', is_active=True, is_staff=True, is_superuser=True) u.set_password('test') u.save() self.site_1 = Site.objects.all()[0] Page.register_templates({'key': 'base', 'title': 'Standard template', 'path': 'feinc...
class OptionPlotoptionsVariwideDragdropDraghandle(Options): def className(self): return self._config_get('highcharts-drag-handle') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#fff') def color(self, text: str): ...
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.') def calculate_cache_key_multiple_times(x, n=1000): import pandas as pd series = pd.Series([_calculate_cache_key(task_name='task_name', cache_version='cache_version', input_literal_map=LiteralMap(literals={'d': TypeEngine.to_literal(ctx=Fl...
class LocalIOSchemaWriter(SchemaWriter[T]): def __init__(self, to_local_path: str, cols: typing.Optional[typing.Dict[(str, type)]], fmt: SchemaFormat): super().__init__(to_local_path, cols, fmt) def _write(self, df: T, path: os.PathLike, **kwargs): pass def write(self, *dfs, **kwargs): ...
def output_orthologs_row(out, annotation, ncbi): (query_name, best_hit_name, best_hit_evalue, best_hit_score, annotations, (og_name, og_cat, og_desc), max_annot_lvl, match_nog_names, all_orthologies, annot_orthologs) = annotation best_hit_name_id = best_hit_name.split('.')[1] all_orthologies['annot_ortholog...
class SubgridError(proteus.SubgridError.SGE_base): def __init__(self, coefficients, nd): proteus.SubgridError.SGE_base.__init__(self, coefficients, nd, lag=False) def initializeElementQuadrature(self, mesh, t, cq): pass def updateSubgridErrorHistory(self, initializationPhase=False): ...
def get_auth_service_mock() -> MagicMock: auth_stub_mock = MagicMock() auth_stub_mock.GetPublicClientConfig.return_value = PublicClientAuthConfigResponse(client_id=CLIENT_ID, redirect_uri=REDIRECT_URI, scopes=['offline', 'all'], authorization_metadata_key='flyte-authorization') auth_stub_mock.GetOAuth2Metad...
('/mark/<fid>/<mark>') def mark(fid, mark): data = parse.urlencode(encode_obj({'fid': fid, 'is_mark': mark})) try: data = xl.urlopen(' data=data) data = data.replace('\n', '').replace('\r', '') data = json.loads(data[data.index('{'):]) if data['state']: xbmc.executebu...
def test_vaex_workflow_subset(): def generate() -> subset_schema: return StructuredDataset(dataframe=vaex_df) def consume(df: subset_schema) -> subset_schema: subset_df = df.open(vaex.dataframe.DataFrameLocal).all() assert (subset_df.column_names == ['y']) coly = subset_df.y.valu...
class OptionSeriesSolidgauge(Options): def accessibility(self) -> 'OptionSeriesSolidgaugeAccessibility': return self._config_sub_data('accessibility', OptionSeriesSolidgaugeAccessibility) def allowPointSelect(self): return self._config_get(False) def allowPointSelect(self, flag: bool): ...
class OptionPlotoptionsVariwideSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsVariwideSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsVariwideSonificationContexttracksMappingFrequency) def gapBetweenNotes(self) -...
class InstanceNetworkInterface(object): def __init__(self, **kwargs): self.full_name = kwargs.get('full_name') self.kind = kwargs.get('kind') self.network = kwargs.get('network') self.subnetwork = kwargs.get('subnetwork') self.network_ip = kwargs.get('networkIP') self...
def test_adding_deprecated_env_from(): config = '\ndeployment:\n enabled: true\nenvFrom:\n- configMapRef:\n name: configmap-name\n' r = helm_template(config) assert (r['daemonset'][name]['spec']['template']['spec']['containers'][0]['envFrom'][0]['configMapRef'] == {'name': 'configmap-name'}) assert ...
def which(program): def is_exe(fpath): return (os.path.isfile(fpath) and os.access(fpath, os.X_OK)) (fpath, _fname) = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ['PATH'].split(os.pathsep): path = path.st...
def find_origin_coordinate(sites): if (len(sites) == 0): return (0, 0) def inner_(): for site in sites: coordinate = SITE_COORDINATE_PATTERN.match(site['name']) assert (coordinate is not None), site x_coord = int(coordinate.group(2)) y_coord = int(...
class TestSkillExceptionPolicyConfigVariable(BaseConfigTestVariable): OPTION_NAME = 'skill_exception_policy' CONFIG_ATTR_NAME = 'skill_exception_policy' GOOD_VALUES = ExceptionPolicyEnum INCORRECT_VALUES = [None, 'sTrING?', (- 1)] REQUIRED = False AEA_ATTR_NAME = '_skills_exception_policy' A...
.parametrize('elasticapm_client', [{'environment': 'production'}], indirect=True) def test_service_info(elasticapm_client): service_info = elasticapm_client.get_service_info() assert (service_info['name'] == elasticapm_client.config.service_name) assert (service_info['environment'] == elasticapm_client.conf...
.parametrize('params', (['t', 'u'], ['u', 't'])) .parametrize('levels', ([500, 850], [850, 500])) .parametrize('source_name', ['indexed-directory']) def test_indexing_order_by_with_request(params, levels, source_name): request = dict(level=levels, variable=params, time='1200') (ds, _, total, n) = get_fixtures(s...
class ClefAccount(_PrivateKeyAccount): def __init__(self, address: str, provider: Union[(HTTPProvider, IPCProvider)]) -> None: self._provider = provider super().__init__(address) def _transact(self, tx: Dict, allow_revert: bool) -> None: if (allow_revert is None): allow_rever...
class OptionSeriesVennSonificationTracksMappingFrequency(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 test_dfsr_subtype0(tmpdir, merge_lis_prs): fpath = os.path.join(str(tmpdir), 'dfsr-subtype0.lis') content = ((headers + ['data/lis/records/curves/dfsr-subtype0.lis.part']) + trailers) merge_lis_prs(fpath, content) with lis.load(fpath) as (f,): dfs = f.data_format_specs()[0] ch1 = dfs...
def process_description(description_fce): def inner(description): clear_description = re.sub('\\s+', ' ', re.sub('\\w+:\\/{2}[\\d\\w-]+(\\.[\\d\\w-]+)*(?:(?:\\/[^\\s/]*))*', '', re.sub('(#|=|---|~|`)*', '', re.sub('((\r?\n)|^).{0,8}((\r?\n)|$)', '', re.sub('((\r*.. image::|:target:) '', description_fce(des...
def chunked(arg_name: str, arg_pos: int, chunk_size: int, process: Callable, reverse: str=None, reverse_pos: int=None, chain: str=None, chain_pos: int=None) -> Callable: def decorator(function: Callable) -> Callable: nonlocal arg_pos, reverse_pos, chain_pos arg_pos -= 1 if (reverse_pos is no...
def smspecs(draw, sum_keys, start_date): sum_keys = draw(sum_keys) n = (len(sum_keys) + 1) nx = draw(small_ints) ny = draw(small_ints) nz = draw(small_ints) keywords = (['TIME '] + sum_keys) units = (['DAYS '] + draw(st.lists(unit_names, min_size=(n - 1), max_size=(n - 1)))) well_n...
class TestTrainingTeiParser(): def test_should_parse_labelled_tokens_as_tag_result(self): tei_root = _get_training_tei_with_text([E('head', TOKEN_1, E('lb')), '\n', E('p', TOKEN_2, E('lb')), '\n']) tag_result = SampleTrainingTeiParser().parse_training_tei_to_tag_result(tei_root) assert (tag_...
(no_gui_test_assistant, 'No GuiTestAssistant') class TestConfirmationDialog(unittest.TestCase, GuiTestAssistant): def setUp(self): GuiTestAssistant.setUp(self) self.dialog = ConfirmationDialog() def tearDown(self): if (self.dialog.control is not None): with self.delete_widget...
class TestSettings(unittest.TestCase): def setUp(self) -> None: self.config_str = "\nserver_port: 50052\n# uri of database backend for notification server\ndb_uri: sqlite:///ns.db\n# High availability is disabled by default\nenable_ha: false\n# TTL of the heartbeat of a server, i.e., if the server hasn't se...
class SparkDataFrameSchemaReader(SchemaReader[pyspark.sql.DataFrame]): def __init__(self, from_path: str, cols: typing.Optional[typing.Dict[(str, type)]], fmt: SchemaFormat): super().__init__(from_path, cols, fmt) def iter(self, **kwargs) -> typing.Generator[(T, None, None)]: raise NotImplemente...
class OptionSeriesVennSonificationTracksMappingTime(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._config...
class TestParsingItems(unittest.TestCase): def test_items(self): actual = parse('items') expected = (((trait('items', optional=True) | dict_items(optional=True)) | list_items(optional=True)) | set_items(optional=True)) self.assertEqual(actual, expected) def test_items_not_notify(self): ...
class Chi(Distribution): def __init__(self, dofs): if (dofs is None): self.dofs = 1 else: self.dofs = dofs if (self.dofs < 0): raise ValueError('Invalid parameter in chi distribution: dofs must be positive.') if (self.dofs == 1): self.b...
class Command(BaseCommand): help = 'Generates configured API schema for project.' def get_mode(self): return (COREAPI_MODE if coreapi.is_enabled() else OPENAPI_MODE) def add_arguments(self, parser): parser.add_argument('--title', dest='title', default='', type=str) parser.add_argumen...
_exceptions def weekly_upcoming_events(): logger.info('Running task: weekly_upcoming_events') locations = Location.objects.all() for location in locations: events_this_week_at_location = published_events_this_week_local(location) if (len(events_this_week_at_location) == 0): logge...
def disassemble_data(reader, address, data_begin, data_end, code_begin, code_end, data_pointers, code_pointers): data = reader.read(4) if (len(data) != 4): LOGGER.debug('Failed to read 4 data bytes at address 0x%x.', address) return data += reader.read(4) if (len(data) == 4): ret...
_tag def generate_p_n(article: Articles): article_list = list(Articles.objects.filter(category=article.category)) now_index = article_list.index(article) max_index = (len(article_list) - 1) if (now_index == 0): prev = '<a href="javascript:void (0);"></a>' else: prev_article = article...
class _EditedMessage(_Message): def __init__(self, message_id: Optional[int]): self.message_id = message_id def filter(self, event: EventCommon): if (not super().filter(event)): return False if (not isinstance(event, MessageEdited.Event)): return False if ...
() ('input_name') ('output_name') ('begin', type=int) ('end', type=int) def apply(input_name, output_name, begin, end): input = np.load((workspace / f'{input_name}.npy')) output = np.load((workspace / f'{output_name}.npy')) output[begin:end] = input[begin:end] np.save((workspace / f'{output_name}.npy'),...
def tex_Step(head, args, **kwargs): (expr, forexpr) = args (n, a, b) = forexpr.args() na = expr.replace({n: a}) if a.is_integer(): na1 = expr.replace({n: Expr((int(a) + 1))}) else: na1 = expr.replace({n: (a + 1)}) nb = expr.replace({n: b}) na = na.latex(**kwargs) na1 = na...
class SupportedRegion(str, _enum.Enum): ASIA_NORTHEAST1 = 'asia-northeast1' ASIA_EAST1 = 'asia-east1' ASIA_NORTHEAST2 = 'asia-northeast2' EUROPE_NORTH1 = 'europe-north1' EUROPE_WEST1 = 'europe-west1' EUROPE_WEST4 = 'europe-west4' US_CENTRAL1 = 'us-central1' US_EAST1 = 'us-east1' US_E...
class StringRevealer(object): ASCII_BYTE = b'!\\"#\\$%&\\\'\\(\\)\\*\\+,-\\./:;<=>\\?\\[\\]\\^_`abcdefghijklmnopqrstuvwxyz\\{\\|\\}\\\\\\~\\t ' ASCII_RE = re.compile((b'([%s]{%d,})' % (ASCII_BYTE, 3))) UNICODE_RE = re.compile((b'((?:[%s]\x00){%d,})' % (ASCII_BYTE, 3))) def __init__(self, attrib): ...
class Player(): def __init__(self, address): self.address = address def get_team_num(self): return mem.read_i32((self.address + nv.m_iTeamNum)) def get_health(self): return mem.read_i32((self.address + nv.m_iHealth)) def get_life_state(self): return mem.read_i32((self.add...
def test_from_file_missing_parameter(simple_roff_parameter_contents): buff = io.BytesIO() simple_roff_parameter_contents[0][1] roffio.write(buff, simple_roff_parameter_contents) buff.seek(0) with pytest.raises(ValueError, match='Did not find parameter'): RoffParameter.from_file(buff, 'c')
class ThreadLocalContext(BaseContext): thread_local = threading.local() thread_local.transaction = None thread_local.spans = () def get_transaction(self, clear: bool=False) -> 'elasticapm.traces.Transaction': transaction = getattr(self.thread_local, 'transaction', None) if clear: ...
class FetchBlockBehaviour(TickerBehaviour): def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) def _get_block(self) -> None: ledger_api_dialogues = cast(LedgerApiDialogues, self.context.ledger_api_dialogues) (ledger_api_msg, _) = ledger_api_dialogues.create(counterpart...
class TestConsumption(unittest.TestCase): def test_create_consumption(self): consumption = TotalConsumption(zoneKey=ZoneKey('DE'), datetime=datetime(2023, 1, 1, tzinfo=timezone.utc), consumption=1, source='trust.me') assert (consumption.zoneKey == ZoneKey('DE')) assert (consumption.datetime ...
(context_settings=get_width()) ('--shrink_node', default='DETERMINISTIC', type=str, help='Named node, or DETERMINISTIC', show_default=True) ('--node_filters', help='JSON version of node_filters (see documentation)', callback=json_to_dict) ('--number_of_shards', default=1, type=int, help='Shrink to this many shards per ...
(('conf' in cfgdiff.supported_formats), 'requires ConfigObj') class ConfigDiffTestCase(CfgDiffTestCase): def test_conf_same(self): self._test_same(cfgdiff.ConfigDiff, './tests/test_same_1-a.ini', './tests/test_same_1-b.ini') def test_conf_different(self): self._test_different(cfgdiff.ConfigDiff,...