code
stringlengths
281
23.7M
('input_conf, passthrough, expected', [param({'node': {'_target_': 'tests.instantiate.AClass', 'a': '${value}', 'b': 20, 'c': 30, 'd': 40}, 'value': 99}, {}, AClass(99, 20, 30, 40), id='interpolation_into_parent'), param({'node': {'_target_': 'tests.instantiate.AClass', '_partial_': True, 'a': '${value}', 'b': 20}, 'va...
class CodeGenerator(NodeVisitor): def __init__(self, environment, name, filename, stream=None, defer_init=False, optimized=True): if (stream is None): stream = NativeStringIO() self.environment = environment self.name = name self.filename = filename self.stream = ...
class KeyfileCreds(BaseModel): type: Optional[str] = None project_id: str = Field(title='Project ID') private_key_id: Optional[str] = Field(None, title='Private Key ID') private_key: Optional[str] = Field(None, sensitive=True) client_email: Optional[EmailStr] = None client_id: Optional[str] = Fi...
def formatter(record): extra = record['extra'] scheme = extra.get('scheme', None) def ifextra(keys, pattern='{}'): keys = to_iterable(keys) if all(((k in extra) for k in keys)): return pattern.format(*[f'{{extra[{k}]}}' for k in keys]) else: return '' if (...
class PostDisapproveView(PermissionRequiredMixin, SingleObjectTemplateResponseMixin, BaseDetailView): context_object_name = 'post' model = Post success_message = _('This post has been disapproved successfully.') template_name = 'forum_moderation/moderation_queue/post_disapprove.html' def disapprove(...
(no_gui_test_assistant, 'No GuiTestAssistant') class TestEventTimer(TestCase, GuiTestAssistant): def setUp(self): GuiTestAssistant.setUp(self) def tearDown(self): GuiTestAssistant.tearDown(self) def test_basic(self): timer = EventTimer() self.assertIsNone(timer.repeat) ...
class TableFormatter(): def __init__(self, header, fmts, min_width=7, space=3): self.min_width = (min_width + (space - 1)) self.space = space widths = np.array([len(h) for h in header]) smaller_indices = (widths < min_width) widths[smaller_indices] = min_width self.wi...
def test_basic_forwarding2(golden): def filter1D(ow: size, kw: size, x: f32[((ow + kw) - 1)], y: f32[ow], w: f32[kw]): for o in seq(0, ow): sum: f32 sum = 0.0 for k in seq(0, kw): sum += (x[(o + k)] * w[k]) y[o] = sum filter1D = divide_loop...
def fetch_crlf_payload(): payload_list = [] if (os.getcwd().split('/')[(- 1)] == 'API'): path = '../Payloads/crlf.txt' else: path = 'Payloads/crlf.txt' with open(path) as f: for line in f: if line: payload_list.append(line.rstrip()) return payload_...
def test_non_elasticsearch_cached_download_not_found(common_test_data): external_load_dates = [{'external_data_type__external_data_type_id': EXTERNAL_DATA_TYPE_DICT['fabs'], 'last_load_date': datetime(2021, 1, 30, 12, 0, 0, 0, timezone.utc)}, {'external_data_type__external_data_type_id': EXTERNAL_DATA_TYPE_DICT['fp...
((detect_target().name() == 'rocm'), 'Not supported by ROCM.') class GroupGEMMRcrBiasActTestCase(unittest.TestCase): ([param('group_gemm_rcr_bias_relu_fp16', 'float16', 'relu'), param('group_gemm_rcr_bias_relu_fp32_sm80', 'float32', 'relu'), param('group_gemm_rcr_bias_relu_bf16', 'bfloat16', 'relu'), param('group_g...
def debug(func: Callable[(..., Any)]) -> Callable[(..., Any)]: (func) def _wrapper(*args: Any, **kwargs: Any) -> Any: print(f"<debug> Calling '{func.__name__}' with args={args} and kwargs={kwargs}") result = func(*args, **kwargs) print(f"<debug> '{func.__name__}' returned {result}") ...
class op(bpy.types.Operator): bl_idname = 'uv.textools_color_convert_to_texture' bl_label = 'Pack Texture' bl_description = 'Pack ID Colors into single texture and UVs' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): if (bpy.context.area.ui_type != 'UV'): return False ...
_memory_db def test_add_role(prompt, capsys): action_and_inputs = ['create_user', 'test_user', 'list_all_users', 'add_role_to_user', 'test_user', 'guest_analyst', 'list_all_users', 'exit'] for action in action_and_inputs: prompt.input.send_text(f'''{action} ''') (test_app, store, db) = _setup_fronte...
class OptionPlotoptionsDumbbellSonificationDefaultspeechoptionsMappingRate(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 gather_dependent_entities(serialized: OrderedDict) -> Tuple[(Dict[(_identifier_model.Identifier, TaskTemplate)], Dict[(_identifier_model.Identifier, admin_workflow_models.WorkflowSpec)], Dict[(_identifier_model.Identifier, _launch_plan_models.LaunchPlanSpec)])]: task_templates: Dict[(_identifier_model.Identifie...
class WorkflowMetadataDefaults(_common.FlyteIdlEntity): def __init__(self, interruptible=None): self._interruptible = interruptible def interruptible(self): return self._interruptible def to_flyte_idl(self): return _core_workflow.WorkflowMetadataDefaults(interruptible=self._interrupt...
class TestHighlightStrip(util.MdCase): extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = {'pymdownx.highlight': {'stripnl': False}} def test_no_stripnl(self): self.check_markdown('\n ```py\n\n import foo\n\n\n import bar\n\n\n\n ...
class TestAXI(unittest.TestCase): def _test_axi2native(self, naccesses=16, simultaneous_writes_reads=False, id_rand_enable=False, len_rand_enable=False, data_rand_enable=False, aw_valid_random=0, w_valid_random=0, ar_valid_random=0, r_valid_random=0, w_ready_random=0, b_ready_random=0, r_ready_random=0): de...
.skipif((django.VERSION > (1, 7)), reason='argparse raises CommandError in this case') ('elasticapm.contrib.django.management.commands.elasticapm.Command._get_argv') def test_subcommand_not_set(argv_mock): stdout = io.StringIO() argv_mock.return_value = ['manage.py', 'elasticapm'] call_command('elasticapm',...
class NetworkNodeMonHistorySerializer(MonHistorySerializer): nic = s.CharField(required=True) def validate(self, attrs): nic = attrs.get('nic') assert nic if (nic in self.obj.used_nics): self.item_id = nic else: raise s.ValidationError(_('NIC not defined o...
def xml_check_text_content(xml_doc_a, xml_doc_b, xpath): if ((xml_doc_a.nodeType == xml_doc_a.TEXT_NODE) or (xml_doc_a.nodeType == xml_doc_a.CDATA_SECTION_NODE)): if (xml_doc_a.data != xml_doc_b.data): return (False, ('Text Node data differs [%s] != [%s] at [%s]' % (xml_doc_a.data, xml_doc_b.dat...
def find_json_objects(text): json_objects = [] inside_string = False escape_character = False stack = [] start_index = (- 1) for (i, char) in enumerate(text): if ((char == '\\') and (not escape_character)): escape_character = True continue if ((char == '"'...
def _output_deck(task_name: str, new_user_params: ExecutionParameters): ctx = FlyteContext.current_context() local_dir = ctx.file_access.get_random_local_directory() local_path = f'{local_dir}{os.sep}{DECK_FILE_NAME}' try: with open(local_path, 'w', encoding='utf-8') as f: f.write(_g...
def get_wrap_config(view: sublime.View, pos: int) -> Config: syntax_name = syntax.doc_syntax(view) config = get_config(view, pos) config.syntax = syntax_name config.type = 'markup' if syntax.is_html(syntax_name): config.context = get_html_context(view, pos) return config
class ACLTestCase(TestCase): def setUp(self): self.username = 'user' self.password = 'password' User.objects.create_user(self.username, password=self.password) self.url_testing = reverse('django_mqtt:mqtt_acl') self.client = Client() _settings(MQTT_ACL_ALLOW=True) def...
class OptionSeriesColumnSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesColumnSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesColumnSonificationContexttracksMappingLowpassFrequency) def resonance(self) -> 'Opt...
class OptionPlotoptionsTreemapSonificationTracksMappingPitch(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...
class TestGANModule(unittest.TestCase): def test_module_without_dimension(self, tmp_dir: str) -> None: module = TestModule() trainer = Trainer(default_root_dir=tmp_dir, fast_dev_run=True, callbacks=[TensorboardGenerativeModelImageSampler()]) with self.assertRaises(AssertionError): ...
_action_type(ofproto.OFPAT_SET_NW_TTL, ofproto.OFP_ACTION_NW_TTL_SIZE) class OFPActionSetNwTtl(OFPAction): def __init__(self, nw_ttl, type_=None, len_=None): super(OFPActionSetNwTtl, self).__init__() self.nw_ttl = nw_ttl def parser(cls, buf, offset): (type_, len_, nw_ttl) = struct.unpack...
_comparable class Forum(db.Model, CRUDMixin): __tablename__ = 'forums' id = db.Column(db.Integer, primary_key=True) category_id = db.Column(db.Integer, db.ForeignKey('categories.id', ondelete='CASCADE'), nullable=False) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Tex...
def apply_weights(cnarr, ref_matched, log2_key, spread_key, epsilon=0.0001): logging.debug('Weighting bins by size and overall variance in sample') simple_wt = np.zeros(len(cnarr)) is_anti = cnarr['gene'].isin(params.ANTITARGET_ALIASES) tgt_cna = cnarr[(~ is_anti)] tgt_var = (descriptives.biweight_m...
class TestLimitedWorkerManager(BaseTestWorkerManager): limits = [] def setup_worker_manager(self): self.limits = [PredicateWorkerLimit((lambda x: x.is_odd), 3, name='odd'), PredicateWorkerLimit((lambda x: (not x.is_odd)), 2, name='even')] self.worker_manager = ToyWorkerManager(redis_connection=s...
class AddBosEosPreEncoder(PreEncoder): def __init__(self, *, bos_piece: Optional[str], eos_piece: Optional[str]): self.bos_piece = bos_piece self.eos_piece = eos_piece def __call__(self, chunks: Iterable[InputChunks]) -> List[InputChunks]: bos_eos_chunks = [] for seq_chunks in ch...
class HeaderFunction(): def __init__(self, path=None, name=None, arguments=None, types: dict=None, imports=None): if (path is not None): self.path = path with open(path) as file: lines = file.readlines() last_line = lines[(- 1)] assert last_lin...
_overwritable() def build_mapped_train_loader(cfg, mapper): if (cfg.DATALOADER.SAMPLER_TRAIN == 'WeightedTrainingSampler'): data_loader = build_weighted_detection_train_loader(cfg, mapper=mapper) elif (cfg.DATALOADER.SAMPLER_TRAIN == 'WeightedCategoryTrainingSampler'): data_loader = build_weight...
class OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingTremolo(Options): def depth(self) -> 'OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingTremoloDepth) def ...
def run_app_with_daemon(fd, is_gui, config_options): with app_state.async_ as async_: d = daemon.Daemon(fd, is_gui) app_state.app.setup_app() d.start() try: app_state.app.run_app() except KeyboardInterrupt: pass finally: d.stop() ...
def iter_hmm_hits(hmmfile, cpus, servers, dbtype=DB_TYPE_HMM, evalue_thr=None, score_thr=None, max_hits=None, skip=None, maxseqlen=None, fixed_Z=None, cut_ga=False, silent=False): pool = multiprocessing.Pool(cpus) for r in pool.imap(iter_hmm, ([hmmnum, hmmer_version, name, leng, model, servers, dbtype, evalue_t...
class InstagramInsightsResult(AbstractCrudObject): def __init__(self, fbid=None, parent_id=None, api=None): self._isInstagramInsightsResult = True super(InstagramInsightsResult, self).__init__(fbid, parent_id, api) class Field(AbstractObject.Field): description = 'description' id...
class TestGenericLedgerApiHandler(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'generic_seller') is_agent_to_agent_messages = False def setup(cls): super().setup() cls.ledger_api_handler = cast(GenericLedgerApiHandler, cls._skill.skill_context.handlers....
def swap(self, context, island_stats_source): selection_mode = bpy.context.scene.tool_settings.uv_select_mode bm = bmesh.from_edit_mesh(bpy.context.active_object.data) uv_layers = bm.loops.layers.uv.verify() islands_all = utilities_uv.getAllIslands(bm, uv_layers) islands_equal = [] for island in...
def extractBoredtranslationsHomeBlog(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_unexpected_close(unused_tcp_port, ws): async def handler(websocket, path): (await websocket.close()) ws('localhost', unused_tcp_port, handler) with ExitStack() as stack: duplexer = SyncWebsocketDuplexer(f'ws://localhost:{unused_tcp_port}', f'ws://localhost:{unused_tcp_port}', None, ...
class RoleSwitch(unittest.TestCase): def setUp(self): host = config['controller_host'] self.controllers = [controller.Controller(host=host, port=6633), controller.Controller(host=host, port=6634)] def runTest(self): for con in self.controllers: con.start() if (not...
class VlanExact(MatchTest): def runTest(self): match = ofp.match([ofp.oxm.vlan_vid((ofp.OFPVID_PRESENT | 2)), ofp.oxm.vlan_pcp(3)]) matching = {'vid=2 pcp=3': simple_tcp_packet(dl_vlan_enable=True, vlan_vid=2, vlan_pcp=3)} nonmatching = {'vid=4 pcp=2': simple_tcp_packet(dl_vlan_enable=True, ...
class GemmRCRFunction(): def __init__(self, inputs_pool): self._it_pool = 0 self._as = [t['a'] for t in inputs_pool] self._bs = [t['b'] for t in inputs_pool] self._inputs_pool_size = len(inputs_pool) self._module = GemmRCRModule() def next_input(self): self._it_po...
class DeleteIndices(): def __init__(self, ilo, master_timeout=30): verify_index_list(ilo) if (not isinstance(master_timeout, int)): raise TypeError(f'Incorrect type for "master_timeout": {type(master_timeout)}. Should be integer value.') self.index_list = ilo self.client ...
.integrationtest .skipif((not has_postgres_configured), reason='PostgresSQL not configured') def test_psycopg2_register_json(instrument, postgres_connection, elasticapm_client): import psycopg2.extras elasticapm_client.begin_transaction('web.django') new_type = psycopg2.extras.register_json(postgres_connect...
def test_apple_roundtrips(use_builtin_types): pl = plistlib.loads(TESTDATA, use_builtin_types=use_builtin_types) data = plistlib.dumps(pl, use_builtin_types=use_builtin_types) pl2 = plistlib.loads(data, use_builtin_types=use_builtin_types) data2 = plistlib.dumps(pl2, use_builtin_types=use_builtin_types)...
def test_yaml_loader_with_expired_cache(tmpdir, mocker, _json_cache, yaml_string, expected_from_loader): mock_resp = mocker.Mock() mock_resp.status_code = 200 mock_resp.text = yaml_string mock_get = mocker.patch('requests.Session.get', return_value=mock_resp) mocker.patch('tempfile.gettempdir', retu...
def extractWwwExenovelsCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('[Teaser]' in item['title']): return None tagmap = [("History's Strongest Manager", "History's St...
def extractSleepysmutWpcomstagingCom(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...
class OptionSeriesWindbarbDataMarkerStates(Options): def hover(self) -> 'OptionSeriesWindbarbDataMarkerStatesHover': return self._config_sub_data('hover', OptionSeriesWindbarbDataMarkerStatesHover) def normal(self) -> 'OptionSeriesWindbarbDataMarkerStatesNormal': return self._config_sub_data('no...
.django_db def test_extent_competed(award_data_fixture, elasticsearch_award_index): elasticsearch_award_index.update_index() should = {'match': {'extent_competed': 'F'}} query = create_query(should) client = elasticsearch_award_index.client response = client.search(index=elasticsearch_award_index.in...
_or_str('.fchk') def geom_from_fchk(text, **geom_kwargs): data = parse_fchk(text) atoms = atoms_from_data(data) try: coords = data['Opt point 1 Geometries'] except KeyError: coords = data['Current cartesian coordinates'] coords = np.array(coords) coords = coords.reshape((- ...
class TestHSLuvSerialize(util.ColorAssertsPyTest): COLORS = [('color(--hsluv 50 30 50 / 0.5)', {}, 'color(--hsluv 50 30 50 / 0.5)'), ('color(--hsluv 50 30 50)', {'alpha': True}, 'color(--hsluv 50 30 50 / 1)'), ('color(--hsluv 50 30 50 / 0.5)', {'alpha': False}, 'color(--hsluv 50 30 50)'), ('color(--hsluv 50 30 none...
class SuperuserRequiredTests(ResolveInfoTestCase): def test_superuser_required(self): self.user.is_superuser = True result = decorators.superuser_required((lambda info: None))(self.info_mock(self.user)) self.assertIsNone(result) def test_permission_denied(self): func = decorators...
class Array(object): def merge_into(self, source, dest, source_end_index, dest_end_index): if ((source is None) or (dest is None)): raise TypeError('source or dest cannot be None') if ((source_end_index < 0) or (dest_end_index < 0)): raise ValueError('end indices must be >= 0...
def test_run_publishers_is_working_properly_with_post_publishers_specified(prepare_publishers): called = [] ('Test', publisher_type=PRE_PUBLISHER_TYPE) def pre_func1(): called.append('pre_func1') ('Test', publisher_type=PRE_PUBLISHER_TYPE) def pre_func2(): called.append('pre_func2') ...
def hashtagtopath(thehashtag): (hashtagcurrent, foldercurrent) = ('', '') notbreaking = True typemainlocal = [] for x in typemain: typemainlocal.append(x) for y in typemainlocal: if (thehashtag[1:] == y): printdebug('one of typemain, found on else') hashtagcur...
def apply_region_configs(env_config): new_config = env_config.copy() for region in env_config.get('regions', consts.REGIONS): if isinstance(env_config.get('regions'), dict): region_specific_config = env_config['regions'][region] new_config[region] = dict(DeepChainMap(region_speci...
class ALSGRPC(ServiceType): skip_variant: ClassVar[bool] = True def __init__(self, *args, **kwargs) -> None: kwargs['service_manifests'] = integration_manifests.load('grpc_als_backend') super().__init__(*args, **kwargs) def requirements(self): (yield ('pod', self.path.k8s))
class OptionSeriesSunburstSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._con...
class ImportBlockComponent(Application): logger = logging.getLogger('trinity.components.BlockImport') def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None: import_parser = subparser.add_parser('import', help='Import blocks from a file (RLP encoded)') import...
def main(): parser = argparse.ArgumentParser(prog='calc_range_srgb.py', description='Calculate RGB range in the given color.') parser.add_argument('--color', '-c', action='store', default='', help='The color whose range relative to RGB will be calculated.') parser.add_argument('--rgb', '-r', action='store',...
def measure_definition(request, measure): measure = get_object_or_404(Measure, pk=measure) context = {'measure': measure, 'measure_details': _get_measure_details(measure.id), 'measure_tags': _get_tags_with_names(measure.tags), 'numerator_sql': _format_measure_sql(columns=measure.numerator_columns, from_=measure...
def test_epoch_start_and_end_blocks_have_same_dataset_size() -> None: for _ in range(100): block_number = Uint(randint((10 ** 9), (2 * (10 ** 9)))) epoch_start_block_number = ((block_number // EPOCH_SIZE) * EPOCH_SIZE) epoch_end_block_number = ((epoch_start_block_number + EPOCH_SIZE) - 1) ...
def _load_config(directory): config = configparser.ConfigParser() files = glob.glob(os.path.join(directory, '*.ini')) logging.debug('Files %s in config directory %s', files, directory) config.read(files) config_dict = {'instances': {}, 'clone_host_map': {}} instances = config_dict['instances'] ...
('ecs_deploy.cli.get_client') def test_update_task_with_role_arn(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.update, (TASK_DEFINITION_ARN_1, '-r', 'arn:new:role')) assert (result.exit_code == 0) assert (not result.exception) asse...
class OptionPlotoptionsStreamgraphSonificationTracksMappingGapbetweennotes(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 TestParseDateMath(CuratorTestCase): def test_assorted_datemaths(self): for (test_string, expected) in [('<prefix-{now}-suffix>', f"prefix-{datetime.utcnow().strftime('%Y.%m.%d')}-suffix"), ('<prefix-{now-1d/d}>', f"prefix-{(datetime.utcnow() - timedelta(days=1)).strftime('%Y.%m.%d')}"), ('<{now+1d/d}>...
def extractDorysoulWordpressCom(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 _limits(): limits_data = API_CLIENT.get_account_limits() if JSON_OUTPUT: _print_json(limits_data) return headers = ['Name', 'Amount', 'Country List'] keys = ['limit', 'amount', 'countryList'] text = _create_table_from_dict(headers=headers, value_functions=keys, data=limits_data, ...
class CommandLineError(TradeException): def __init__(self, errorStr, usage=None): (self.errorStr, self.usage) = (errorStr, usage) def __str__(self): if self.usage: return 'ERROR: {}\n\n{}'.format(self.errorStr, self.usage) else: return 'ERROR: {}'.format(self.erro...
def link(node: RenderTreeNode, context: RenderContext) -> str: if (node.info == 'auto'): autolink_url = node.attrs['href'] assert isinstance(autolink_url, str) if (autolink_url.startswith('mailto:') and (not node.children[0].content.startswith('mailto:'))): autolink_url = autolin...
class ActionCodeSettings(): def __init__(self, url, handle_code_in_app=None, dynamic_link_domain=None, ios_bundle_id=None, android_package_name=None, android_install_app=None, android_minimum_version=None): self.url = url self.handle_code_in_app = handle_code_in_app self.dynamic_link_domain ...
class Moods(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(verbose_name='', max_length=16) ip = models.GenericIPAddressField(verbose_name='ip', default='120.228.2.238') addr = models.TextField(verbose_name='', null=True) create_date = models.DateTimeField(verbose_nam...
def base_h_gen(out, name): common_top_matter(out, name) base_h_content(out) gen_object_enum(out) out.write('\n/\n *\n * Experimenter IDs\n *\n /\n\n') for (name, val) in of_g.experimenter_name_to_id.items(): out.write(('#define OF_EXPERIMENTER_ID_%s 0x%08x\n' % (name.upper(), val))) out....
_ns.route('/pending-actions/') def pending_actions(): busy_namespaces = set() data = [] for action in actions_logic.ActionsLogic.get_waiting(): if ((action.object_type == 'copr') and (action.action_type == ActionTypeEnum('delete'))): busy_namespaces.add(action.copr.full_name) eli...
def extractRoundhousenovelsCom(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) i...
def load(request): session = {} cookie = request.cookies.get('vulpy_session') try: if cookie: decoded = base64.b64decode(cookie.encode()) if decoded: session = json.loads(base64.b64decode(cookie)) except Exception: pass return session
def parse_cookie_header(header_value): cookies = {} for token in header_value.split(';'): (name, __, value) = token.partition('=') name = name.strip() value = value.strip() if (not name): continue if _COOKIE_NAME_RESERVED_CHARS.search(name): contin...
('/join', methods=['POST']) def join(): name = request.form['name'] room_id = request.form['room-id'] session['player-id'] = str(uuid.uuid4()) session['player-name'] = name session['player-money'] = 1000 session['room-id'] = (room_id if room_id else None) return redirect(url_for('index'))
.django_db def test_award_count_invalid_defc_type(client, monkeypatch, basic_award, helpers): helpers.patch_datetime_now(monkeypatch, 2022, 12, 31) resp = helpers.post_for_count_endpoint(client, url, '100') assert (resp.status_code == status.HTTP_400_BAD_REQUEST) assert (resp.data['detail'] == "Invalid ...
def test_transaction_fixtures(fixture, fixture_transaction_class): TransactionClass = fixture_transaction_class try: txn = TransactionClass.decode(fixture['txbytes']) except (rlp.DeserializationError, rlp.exceptions.DecodingError): assert ('hash' not in fixture), 'Transaction was supposed to...
def _register_scene_prompt_template(scene_registry: Dict[(str, Dict)], prompt_template, language: str, model_names: List[str]): for model_name in model_names: if (model_name not in scene_registry): scene_registry[model_name] = dict() registry = scene_registry[model_name] registry...
def gen_data_in_runpath(tmp_path): simulations_dir = (tmp_path / 'simulations') simulations_dir.mkdir() for i in range(3): realization_dir = (simulations_dir / f'realization-{i}') realization_dir.mkdir() (realization_dir / 'iter-0').mkdir() ((realization_dir / 'iter-0') / 'rf...
def extractYaniiitranslationsBlogspotCom(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, ...
class OptionPlotoptionsScatter3dOnpointPosition(Options): def offsetX(self): return self._config_get(None) def offsetX(self, num: float): self._config(num, js_type=False) def offsetY(self): return self._config_get(None) def offsetY(self, num: float): self._config(num, js_...
def dfs(dict): sidebar_items = [] for (key, val) in dict.items(): if (len(modules_and_symbols[key][1]) > 0): items = ([f'"api/{symbol_to_article[key]}"'] + [f'"api/{symbol_to_article[fullname(key, item)]}"' for (item, _) in modules_and_symbols[key][1]]) else: items = [] ...
def get_capacity_data_for_all_zones(target_datetime: datetime, session: Session) -> dict: data = get_data_from_url(target_datetime, session) capacity_dict = {} for item in data: if (pycountry.countries.get(alpha_3=item['key'][0]) is not None): zone = pycountry.countries.get(alpha_3=item[...
def edit_message_caption(token, caption, chat_id=None, message_id=None, inline_message_id=None, parse_mode=None, caption_entities=None, reply_markup=None): method_url = 'editMessageCaption' payload = {'caption': caption} if chat_id: payload['chat_id'] = chat_id if message_id: payload['me...
_init.register_param_type _init_ack.register_param_type _unresolvable_addr.register_param_type _restart_with_new_addr.register_param_type class param_ipv4(param): _TYPE = {'ascii': ['value']} def param_type(cls): return PTYPE_IPV4 def __init__(self, value='127.0.0.1', length=0): super(param_...
class iplookup(Module): config = Config({Option('HOST_IP', 'Provide your target IP', True): str('136.158.41.95')}) def run(self): dataList = [] ip = self.config.option('HOST_IP').value print(("\n Locating '%s'..." % ip)) TABLE_DATA = [] url = ' data = requests.get...
class WandbLogger(base.Logger): def __init__(self, label: Optional[str]=None, steps_key: Optional[str]=None, *, project: Optional[str]=None, entity: Optional[str]=None, dir: Optional[str]=None, name: Optional[str]=None, group: Optional[str]=None, config: Optional[Any]=None, **wandb_kwargs): if (wandb is Non...
def diag_quadrupole3d_22(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 6, 6), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (3.0 * x0) x2 = (x0 * ((ax * A[0]) + (bx * B[0]))) x3 = (- x2) x4 = (x3 + A[0]) x5 = (x3 + B[0]) x6 = (x4 * x5) x7 = (2.0 * x6) x8 = (x3 + R[0]) x9...
def test_dispatch_to_response_pure_notification_parse_error() -> None: assert (dispatch_to_response_pure(deserializer=default_deserializer, validator=default_validator, post_process=identity, context=NOCONTEXT, methods={'ping': ping}, request='{') == Left(ErrorResponse(ERROR_PARSE_ERROR, 'Parse error', 'Expecting p...
def test_percentiles_with_out_of_bounds_fractions(): assert (1 == percentile([1, 2, 3, 4], percentile=10)) assert (1 == percentile([1, 2, 3, 4], percentile=15)) assert (1 == percentile([1, 2, 3, 4], percentile=20)) assert (1 == percentile([1, 2, 3, 4], percentile=25)) assert (1 < percentile([1, 2, 3...
class String(ModelField): def __init__(self, **kwargs): assert ('max_length' in kwargs), 'max_length is required' super().__init__(**kwargs) def get_validator(self, **kwargs) -> typesystem.Field: return typesystem.String(**kwargs) def get_column_type(self): return sqlalchemy....