code
stringlengths
281
23.7M
def check_keylayout(filename): path = os.path.join('.', 'dist', (filename + '.keylayout')) tree = etree.parse(path, etree.XMLParser(recover=True)) dead_keys = [] for keymap_index in range(5): keymap_query = f'//keyMap[="{keymap_index}"]' keymap = tree.xpath(keymap_query) assert (...
def gem_to_loopy(gem_expr, var2terminal, scalar_type): shape = (gem_expr.shape if (len(gem_expr.shape) != 0) else (1,)) idx = make_indices(len(shape)) indexed_gem_expr = gem.Indexed(gem_expr, idx) output_loopy_arg = loopy.GlobalArg('output', shape=shape, dtype=scalar_type, is_input=True, is_output=True)...
('args,expected', [([], {'db': {'driver': 'mysql', 'pass': 'secret', 'user': '${oc.env:USER}'}, 'ui': {'windows': {'create_db': True, 'view': True}}, 'schema': {'database': 'school', 'tables': [{'name': 'students', 'fields': [{'name': 'string'}, {'class': 'int'}]}, {'name': 'exams', 'fields': [{'profession': 'string'},...
def execution(execution: Dict[(str, Any)], filler: Dict[(str, Any)]) -> Dict[(str, Any)]: execution = normalize_execution((execution or {})) if (('caller' in execution) and ('origin' not in execution)): execution = assoc(execution, 'origin', execution['caller']) if ('vyperLLLCode' in execution): ...
class HCI_Cmd_LE_Set_Extended_Scan_Enable(HCI_Command): def __init__(self, enable=True, filter_dups=1, duration=0, period=0): super().__init__(b'\x08', b'B') self.payload.append(Bool('enable', enable)) self.payload.append(EnumByte('filter', filter_dups, {0: 'Disable', 1: 'Enable', 2: 'Eanble...
def filter_firewall_decrypted_traffic_mirror_data(json): option_list = ['dstmac', 'interface', 'name', 'traffic_source', 'traffic_type'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictio...
(name='worker', cls=build_lazy_click_command(_dynamic_factory=_model_dynamic_factory)) def start_model_worker(**kwargs): if kwargs['daemon']: port = kwargs['port'] model_type = (kwargs.get('worker_type') or 'llm') log_file = os.path.join(LOGDIR, f'model_worker_{model_type}_{port}_uvicorn.log...
class Xkblayout(IntervalModule): interval = 1 color = '#FFFFFF' format = ' {symbol}' layouts = [] uppercase = True settings = (('color', 'RGB hexadecimal color code specifuer, defaults to #FFFFFF'), ('format', 'Format string'), ('layouts', 'List of layouts'), ('uppercase', 'Flag for uppercase ou...
class TestRegisterWithMalformedEntryPoint(): MESSAGE_REGEX = "Malformed .*: '.*'. It must be of the form '.*'." def test_wrong_spaces(self): with pytest.raises(AEAException, match=self.MESSAGE_REGEX): aea.crypto.registries.register_crypto('crypto_id', ' path.to.module:CryptoClass') w...
def extractMoemclendonWordpressCom(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_typ...
class PayeeBadgeDelegate(QStyledItemDelegate): margin_x = 0 margin_y = 0 def __init__(self, form_context: DetailFormContext, parent: Optional[Any]=None) -> None: super().__init__(parent) self._form_context = form_context def paint(self, painter: QPainter, option: QStyleOptionViewItem, mo...
.slow .parametrize('block_file_name', ['block_1.json', 'block_1234567.json', 'block_.json']) def test_pow_validation_block_headers(block_file_name: str) -> None: block_str_data = cast(bytes, pkgutil.get_data('ethereum', f'assets/blocks/{block_file_name}')).decode() block_json_data = json.loads(block_str_data) ...
def extractDefectivetlsWordpressCom(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_ty...
class TestProtFuncs(BaseEvenniaTest): _settings(PROT_FUNC_MODULES=['evennia.prototypes.protfuncs']) def test_protkey_protfunc(self): test_prot = {'key1': 'value1', 'key2': 2} self.assertEqual(protlib.protfunc_parser('$protkey(key1)', testing=True, prototype=test_prot), 'value1') self.ass...
class ObsSymbolic(ObsBase): def __init__(self, contract_manager, account_manager, dataset_dump_path, backend_loggers): super().__init__(contract_manager, account_manager, dataset_dump_path) self.sym_stat = Stat(contract_manager, account_manager) self.contract_to_storage = {} self.tx_...
def get_es_kdata_index(security_type='stock', exchange='sh', level='day'): if (exchange in ['sh', 'sz']): return '{}_{}_{}_kdata'.format(security_type, 'china', level) elif (exchange in ['nasdaq', 'amex', 'nyse']): return '{}_{}_{}_kdata'.format(security_type, 'usa', level) else: ret...
def test_standard_ignore(): patterns = ['*.pyc', '.cache', '.cache/*', '__pycache__', '**/__pycache__', '*.foo'] ignore = StandardIgnore(root='.', patterns=patterns) assert (not ignore.is_ignored('foo.py')) assert ignore.is_ignored('foo.pyc') assert ignore.is_ignored('.cache/foo') assert ignore....
def test_verify_from_public_key_obj(key_api, private_key): non_recoverable_signature = key_api.ecdsa_sign_non_recoverable(MSGHASH, private_key) recoverable_signature = key_api.ecdsa_sign_non_recoverable(MSGHASH, private_key) public_key = private_key.public_key for signature in (recoverable_signature, no...
def test_hydrate_workflow_template__branch_node(): workflow_template = _core_workflow_pb2.WorkflowTemplate() branch_node = _core_workflow_pb2.Node(id='branch_node', branch_node=_core_workflow_pb2.BranchNode(if_else=_core_workflow_pb2.IfElseBlock(case=_core_workflow_pb2.IfBlock(then_node=_core_workflow_pb2.Node(...
class OptionSeriesBarSonificationTracksMappingLowpassFrequency(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...
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.') .parametrize('map_task_fn', [map_task, array_node_map_task]) def test_everything(map_task_fn): import pandas as pd def get_static_list() -> typing.List[float]: return [3.14, 2.718] def get_list_of_pd(s: int) -> typing.List[pd....
def set_other_config(manager, system_id, key, val, fn): val = str(val) def _set_iface_other_config(tables, *_): row = fn(tables) if (not row): return None other_config = row.other_config other_config[key] = val row.other_config = other_config req = ovsdb_e...
class OptionSeriesBarTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): self._confi...
def register(registry): _IndexedCustomEditor.register(registry) registry.register_interaction(target_class=SimpleEditor, interaction_class=MouseClick, handler=(lambda wrapper, _: mouse_click_qwidget(wrapper._target._button, delay=wrapper.delay))) register_traitsui_ui_solvers(registry, SimpleEditor, _get_nes...
def main(): pages = {} class_names = [] layouts = set() namespace = {} namespace.update(ui.__dict__) namespace.update(ui.layouts.__dict__) namespace.update(ui.widgets.__dict__) namespace.update(ui.pywidgets.__dict__) for mod in namespace.values(): if isinstance(mod, ModuleTyp...
def test_channels(audio, multichannel_format): if (audio.ndim == 1): with tmp.NamedTemporaryFile(delete=False, suffix=('.' + multichannel_format)) as tempfile: stempeg.write_audio(tempfile.name, audio, sample_rate=44100) (loaded_audio, rate) = stempeg.read_stems(tempfile.name) ...
_test def test_local_run() -> None: runner = LocalRunner(module=MyLocalGraph(config=MySinkConfig(output_filename=LOCAL_OUTPUT_FILENAME))) runner.run() remaining_numbers = {str(i) for i in range(NUM_MESSAGES)} with open(LOCAL_OUTPUT_FILENAME, 'r') as output_file: lines = output_file.readlines() ...
class Test_Fixup(): () def fixup(self, *, app): return Fixup(app) def test_fixup_env_enabled(self, *, app, fixup, monkeypatch): monkeypatch.setenv('DJANGO_SETTINGS_MODULE', 'settings') with patch_module('django'): assert fixup.enabled() assert any((isinstance(...
class Etherscan(): def __init__(self, api_key: str) -> None: if (not api_key): raise ValueError('Must provide an API key for Etherscan API access') self.api_key = api_key def get_proxy_api_url(self, network: Network) -> str: return f'{API_URLS[network]}?module=proxy&apikey={s...
class experimenter_stats_reply(stats_reply): subtypes = {} version = 2 type = 19 stats_type = 65535 def __init__(self, xid=None, flags=None, experimenter=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): ...
class Scatter(GraphPlotly.Chart): requirements = ('plotly.js',) __reqJs = ['plotly.js'] def chart(self) -> JsPlotly.Pie: if (self._chart is None): self._chart = JsPlotly.Pie(page=self.page, js_code=self.js_code, component=self) return self._chart def layout(self) -> LayoutGeo...
.xfail(reason='modification to initial allocation made the block fixture invalid') def test_import_block_validation(valid_chain, funded_address, funded_address_initial_balance): block = rlp.decode(valid_block_rlp, sedes=FrontierBlock) (imported_block, _, _) = valid_chain.import_block(block) assert (len(impo...
def ensure_no_static(opcode_fn: Callable[(..., Any)]) -> Callable[(..., Any)]: (opcode_fn) def inner(computation: ComputationAPI) -> Callable[(..., Any)]: if computation.msg.is_static: raise WriteProtection('Cannot modify state while inside of a STATICCALL context') return opcode_fn(...
def extractSubudai11(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('Mai Kitsune Waifu Chapter' in item['title']): return buildReleaseMessageWithType(item, 'My Fox Immortal Wi...
class OptionPlotoptionsPyramidSonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsPyramidSonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPyramidSonificationTracksMappingLowpassFrequency) def resonance(self) -> 'Option...
def get_twitter_client(): app_key = config['twitter']['api_key'] app_secret = config['twitter']['api_secret'] oauth_token = config['twitter']['oauth_token'] oauth_token_secret = config['twitter']['oauth_secret'] return tweepy.Client(consumer_key=app_key, consumer_secret=app_secret, access_token=oaut...
class LoggingGcsCommon(ModelNormal): allowed_values = {} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): return {'user': (str,), 'secret_key': (...
class OptionPlotoptionsItemSonificationContexttracksMappingPan(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 run_distributed(scheduler=None): init_logging(THIS_DIR, scheduler) atoms = ('H', 'H') geoms = list() for i in range(7): bond_length = (0.8 + (i * 0.2)) print(f'{i}: {bond_length:.02f}') coords = np.array((0.0, 0.0, 0.0, 0.0, 0.0, bond_length)) geom = Geometry(atoms, c...
class OptionSeriesScatterSonificationTracksMappingGapbetweennotes(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 test_integration_surfaces(): surfaces = td.FieldProjectionAngleMonitor(size=(2, 0, 2), theta=[1, 2], phi=[0], name='f', freqs=[.0]).integration_surfaces assert (len(surfaces) == 1) assert (surfaces[0].normal_dir == '+') surfaces = td.FieldProjectionAngleMonitor(size=(2, 0, 2), theta=[1, 2], phi=[0],...
def test_replay_decider_respond_query(): service: WorkflowService = Mock() service.respond_query_task_completed = Mock(return_value=(None, None)) decision_task_loop = DecisionTaskLoop(worker=Mock(), service=service) decision_task_loop.respond_query(task_token=b'the-task-token', result=b'the-result', err...
class DeleteMixinTest(QuickbooksUnitTestCase): def test_delete_unsaved_exception(self): from quickbooks.exceptions import QuickbooksException bill = Bill() self.assertRaises(QuickbooksException, bill.delete, qb=self.qb_client) ('quickbooks.mixins.QuickBooks.delete_object') def test_d...
def test_override_ledger_configurations_negative(): agent_config = MagicMock() agent_config.component_configurations = {} expected_configurations = deepcopy(LedgerApis.ledger_api_configs) _override_ledger_configurations(agent_config) actual_configurations = LedgerApis.ledger_api_configs assert (...
class ContourModuleFactory(DataModuleFactory): contours = Any(5, help='Integer/list specifying number/list of\n contours. Specifying a list of values will only\n give the requested contours asked for.') def _contours_changed(self): contour_list = True try: ...
class CleanAfterTestCase(TestCase): ('aea.cli.utils.decorators.os.path.exists', return_value=True) ('aea.cli.utils.decorators._cast_ctx', (lambda x: x)) ('aea.cli.utils.decorators.shutil.rmtree') def test_clean_after_positive(self, rmtree_mock, *mocks): _after def func(click_context): ...
def predictRecallMonteCarlo(prior, tnow, N=(1000 * 1000)): import scipy.stats as stats (alpha, beta, t) = prior tPrior = stats.beta.rvs(alpha, beta, size=N) tnowPrior = (tPrior ** (tnow / t)) (freqs, bins) = np.histogram(tnowPrior, 'auto') bincenters = (bins[:(- 1)] + (np.diff(bins) / 2)) re...
def main(args=None): configLogger(logger=log) parser = argparse.ArgumentParser() parser.add_argument('input', nargs='+', metavar='INPUT') parser.add_argument('-o', '--output') parser.add_argument('-e', '--max-error', type=float, default=MAX_ERR) parser.add_argument('--post-format', type=float, d...
def pull_reddit(args, op): print('') print('# Pull from Reddit') print('') print(f'environment: {os.environ}') def run(): pulling_count = os.getenv('REDDIT_PULLING_COUNT', 25) return op.pull(pulling_count=pulling_count, pulling_interval=0, data_folder=args.data_folder, run_id=args.ru...
def test_ner_silver_to_gold(dataset, spacy_model): silver_dataset = '__test_ner_silver_to_gold__' silver_examples = [{INPUT_HASH_ATTR: 1, TASK_HASH_ATTR: 11, 'text': 'Hello world', 'answer': 'accept', 'spans': [{'start': 0, 'end': 5, 'label': 'PERSON'}]}, {INPUT_HASH_ATTR: 1, TASK_HASH_ATTR: 12, 'text': 'Hello ...
_tag(takes_context=True) def search_results(context, search_results): context.push() try: context.update({'search_results': search_results, 'query': context['query']}) return template.loader.render_to_string('watson/includes/search_results.html', context.flatten()) finally: context.p...
class GammaNormalModel(): def __init__(self, shape: Tensor, rate: Tensor, mu: Tensor) -> None: self.shape_ = shape self.rate_ = rate self.mu_ = mu _variable def gamma(self) -> dist.Distribution: return dist.Gamma(self.shape_, self.rate_) _variable def normal(self) -> ...
def add_version_to_css(app: Sphinx, pagename, templatename, context, doctree): if (app.builder.name != 'html'): return if ('_static/local.css' in context.get('css_files', {})): css = Path(app.srcdir, '_static/local.css').read_text('utf8') hashed = hashlib.sha256(css.encode('utf-8')).hexd...
_required(login_url='/login') def ArticleMe(request): article = Article.objects.filter(authors__follow__fan_id=request.user.id, is_show=True) category = Category_Article.objects.all() type = request.GET.get('type', '') try: page = request.GET.get('page', 1) if type: article =...
def _weights_init(m: nn.Module) -> None: classname = m.__class__.__name__ if (classname.find('Conv') != (- 1)): torch.nn.init.normal_(m.weight, 0.0, 0.02) elif (classname.find('BatchNorm') != (- 1)): torch.nn.init.normal_(m.weight, 1.0, 0.02) torch.nn.init.zeros_(m.bias)
class BaseTestMissingValuesRenderer(TestRenderer): MISSING_VALUES_NAMING_MAPPING = {None: 'Pandas nulls (None, NAN, etc.)', '': '"" (empty string)', np.inf: 'Numpy "inf" value', (- np.inf): 'Numpy "-inf" value'} def _get_number_and_percents_of_missing_values(missing_values_info: DatasetMissingValues) -> pd.Data...
def load(libmagick): libmagick.AcquireExceptionInfo.argtypes = [] libmagick.AcquireExceptionInfo.restype = c_void_p libmagick.AcquireImageInfo.argtypes = [] libmagick.AcquireImageInfo.restype = c_void_p libmagick.CloneImageInfo.argtypes = [c_void_p] libmagick.CloneImageInfo.restype = c_void_p ...
def extractTodstlBlogspotCom(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) in ...
def validate_header(header: Header, parent_header: Header) -> None: parent_has_ommers = (parent_header.ommers_hash != EMPTY_OMMER_HASH) ensure((header.timestamp > parent_header.timestamp), InvalidBlock) ensure((header.number == (parent_header.number + 1)), InvalidBlock) ensure(check_gas_limit(header.gas...
def url_unparse(components): (scheme, netloc, path, query, fragment) = components url = '' if (netloc or (scheme and path.startswith('/'))): if (path and (path[:1] != '/')): path = ('/' + path) url = (('//' + (netloc or '')) + path) elif path: url += path if schem...
class SubcomponentList(PaginationMixin, AgencyBase): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/agency/toptier_code/sub_components.md' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.params_to_validate = ['toptier_code', 'fiscal_year'] _response() ...
class OptionSeriesHeatmapSonificationTracksMappingNoteduration(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...
_os(*metadata.platforms) def main(): svchost = 'C:\\Users\\Public\\svchost.exe' powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' common.copy_file(EXE_FILE, svchost) common.execute([svchost, '/c', 'echo', 'schedule', f';{powershell}', 'C:\\Users\\A'], timeout=5, kill=True) ...
def _add_tests(): import os import os.path import functools this_dir = os.path.dirname(sys.modules[__name__].__file__) packet_data_dir = os.path.join(this_dir, '../../packet_data') json_dir = os.path.join(this_dir, 'json') ofvers = ['of10', 'of12', 'of13', 'of14', 'of15'] cases = set() ...
class queue_op_failed_error_msg(error_msg): version = 4 type = 1 err_type = 9 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...
class TestDeleteIlmPolicyRunner(): params = {'policy-name': 'my-ilm-policy', 'request-params': {'master_timeout': '30s', 'timeout': '30s'}} ('elasticsearch.Elasticsearch') .asyncio async def test_delete_ilm_policy_with_request_params(self, es): es.ilm.delete_lifecycle = mock.AsyncMock(return_val...
class _RichComparison(Matcher): def __init__(self, klass: type, lt: Optional[AnyType]=None, le: Optional[AnyType]=None, eq: Optional[AnyType]=None, ne: Optional[AnyType]=None, ge: Optional[AnyType]=None, gt: Optional[AnyType]=None) -> None: self.klass = klass self.lt = lt self.le = le ...
def load_mnemonic_arguments_decorator(function: Callable[(..., Any)]) -> Callable[(..., Any)]: decorators = [jit_option(callback=validate_mnemonic, help=(lambda : load_text(['arg_mnemonic', 'help'], func='existing_mnemonic')), param_decls='--mnemonic', prompt=(lambda : load_text(['arg_mnemonic', 'prompt'], func='ex...
class OptionSeriesPieSonificationDefaultinstrumentoptionsMappingPlaydelay(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 Event(object): def __init__(self) -> None: self._event_handler = [] def subscribe(self, fn): self._event_handler.append(fn) return self def unsubscribe(self, fn): self._event_handler.remove(fn) return self def __iadd__(self, fn): self._event_handler....
class OptionPlotoptionsHistogramAccessibility(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): ...
class RPCSocket(object): __s = None __reader = None __parser = None def __init__(self, *args, is_unix_socket=False, is_ipv6=False, **kwargs): self.__as_service = False self.__reader = reader.reader() self.__parser = RPCParser() if is_unix_socket: fa = socket.A...
def hash_matches(fname, known_hash, strict=False, source=None): if (known_hash is None): return True algorithm = hash_algorithm(known_hash) new_hash = file_hash(fname, alg=algorithm) matches = (new_hash.lower() == known_hash.split(':')[(- 1)].lower()) if (strict and (not matches)): i...
class JsonConverter(DataConverterBase): def __init__(self): super(JsonConverter, self).__init__() def getName(): return 'json_converter' def collect(self, data, args=None): rows = self._prepareData(data) results = [] valid_run_idxs = [] for row in rows: ...
(Output('configs-output', 'children'), [Input('dash-uploader', 'disabled'), Input('dash-uploader', 'disableDragAndDrop')]) def update_config_states(is_disabled, is_disableDragAndDrop): val_configs = [] if is_disabled: val_configs.append(0) if is_disableDragAndDrop: val_configs.append(1) ...
class ModelsAPI(APIClient): def __init__(self, dbt_runner: BaseDbtRunner): super().__init__(dbt_runner) self.models_fetcher = ModelsFetcher(dbt_runner=self.dbt_runner) def get_models_runs(self, days_back: Optional[int]=7, exclude_elementary_models: bool=False) -> ModelRunsWithTotalsSchema: ...
class Channel(BaseChannel): __slots__ = ['_confirming_deliveries', 'consumer_callback', 'rpc', '_basic', '_connection', '_exchange', '_inbound', '_queue', '_tx', '_die', 'message_build_timeout'] def __init__(self, channel_id, connection, rpc_timeout): super(Channel, self).__init__(channel_id) se...
.parametrize('elasticapm_client', [{'span_compression_enabled': True, 'span_compression_same_kind_max_duration': '5ms', 'span_compression_exact_match_max_duration': '5ms'}], indirect=True) def test_same_kind(elasticapm_client): transaction = elasticapm_client.begin_transaction('test') with elasticapm.capture_sp...
def extractBlackmaskedphantomWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Aloof King', 'Aloof King and Cold (Acting) Queen', 'translated'), ('The Adventures of ...
class OptionSeriesTreegraphMarker(Options): def fillColor(self): return self._config_get(None) def fillColor(self, text: str): self._config(text, js_type=False) def fillOpacity(self): return self._config_get(1) def fillOpacity(self, num: float): self._config(num, js_type=...
def test_stringify_env_args(): preprocessed_messages = {'ENV_VAR_STRING': 'some_string', 'ENV_VAR_BOOLEAN1': True, 'ENV_VAR_BOOLEAN2': False, 'ENV_VAR_INT': 23, 'ENV_VAR_DICT': {'testing': 'is_cool'}, 'ENV_VAR_LIST': ['abc', 'def'], 'ENV_VAR_LIST_OF_DICTS': [{'a': 'b'}]} expected = {'ENV_VAR_STRING': 'some_stri...
.django_db def test_object_class_groups_by_object_classes(client, elasticsearch_account_index, faba_with_two_object_classes_and_two_awards, monkeypatch, helpers): setup_elasticsearch_test(monkeypatch, elasticsearch_account_index) helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) helpers.reset_dabs_cache...
def _upload_firmware_get(test_client, intercom): rv = test_client.get('/upload') assert (b'<h3 class="mb-3">Upload Firmware</h3>' in rv.data), 'upload page not displayed correctly' plugins = intercom.get_available_analysis_plugins() mandatory_plugins = [p for p in plugins if plugins[p][1]] default_p...
class RewardAggregator(RewardAggregatorInterface): def get_interfaces(self) -> List[Type[ABC]]: return [DummyEnvEvents] def summarize_reward(self, maze_state: Optional[MazeStateType]=None) -> float: return sum((e.value for e in self.query_events(DummyEnvEvents.twice_per_step))) def to_scalar...
def normal_normal_conjugate_fixer(bmg: BMGraphBuilder) -> NodeFixer: def _transform_mu(mu: bn.ConstantNode, std: bn.ConstantNode, sigma: bn.ConstantNode, obs: List[bn.Observation]) -> bn.BMGNode: precision_prior = pow(std.value, (- 2.0)) precision_data = (len(obs) * pow(sigma.value, (- 2.0))) ...
class InitCommand(Command): def does_already_exist(self): if os.path.isfile(self.PROJECT_FILE): sys.stdout.write('{warning}A project called {green}{name}{warning} already exists, erase it?{reset} (y/n) '.format(name=self.get_project_name(), green=Fore.GREEN, warning=Fore.WARNING, reset=Style.RES...
def test_training_job_resource_config(): rc = training_job.TrainingJobResourceConfig(instance_count=1, instance_type='random.instance', volume_size_in_gb=25, distributed_protocol=training_job.DistributedProtocol.MPI) rc2 = training_job.TrainingJobResourceConfig.from_flyte_idl(rc.to_flyte_idl()) assert (rc2 ...
('with_commandline', (True, False)) def test_optuna_example(with_commandline: bool, tmpdir: Path) -> None: storage = ('sqlite:///' + os.path.join(str(tmpdir), 'test.db')) study_name = 'test-optuna-example' cmd = ['example/sphere.py', '--multirun', ('hydra.sweep.dir=' + str(tmpdir)), 'hydra.job.chdir=True', ...
def split_dofs(elem): entity_dofs = elem.entity_dofs() ndim = elem.cell.get_spatial_dimension() edofs = [[], []] for key in sorted(entity_dofs.keys()): vals = entity_dofs[key] edim = key try: edim = sum(edim) except TypeError: pass for k in...
def compute_gradient_norm(params: Iterable[torch.Tensor]) -> float: total_norm = 0.0 for p in params: if (p.requires_grad and (np.prod(p.shape) > 0)): param_norm = p.grad.data.norm(2) total_norm += (param_norm.item() ** 2) total_norm = (total_norm ** (1.0 / 2)) return tot...
.parametrize(('provider', 'feature', 'subfeature', 'phase'), global_features(return_phase=True)['ungrouped_providers']) class TestComputeOutput(): def test_output_fake(self, mocker: MockerFixture, provider, feature, subfeature, phase): if (phase == 'create_project'): pytest.skip('create_project ...
class ValveChangePortTestCase(ValveTestBases.ValveTestNetwork): CONFIG = ('\ndps:\n s1:\n%s\n interfaces:\n p1:\n number: 1\n native_vlan: 0x100\n p2:\n number: 2\n native_vlan: 0x200\n permanent_learn: True\n...
def test_custom_mapping(worker): class CustomNameWorkflow(): _method(name='blah') def the_signal_method(self): pass worker.register_workflow_implementation_type(CustomNameWorkflow) assert (CustomNameWorkflow._signal_methods['blah'] == CustomNameWorkflow.the_signal_method)
.parametrize('transfer', [prolong, inject, restrict]) def test_transfer_invalid_level_combo(transfer): m = UnitIntervalMesh(10) mh = MeshHierarchy(m, 2) Vcoarse = FunctionSpace(mh[0], 'DG', 0) Vfine = FunctionSpace(mh[(- 1)], 'DG', 0) if (transfer == restrict): (Vcoarse, Vfine) = (Vcoarse.du...
(accept=('application/json', 'text/json'), renderer='json', error_handler=bodhi.server.services.errors.json_handler) (accept='application/javascript', renderer='jsonp', error_handler=bodhi.server.services.errors.jsonp_handler) def get_release_json(request): id = request.matchdict.get('name') release = Release.g...
class OptionSeriesFunnelSonificationDefaultinstrumentoptionsPointgrouping(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: bo...
class TestDecimalFieldMappings(TestCase): def test_decimal_field_has_decimal_validator(self): class TestSerializer(serializers.ModelSerializer): class Meta(): model = DecimalFieldModel fields = '__all__' serializer = TestSerializer() assert (len(se...
class QdrantDB(BaseVectorDB): BATCH_SIZE = 10 def __init__(self, config: QdrantDBConfig=None): if (config is None): config = QdrantDBConfig() elif (not isinstance(config, QdrantDBConfig)): raise TypeError('config is not a `QdrantDBConfig` instance. Please make sure the ty...
class PubAcc(BasicAuthWithTopicTestCase): def setUp(self): BasicAuthWithTopicTestCase.setUp(self) self.acc = models.PROTO_MQTT_ACC_PUB def test_login_with_pub_acl_public(self): response = self._test_login_with_pub_acl_public() self.assertEqual(response.status_code, 200) def t...
class PairwiseDistance(Metric[PairwiseDistanceResult]): k: int item_features: List[str] def __init__(self, k: int, item_features: List[str], options: AnyOptions=None) -> None: self.k = k self.item_features = item_features super().__init__(options=options) def calculate(self, data...