code
stringlengths
281
23.7M
def check_type_exc(pattern, obj, path=None): try: if isinstance(pattern, (list, tuple)): _check_isinstance(obj, (list, tuple)) if ((len(pattern) == 2) and (pattern[(- 1)] is ...)): cls = pattern[0] for (i, v) in enumerate(obj): chec...
class TrainingState(NamedTuple): policy_params: networks_lib.Params policy_opt_state: optax.OptState value_params: networks_lib.Params value_opt_state: optax.OptState critic_params: networks_lib.Params critic_opt_state: optax.OptState target_critic_params: networks_lib.Params key: types....
def invalidate_iterator(vtable): send_command('create test') send_command('create db') filler = 24 all_killer = 512 for i in xrange(filler): send_command(('store db string %s %s' % (str(i), ('A' * i)))) send_command(('getter db %s %s' % (1, str(all_killer)))) send_getter('empty') ...
def RdYlGn(range, **traits): _data = dict(red=[(0.0, 0., 0.), (0.1, 0., 0.), (0.2, 0., 0.), (0.3, 0., 0.), (0.4, 0., 0.), (0.5, 1.0, 1.0), (0.6, 0., 0.), (0.7, 0., 0.), (0.8, 0.4, 0.4), (0.9, 0., 0.), (1.0, 0.0, 0.0)], green=[(0.0, 0.0, 0.0), (0.1, 0., 0.), (0.2, 0., 0.), (0.3, 0., 0.), (0.4, 0., 0.), (0.5, 1.0, 1....
def test_lp_all_parameters(): nt = typing.NamedTuple('OutputsBC', [('t1_int_output', int), ('c', str)]) def t1(a: int) -> nt: a = (a + 2) return nt(a, ('world-' + str(a))) def t2(a: str, b: str, c: str) -> str: return ((b + a) + c) def wf(a: int, c: str) -> str: (x, y) = ...
def train_val_split(df, n_val_samples: int, filter_out_unseen: bool=False) -> Tuple[(pd.DataFrame, pd.DataFrame)]: if filter_out_unseen: (train, val) = train_test_split(df, test_size=int((1.1 * n_val_samples)), random_state=42) logger.info('Train shape: {}, val shape: {}'.format(train.shape, val.sha...
class Base_MATLAB_Language(Base_Language): def __init__(self, name): super().__init__(name) self.token_kinds.add('NVP_DELEGATE') self.tokens_with_implicit_value.add('NVP_DELEGATE') self.has_nvp_delegate = True self.keywords.add('spmd') self.function_contract_keywords....
def build(fips_dir, proj_dir, cfg_name, target=None, build_tool_args=None): dep.fetch_imports(fips_dir, proj_dir) proj_name = util.get_project_name_from_dir(proj_dir) util.ensure_valid_project_dir(proj_dir) dep.gather_and_write_imports(fips_dir, proj_dir, cfg_name) configs = config.load(fips_dir, pr...
class PopularityBiasResult(MetricResult): k: int normalize_arp: bool current_apr: float current_coverage: float current_gini: float current_distr: Distribution reference_apr: Optional[float] = None reference_coverage: Optional[float] = None reference_gini: Optional[float] = None ...
def main(): heads = 3 key_mask = torch.LongTensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 0]]) (N, L) = key_mask.size() mask = key_mask.view(N, 1, 1, L).repeat(1, heads, L, 1) print('### Only the padding masks ###') print(mask) print(mask.shape) sub_mask = subsequent_mask(L).view(1, 1, L, L).repe...
class OptionSeriesArearangeSonificationContexttracksMappingTremoloSpeed(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 HalfBox(Boxes): description = 'This can be used to create:\n\n* a hanging shelf:\n![HalfBox as hanging shelf](static/samples/HalfBox_Shelf_usage.jpg)\n\n* an angle clamping jig:\n![HalfBox as an angle clamping jig](static/samples/HalfBox_AngleJig_usage.jpg)\n\n* a bookend:\n![HalfBox as a bookend](static/samp...
class MATLAB_Lexer(Token_Generator): def __init__(self, language, mh, content, filename, blockname=None): super().__init__(language, filename, blockname) assert isinstance(content, str) self.text = content self.context_line = self.text.splitlines() self.mh = mh self.l...
class Plugin(plugin.PluginProto): PLUGIN_ID = 518 PLUGIN_NAME = 'Environment - BLE Xiaomi CGG1 Hygrometer (EXPERIMENTAL)' PLUGIN_VALUENAME1 = 'Temperature' PLUGIN_VALUENAME2 = 'Humidity' PLUGIN_VALUENAME3 = 'Battery' def __init__(self, taskindex): plugin.PluginProto.__init__(self, taskin...
def generate_go_ethereum_fixture(destination_dir): with contextlib.ExitStack() as stack: datadir = stack.enter_context(common.tempdir()) keystore_dir = os.path.join(datadir, 'keystore') common.ensure_path_exists(keystore_dir) keyfile_path = os.path.join(keystore_dir, common.KEYFILE_F...
def test_flexx_in_thread4(): res = [] loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app.create_server() def try_start(): try: app.stop() app.start() except RuntimeError: res.append('start-fail') else: res.append('...
class Resources(_common.FlyteIdlEntity): class ResourceName(object): UNKNOWN = _core_task.Resources.UNKNOWN CPU = _core_task.Resources.CPU GPU = _core_task.Resources.GPU MEMORY = _core_task.Resources.MEMORY STORAGE = _core_task.Resources.STORAGE EPHEMERAL_STORAGE = _c...
def test_redis_handler_backend_register_next_step_handler(telegram_bot, private_chat, update_type): if (not REDIS_TESTS): pytest.skip('please install redis and configure redis server, then enable REDIS_TESTS') telegram_bot.next_step_backend = RedisHandlerBackend(prefix='pyTelegramBotApi:step_backend1') ...
def create_router_factory(fides_model: FidesModelType, model_type: str) -> APIRouter: router = APIRouter(prefix=f'{API_PREFIX}/{model_type}', tags=[fides_model.__name__]) (name='Create', path='/', response_model=fides_model, status_code=status.HTTP_201_CREATED, dependencies=[Security(verify_oauth_client_prod, s...
class MergeGraph(BaseGraph): def __init__(self, *args: Dict, input_classes: List): self._args = args self._input_classes = input_classes merged_dag = self._build() super().__init__(merged_dag, whoami='Merged Graph') def _merge_inputs(*args: Dict): key_set = {k for arg in ...
def filter_log_fortianalyzer_setting_data(json): option_list = ['__change_ip', 'access_config', 'alt_server', 'certificate', 'certificate_verification', 'conn_timeout', 'enc_algorithm', 'fallback_to_primary', 'faz_type', 'hmac_algorithm', 'interface', 'interface_select_method', 'ips_archive', 'max_log_rate', 'mgmt_...
class Board(): def _reset(self): self._board = [] self._lock = None for _ in range(8): self._board.append(([EMPTY] * 8)) self._board[3][3] = self._board[4][4] = BLACK self._board[4][3] = self._board[3][4] = WHITE def __init__(self, p=None): self._reset...
def _load_unittest_test_cases(import_module_names: List[str]) -> None: global _unittest_testcase_loaded if _unittest_testcase_loaded: return _unittest_testcase_loaded = True for test_case in _get_all_test_cases(import_module_names): test_method_names = [test_method_name for test_method_n...
class ConflictPredictionMetric(Metric[ConflictPredictionMetricResults]): def calculate(self, data: InputData) -> ConflictPredictionMetricResults: dataset_columns = process_columns(data.current_data, data.column_mapping) prediction_name = dataset_columns.utility_columns.prediction if (predict...
class TestInlineHiliteGuessInline(util.MdCase): extension = ['pymdownx.highlight', 'pymdownx.inlinehilite', 'pymdownx.superfences'] extension_configs = {'pymdownx.highlight': {'guess_lang': 'inline'}, 'pymdownx.inlinehilite': {'css_class': 'inlinehilite', 'style_plain_text': True}} def test_guessing_inline(...
class ExtendedLoopingCall(LoopingCall): start_delay = None callcount = 0 def start(self, interval, now=True, start_delay=None, count_start=0): assert (not self.running), 'Tried to start an already running ExtendedLoopingCall.' if (interval < 0): raise ValueError('interval must be...
_action_type(ofproto.OFPAT_METER, ofproto.OFP_ACTION_METER_SIZE) class OFPActionMeter(OFPAction): def __init__(self, meter_id, type_=None, len_=None): super(OFPActionMeter, self).__init__() self.meter_id = meter_id def parser(cls, buf, offset): (type_, len_, meter_id) = struct.unpack_fro...
def run_cmd(cmd, show_output=True, raise_errs=True, **kwargs): internal_assert((cmd and isinstance(cmd, list)), 'console commands must be passed as non-empty lists') if hasattr(shutil, 'which'): cmd[0] = (shutil.which(cmd[0]) or cmd[0]) logger.log_cmd(cmd) try: if (show_output and raise_...
class MonitorManager(): def __init__(self, requested_monitors): self.initiate_monitors(requested_monitors) def initiate_monitors(self, additional_monitors): logging.info('initiating monitors: [%s]', ','.join(additional_monitors)) self.memorymap_monitor = MemorymapMonitor() self.m...
def extractGstranslationWordpressCom(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_t...
def test_sine_wave(wave: WaveformGenerator, scope: Oscilloscope): frequency = 500 wave.load_function('SI1', 'sine') wave.generate('SI1', frequency) time.sleep(0.1) (x, y) = scope.capture(1, 10000, 1, trigger=0) def expected_f(x, amplitude, frequency, phase): return (amplitude * np.sin(((...
((sys.platform == 'win32'), reason='does not run on windows') ('shell,script,comp_func', [('bash', 'tests/scripts/test_bash_install_uninstall.sh', 'hydra_bash_completion'), ('fish', 'tests/scripts/test_fish_install_uninstall.fish', 'hydra_fish_completion')]) def test_install_uninstall(shell: str, script: str, comp_func...
class OptionPlotoptionsFunnel3dTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionPlotoptionsFunnel3dTooltipDatetime...
class TestPutSettings(): ('elasticsearch.Elasticsearch') .asyncio async def test_put_settings(self, es): es.cluster.put_settings = mock.AsyncMock() params = {'body': {'transient': {'indices.recovery.max_bytes_per_sec': '20mb'}}} r = runner.PutSettings() (await r(es, params)) ...
class Creator(object): DEFAULT_STORAGE_PATH = os.path.expanduser('~/.elasticluster/storage') DEFAULT_STORAGE_TYPE = 'yaml' def __init__(self, conf, storage_path=None, storage_type=None): self.cluster_conf = conf['cluster'] self.storage_path = (os.path.expandvars(os.path.expanduser(storage_pa...
def fewshot_cfg_string(): return f''' [nlp] lang = "en" pipeline = ["llm"] batch_size = 128 [components] [components.llm] factory = "llm" [components.llm.task] _tasks = "spacy.SpanCat.v2" labels = ["PER", "ORG", "LOC"] [components.llm.task.examples] = "spacy.FewShotR...
class _coconut(object): import collections, copy, functools, types, itertools, operator, threading, os, warnings, contextlib, traceback, weakref, multiprocessing, inspect from multiprocessing import dummy as multiprocessing_dummy if (_coconut_sys.version_info < (3, 2)): try: from backpor...
def sign(wheelfile, replace=False, get_keyring=get_keyring): warn_signatures() (WheelKeys, keyring) = get_keyring() ed25519ll = signatures.get_ed25519ll() wf = WheelFile(wheelfile, append=True) wk = WheelKeys().load() name = wf.parsed_filename.group('name') sign_with = wk.signers(name)[0] ...
def init_arg(): parser = argparse.ArgumentParser() parser.add_argument('--exe', help='python interpreter to use') parser.add_argument('--it', default=10000, type=int) parser.add_argument('--kk', default=1) parser.add_argument('--alpha') parser.add_argument('-o') parser.add_argument('--projdi...
def _translate_glob(pat): translated_parts = [] for part in _iexplode_path(pat): translated_parts.append(_translate_glob_part(part)) os_sep_class = ('[%s]' % re.escape(SEPARATORS)) res = _join_translated(translated_parts, os_sep_class) return '(?ms){res}\\Z'.format(res=res)
class FaucetUntaggedACLMirrorDefaultAllowTest(FaucetUntaggedACLMirrorTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n unicast_flood: False\nacls:\n 1:\n - rule:\n actions:\n mirror: %(port_3)d\n' CONFIG = '\n interfaces:\n ...
.parametrize(('list_of_objects', 'expected_result'), [([entry_1, entry_2], GRAPH_PART), ([entry_1, entry_2, entry_3], GRAPH_PART_SYMLINK)]) def test_create_graph_nodes_and_groups(list_of_objects, expected_result): assert (create_data_graph_nodes_and_groups(list_of_objects, WHITELIST) == expected_result)
class ProfileReport(): calls: int total_time: int children: Dict[(str, 'ProfileReport')] parent: Optional['ProfileReport'] def __init__(self) -> None: self.calls = 0 self.total_time = 0 self.children = {} self.parent = None def _to_string(self, indent: str) -> str...
class OptionPlotoptionsFunnel3dLabel(Options): def boxesToAvoid(self): return self._config_get(None) def boxesToAvoid(self, value: Any): self._config(value, js_type=False) def connectorAllowed(self): return self._config_get(False) def connectorAllowed(self, flag: bool): s...
class ExecutionParameters(object): (init=False) class Builder(object): stats: taggable.TaggableStats attrs: typing.Dict[(str, typing.Any)] decks: List[Deck] raw_output_prefix: Optional[str] = None execution_id: typing.Optional[_identifier.WorkflowExecutionIdentifier] = No...
def _wasserstein_distance_norm(reference_data: pd.Series, current_data: pd.Series, feature_type: ColumnType, threshold: float) -> Tuple[(float, bool)]: norm = max(np.std(reference_data), 0.001) wd_norm_value = (stats.wasserstein_distance(reference_data, current_data) / norm) return (wd_norm_value, (wd_norm_...
def extractUminovelBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('With contract Skill many Brides!', 'With contract Skill many Brides!', 'translated'), ('WCSB', 'W...
def test_install_package(np_path): assert (ethpm.get_installed_packages(np_path) == ([], [])) ethpm.install_package(np_path, 'ipfs://testipfs-math') assert np_path.joinpath('contracts/math/Math.sol').exists() assert (ethpm.get_installed_packages(np_path) == ([('math', '1.0.0')], []))
class OptionSeriesFunnelSonificationContexttracksActivewhen(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, num: float): ...
class FlexibleTargeting(AbstractObject): def __init__(self, api=None): super(FlexibleTargeting, self).__init__() self._isFlexibleTargeting = True self._api = api class Field(AbstractObject.Field): behaviors = 'behaviors' college_years = 'college_years' connections...
class Test_mac(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_mac_is_multicast(self): addr = b'\x01#Eg\x89\n' val = True res = mac.is_multicast(addr) eq_(val, res) def test_mac_haddr_to_str(self): addr = 'aa:aa:aa:aa:aa...
class OptionSeriesBellcurveSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesBellcurveSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesBellcurveSonificationContexttracksMappingLowpassFrequency) def resonance(self...
class DecadePopupController(OptionsController): def __init__(self, plugin, album_model): super(DecadePopupController, self).__init__() self._album_model = album_model self.plugin = plugin self._spritesheet = None cl = CoverLocale() cl.switch_locale(cl.Locale.LOCALE_DO...
def test_get_sub_awards_csv_sources(db): original = VALUE_MAPPINGS['sub_awards']['filter_function'] VALUE_MAPPINGS['sub_awards']['filter_function'] = MagicMock(returned_value='') csv_sources = download_generation.get_download_sources({'download_types': ['sub_awards'], 'filters': {'award_type_codes': list(aw...
class Profile(MethodView): _required def get(self): result = {} try: result['user'] = current_user.username result['admin'] = current_user.is_admin result['email'] = current_user.email except AttributeError: abort(404) return (jsoni...
class PipelineRunner(): def __init__(self, runner, max_concurrent_jobs=4, poll_interval=30, jobCompletionHandler=None, groupCompletionHandler=None): self.__runner = runner self.max_concurrent_jobs = max_concurrent_jobs self.poll_interval = poll_interval self.groups = [] self....
def test_set_get_text_alignment(): with Drawing() as ctx: ctx.text_alignment = 'center' assert (ctx.text_alignment == 'center') with raises(TypeError): ctx.text_alignment = with raises(ValueError): ctx.text_alignment = 'not-a-text-alignment-type'
def extract_hash_from_duns_or_uei(duns_or_uei): if (len(duns_or_uei) == 9): qs_hash = RecipientLookup.objects.filter(duns=duns_or_uei).values('recipient_hash').first() if (len(duns_or_uei) == 12): qs_hash = RecipientLookup.objects.filter(uei=duns_or_uei.upper()).values('recipient_hash').first() ...
class OptionPlotoptionsHeatmapSonificationDefaultinstrumentoptionsPointgrouping(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, fl...
def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=(), config=None): if (not frames): frame = (start_frame if (start_frame is not None) else inspect.currentframe().f_back) frames = _walk_stack(frame) max_frames = (config.stack_trace_limit if config else (- 1)) stop...
def get_mmseqs_version(): mmseqs_version = None cmd = f'{MMSEQS2} version' try: completed_process = run(cmd, capture_output=True, check=True, shell=True) if (completed_process is not None): mmseqs_version = f"MMseqs2 version found: {completed_process.stdout.decode('utf-8').strip(...
class OPtionsHierarchical(DataClass): def enabled(self): return self._attrs['enabled'] def enabled(self, val): self._attrs['enabled'] = val def levelSeparation(self): return self._attrs['levelSeparation'] def levelSeparation(self, val): self._attrs['levelSeparation'] = va...
def test_no_exo_floor_div_triangular_access(golden): def foo(N: size, x: f32[(N, N)]): for ii in seq(0, (N % 4)): for joo in seq(0, ((ii + ((N / 4) * 4)) / 16)): x[(ii, joo)] = 0.0 (c_file, h_file) = compile_procs_to_strings([foo], 'test.h') code = f'''{h_file} {c_file}''...
def extractLptransPassionstampCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Legend of the Continental Heroes', 'Legend of the Continental Heroes', 'translated'), ('PRC', ...
.django_db def test_spending_by_award_tas_dates(client, monkeypatch, elasticsearch_award_index, mock_tas_data): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) data = {'filters': {'tas_codes': [{'aid': '028', 'main': '8006', 'bpoa': '2011'}], 'award_type_codes': ['A', 'B', 'C', 'D']}, 'fields':...
def test_delete_stream_admin(db, client, admin_jwt): stream = get_stream(db) response = client.delete(f'/v1/video-streams/{stream.id}', content_type='application/vnd.api+json', headers=admin_jwt) assert (response.status_code == 200) stream = VideoStream.query.get(stream.id) assert (stream == None)
('cuda.var.gen_function') def var_gen_function(func_attrs) -> str: bessel = ('true' if func_attrs['unbiased'] else 'false') backend_spec = CUDASpec() output_type = func_attrs['outputs'][0]._attrs['dtype'] elem_output_type = backend_spec.dtype_to_lib_type(output_type) acc_type = 'float' if (Targe...
class OptionPlotoptionsSolidgaugeSonificationTracksPointgrouping(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): ...
class SagemakerTrainingJobConfig(object): training_job_resource_config: _training_job_models.TrainingJobResourceConfig algorithm_specification: _training_job_models.AlgorithmSpecification should_persist_output: typing.Callable[([DistributedTrainingContext], bool)] = (lambda dctx: (dctx.current_host == dctx....
class SparkPSI(SparkStatTestImpl): base_stat_test = psi_stat_test def __call__(self, data: SpartStatTestData, feature_type: ColumnType, threshold: float) -> StatTestFuncReturns: cur = data.current_data ref = data.reference_data column_name = data.column_name (reference_percents, ...
def run_dev_modal_com(): modal_run_cmd = ['modal', 'serve', 'app'] try: console.print(f" [bold cyan]Running FastAPI app with command: {' '.join(modal_run_cmd)}[/bold cyan]") subprocess.run(modal_run_cmd, check=True) except subprocess.CalledProcessError as e: console.print(f' [bold re...
('dftbp') .parametrize('root, ref_energy, ref_norm', [(None, (- 19.), 0.), (1, (- 19.), 0.)]) def test_cytosin_es_forces(root, ref_energy, ref_norm): geom = geom_loader('lib:cytosin.xyz') calc_kwargs = {'parameter': 'mio-ext', 'root': root, 'track': bool(root)} calc = DFTBp(**calc_kwargs) geom.set_calcu...
_handler(commands=['find']) def find(message: types.Message): global freeid if (message.chat.id not in users): bot.send_message(message.chat.id, 'Finding...') if (freeid is None): freeid = message.chat.id else: bot.send_message(message.chat.id, 'Founded!') ...
class TableQueryValues(SqlTree): type: Type name: str rows: list def _compile(self, qb): if (qb.target != 'bigquery'): values_cls = Values fields = [Name(col_type, col_name) for (col_name, col_type) in self.type.elems.items()] else: values_cls = BigQue...
_deserializable class TextChunker(BaseChunker): def __init__(self, config: Optional[ChunkerConfig]=None): if (config is None): config = ChunkerConfig(chunk_size=300, chunk_overlap=0, length_function=len) text_splitter = RecursiveCharacterTextSplitter(chunk_size=config.chunk_size, chunk_o...
.django_db def test_federal_account_content(client, fixture_data): resp = client.get('/api/v2/federal_accounts/999-0009/', data={'fiscal_year': 2022}) expected_result = {'fiscal_year': '2022', 'id': 9999, 'agency_identifier': '999', 'main_account_code': '0009', 'account_title': 'Custom 99', 'federal_account_cod...
class FIRE(Optimizer): def __init__(self, geometry, dt=0.1, dt_max=1, N_acc=2, f_inc=1.1, f_acc=0.99, f_dec=0.5, n_reset=0, a_start=0.1, **kwargs): self.dt = dt self.dt_max = dt_max self.N_acc = N_acc self.f_inc = f_inc self.f_acc = f_acc self.f_dec = f_dec se...
class HddUsage(SensorInterface): def __init__(self, hostname='', interval=30.0, warn_level=0.95): self._hdd_usage_warn = warn_level self._path = LOG_PATH SensorInterface.__init__(self, hostname, sensorname='HDD Usage', interval=interval) def reload_parameter(self, settings): self...
class OptionSeriesAreasplinerangeSonificationDefaultinstrumentoptionsMappingLowpass(Options): def frequency(self) -> 'OptionSeriesAreasplinerangeSonificationDefaultinstrumentoptionsMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesAreasplinerangeSonificationDefaultinstrumentopt...
class _TestController(ControllerBase): def __init__(self, req, link, data, **config): super(_TestController, self).__init__(req, link, data, **config) eq_(data['test_param'], 'foo') ('test', '/test/{dpid}', methods=['GET'], requirements={'dpid': dpidlib.DPID_PATTERN}) def test_get_dpid(self,...
def test_init_identity_negative(): name = 'some_name' address_1 = 'some_address' addresses_1 = {'some_ledger_id': 'some_address'} addresses_2 = {} public_key_1 = 'some_public_key' public_keys_1 = {'some_ledger_id': 'some_public_key'} public_keys_2 = {} with pytest.raises(ValueError, matc...
def test_working_hours_argument_data_is_not_in_correct_range1(): import copy from stalker import defaults wh = copy.copy(defaults.working_hours) wh['sun'] = [[(- 10), 1000]] with pytest.raises(ValueError) as cm: WorkingHours(working_hours=wh) assert (str(cm.value) == 'WorkingHours.workin...
.parametrize('address, slot, new_value', ((INVALID_ADDRESS, 0, 0), (ADDRESS, b'\x00', 0), (ADDRESS, 0, b'\x00'), (ADDRESS, 0, None), (ADDRESS, None, 0))) def test_set_storage_input_validation(state, address, slot, new_value): with pytest.raises(ValidationError): state.set_storage(address, slot, new_value)
class ForceReply(JsonSerializable): def __init__(self, selective: Optional[bool]=None, input_field_placeholder: Optional[str]=None): self.selective: bool = selective self.input_field_placeholder: str = input_field_placeholder def to_json(self): json_dict = {'force_reply': True} i...
class PatchConfig(): def __init__(self, config_overwrite: 'dict | None'=None, initial_config_overwrite: 'dict | None'=None, read_initial: bool=False): self.initial_config_overwrite = initial_config_overwrite self.config_overwrite = config_overwrite self.read_initial = read_initial se...
def has_been_completed_by(poll, user): user_votes = TopicPollVote.objects.filter(poll_option__poll=poll) if user.is_anonymous: forum_key = get_anonymous_user_forum_key(user) user_votes = (user_votes.filter(anonymous_key=forum_key) if forum_key else user_votes.none()) else: user_votes...
def write_date(f, t_millis): write_scalar(f, datetime.datetime.now().strftime('%H%M%S.%f')) write_scalar(f, t_millis) write_vector(f, rover.x) write_vector(f, rover.v) write_vector(f, rover.a) write_vector(f, rover.W) write_3x3(f, rover.R) write_vector(f, rover.control.xd) write_vect...
def test_short_deck_1(): n_players = 3 (state, _) = _new_game(n_players=n_players) player_i_order = [2, 0, 1] for i in range(n_players): assert (state.current_player.name == f'player_{player_i_order[i]}') assert (len(state.legal_actions) == 3) assert (state.betting_stage == 'pre_...
class FunctionCall(Expression, TupleMixin): expression: Expression arguments: List[Expression] names: List[str] is_local = synthesized() call_type = synthesized() call_info = synthesized() def call_info(self, arguments: {Expression.expression_value, Expression.cfg}): argument_values ...
def encode(ffrom, fto, data_segment): ffrom = BytesIO(file_read(ffrom)) fto = BytesIO(file_read(fto)) (from_call0, from_data_pointers, from_code_pointers) = disassemble(ffrom, data_segment.from_data_offset_begin, data_segment.from_data_offset_end, data_segment.from_data_begin, data_segment.from_data_end, da...
def extractTheSunIsColdTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('108 maidens' in item['tags']): return buildReleaseMessageWithType(item, '108 Maidens of Des...
def render_contacts(pb_client, model, scale_h=0.0005, scale_r=0.01, color=[1.0, 0.1, 0.0, 0.5]): data = pb_client.getContactPoints(model) for d in data: (p, n, l) = (np.array(d[6]), np.array(d[7]), d[9]) p1 = p p2 = (p + ((n * l) * scale_h)) gl_render.render_arrow(p1, p2, D=scale...
class VGG(object): def __init__(self, weights_path, layers=VGG19_LAYERS): self.weights = load_vgg_weights(weights_path) self.layers = layers def forward(self, image): idx = 0 net = {} current = image for name in self.layers: kind = name[:4] ...
def put(domain: str, key: str, value: str) -> None: conn = _db_conn() conn.execute('UPDATE ghstack_cache SET value = ? WHERE domain = ? AND key = ?', (value, domain, key)) c = conn.execute('\n INSERT INTO ghstack_cache (domain, key, value)\n SELECT ?, ?, ? WHERE (SELECT Changes() = 0)\n ...
def read_mac(esp, args): def print_mac(label, mac): print(('%s: %s' % (label, ':'.join(map((lambda x: ('%02x' % x)), mac))))) eui64 = esp.read_mac('EUI64') if eui64: print_mac('MAC', eui64) print_mac('BASE MAC', esp.read_mac('BASE_MAC')) print_mac('MAC_EXT', esp.read_mac('MAC...
class TrafficMatrixSequence(object): def __init__(self, interval=None, t_unit='min'): self.attrib = {} if (interval is not None): if (not (t_unit in time_units)): raise ValueError('The t_unit argument is not valid') self.attrib['interval'] = interval ...
def test_act_serialization(): msg = GymMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=GymMessage.Performative.ACT, action=GymMessage.AnyObject('some_action'), step_id=1) msg.to = 'receiver' envelope = Envelope(to=msg.to, sender='sender', message=msg) envelope_bytes = envel...
def test_well_gridprops_zone(loadwell1): grid = xtgeo.grid_from_file('../xtgeo-testdata/3dgrids/reek/reek_sim_grid.roff') gridzones = xtgeo.gridproperty_from_file('../xtgeo-testdata/3dgrids/reek/reek_sim_zone.roff', grid=grid) gridzones.name = 'Zone' well = loadwell1 well.get_gridproperties(gridzone...
def query_exchange(in_domain: str, out_domain: str, session: Session, target_datetime: (datetime | None)=None) -> (str | None): params = {'documentType': 'A11', 'in_Domain': in_domain, 'out_Domain': out_domain} return query_ENTSOE(session, params, target_datetime=target_datetime, function_name=query_exchange.__...
class _SSLContext(object): def __init__(self, protocol): self._protocol = protocol self._certfile = None self._keyfile = None self._password = None def load_cert_chain(self, certfile, keyfile=None, password=None): self._certfile = certfile self._keyfile = (keyfile...