code
stringlengths
281
23.7M
def extractAnotherWorldTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('Depths of Labyrinth' in item['tags']): return buildReleaseMessageWithType(item, "Ai...
class DataTable(ConstrainedControl): def __init__(self, columns: Optional[List[DataColumn]]=None, rows: Optional[List[DataRow]]=None, ref: Optional[Ref]=None, key: Optional[str]=None, width: OptionalNumber=None, height: OptionalNumber=None, left: OptionalNumber=None, top: OptionalNumber=None, right: OptionalNumber=...
class GenCheckDriver(): def __init__(self, module): self.module = module def reset(self): (yield self.module.reset.eq(1)) (yield) (yield self.module.reset.eq(0)) (yield) def configure(self, base, length, end=None, random_addr=None, random_data=None): if (end i...
class ViewMode(BaseMode): name = Mode.view keymap = {Action.aim: False, Action.call_shot: False, Action.fine_control: False, Action.move: False, Action.stroke: False, Action.quit: False, Action.zoom: False, Action.cam_save: False, Action.cam_load: False, Action.show_help: False, Action.pick_ball: False, Action....
.parametrize('interpol_cls', [Interpolator, LST, IDPP, Redund]) def test_ala_dipeptide_interpol(interpol_cls): initial = geom_loader('lib:dipeptide_init.xyz') final = geom_loader('lib:dipeptide_fin.xyz') geoms = (initial, final) interpolator = interpol_cls(geoms, 28, align=True) geoms = interpolator...
class PubsubSubscription(resource_class_factory('pubsub_subscription', 'name', hash_key=True)): ('iam_policy') def get_iam_policy(self, client=None): try: (data, _) = client.fetch_pubsub_subscription_iam_policy(self['name']) return data except (api_errors.ApiExecutionErro...
class OptionSeriesCylinderSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionSeriesCylinderSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionSeriesCylinderSonificationDefaultinstrumentoptionsMappingFrequency) def gapBe...
class OptionSeriesTilemapStatesSelect(Options): def animation(self) -> 'OptionSeriesTilemapStatesSelectAnimation': return self._config_sub_data('animation', OptionSeriesTilemapStatesSelectAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self....
def _genenv_ignoring_key_case_with_prefixes(env_key: str, env_prefixes: List[str]=None, default_value=None) -> str: if env_prefixes: for env_prefix in env_prefixes: env_var_value = _genenv_ignoring_key_case(env_key, env_prefix) if env_var_value: return env_var_value ...
def vel_u_AFBC(x, flag): if (non_slip_BCs and ((flag == boundaryTags['box_left']) or (flag == boundaryTags['box_right']) or (flag == boundaryTags['box_top']) or (flag == boundaryTags['box_front']) or (flag == boundaryTags['box_back']))): return None elif (openTop and (flag == boundaryTags['top'])): ...
class TimeEdit(QtWidgets.QTimeEdit): def __init__(self, *args, **kwargs): self.resolution = None if ('resolution' in kwargs): self.resolution = kwargs['resolution'] kwargs.pop('resolution') super(TimeEdit, self).__init__(*args, **kwargs) def stepBy(self, step): ...
class OptionSeriesPolygonMarkerStatesHover(Options): def animation(self) -> 'OptionSeriesPolygonMarkerStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesPolygonMarkerStatesHoverAnimation) def enabled(self): return self._config_get(False) def enabled(self, flag: bool...
class TestContrast(util.ColorAsserts, unittest.TestCase): def test_bad_indirect_input(self): with self.assertRaises(TypeError): Color('red').contrast(3) def test_contrast_dict(self): self.assertEqual(Color('white').contrast('blue'), Color('white').contrast({'space': 'srgb', 'coords':...
def create_homestead_header_from_parent(parent_header: BlockHeaderAPI, **header_params: Any) -> BlockHeader: if ('difficulty' not in header_params): header_params.setdefault('timestamp', (parent_header.timestamp + 1)) header_params['difficulty'] = compute_homestead_difficulty(parent_header, header_p...
def get_interpolated_tones(text, tones): print(text) print(tones) print('The length of text and tones: ', len(text), len(tones)) assert (len(text.split()) == len(tones.split())) interpolated_tones = [] chars = [] for (phone, tone) in list(zip(text.split(), tones.split())): interpolat...
class Test_svlan(unittest.TestCase): pcp = 0 cfi = 0 vid = 32 tci = (((pcp << 15) | (cfi << 12)) | vid) ethertype = ether.ETH_TYPE_8021Q buf = pack(svlan._PACK_STR, tci, ethertype) sv = svlan(pcp, cfi, vid, ethertype) def setUp(self): pass def tearDown(self): pass ...
def extractAnykatranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('face slapping the slag gong system', 'face slapping the slag gong system', 'translated')...
def test_generate_probe_features_normal(): sel = ProbeFeatureSelection(estimator=DecisionTreeClassifier(), n_probes=2, distribution='normal', random_state=1) n_obs = 3 probe_features = sel._generate_probe_features(n_obs).round(3) expected_results = {'gaussian_probe_0': [4.873, (- 1.835), (- 1.585)], 'ga...
def test(): import spacy.matcher assert isinstance(matcher, spacy.matcher.Matcher), 'matcher?' assert ('Matcher(nlp.vocab)' in __solution__), 'matcher?' assert (len(pattern) == 2), '2(2)' assert (isinstance(pattern[0], dict) and isinstance(pattern[1], dict)), '' assert ((len(pattern[0]) == 1) an...
_heads([Sum, Product]) def tex_Sum_Product(head, args, **kwargs): if (head == Sum): ss = '\\sum' else: ss = '\\prod' if (len(args) == 0): raise ValueError func = args[0].latex(**kwargs) if (len(args) == 1): return ((ss + ' ') + func) if (args[1].head() == For): ...
class MuxAccountLookCommand(COMMAND_DEFAULT_CLASS): def parse(self): super().parse() playable = self.account.characters if self.args: self.playable = dict(((utils.to_str(char.key.lower()), char) for char in playable)).get(self.args.lower(), None) else: self.pl...
class ExtractSummary(BaseChat): chat_scene: str = ChatScene.ExtractSummary.value() def __init__(self, chat_param: Dict): chat_param['chat_mode'] = ChatScene.ExtractSummary super().__init__(chat_param=chat_param) self.user_input = chat_param['select_param'] async def generate_input_va...
class TestFilmAdvanceLever(object): def test_lever_not_on_camera_cannot_be_pressed(self): l = FilmAdvanceLever() with pytest.raises(FilmAdvanceLever.CannotBeWound): l.wind() def test_lever_advances_mechanism(self): c = Camera() assert (c.exposure_control_system.shutte...
class Sensor(GenericSensor): def setup_module(self) -> None: from smbus2 import SMBus self.bus = SMBus(self.config['i2c_bus_num']) self.address = self.config['chip_addr'] def get_value(self, sens_conf: ConfigType) -> SensorValueType: value: int = (self.bus.read_word_data(self.add...
class FormulaFile(): def __init__(self, formulas, contents, mtime, filename): self.formulas = formulas self.contents = contents self.mtime = mtime self.filename = filename self.file_backed = True def out_of_date(self): return (self.file_backed and (os.stat(self.fi...
def test_angle_limit(setup): print('') print('get joint min angle value:') print(mc.get_joint_min_angle(1)) print(mc.get_joint_min_angle(2)) print(mc.get_joint_min_angle(3)) print(mc.get_joint_min_angle(4)) print(mc.get_joint_min_angle(5)) print(mc.get_joint_min_angle(6)) print('get ...
(scope='function') def privacy_request_with_custom_fields(db: Session, policy: Policy) -> PrivacyRequest: privacy_request = _create_privacy_request_for_policy(db, policy) privacy_request.persist_custom_privacy_request_fields(db=db, custom_privacy_request_fields={'first_name': CustomPrivacyRequestField(label='Fi...
def bm_focal_loss() -> None: if (not torch.cuda.is_available()): print('Skipped: CUDA unavailable') return kwargs_list = [{'N': 100}, {'N': 100, 'alpha': 0}, {'N': 1000}, {'N': 1000, 'alpha': 0}, {'N': 10000}, {'N': 10000, 'alpha': 0}] benchmark(TestFocalLoss.focal_loss_with_init, 'Focal_los...
def extract_source_code_release(identifier): source_code_archive_path = get_source_code_archive_path(identifier) source_code_extract_path = get_source_code_extract_path(identifier) ensure_path_exists(source_code_extract_path) print(f'Extracting archive: {source_code_archive_path} -> {source_code_extract...
def main(): parser = argparse.ArgumentParser(description='LiteEth Etherbone test utility') parser.add_argument('--port', default='1234', help='Host bind port') parser.add_argument('--udp', action='store_true', help='Use CommUDP directly instead of RemoteClient') parser.add_argument('--ident', action='st...
class OptionPlotoptionsPictorialSonificationDefaultspeechoptionsMappingPitch(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('undefined') def mapTo(self, ...
def interleaved_tokenlist(required_item, other_item, sep, allow_trailing=False, at_least_two=False): sep = sep.suppress() if at_least_two: out = (((Group(required_item) + Group(OneOrMore((sep + other_item)))) | (Group((other_item + ZeroOrMore((sep + other_item)))) + Group(OneOrMore((sep + required_item)...
class SimpleLogin(): messages = {'login_success': Message('login success!', 'success'), 'login_failure': Message('invalid credentials', 'danger'), 'is_logged_in': Message('already logged in'), 'logout': Message('Logged out!'), 'login_required': Message('You need to login first', 'warning'), 'access_denied': Message...
class OptionPlotoptionsBulletSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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(s...
class TaskActionManagerBuilder(ActionManagerBuilder): task = Instance(Task) additions = Property(List(SchemaAddition), observe='task.extra_actions') def create_menu_bar_manager(self): if self.task.menu_bar: return self.create_action_manager(self.task.menu_bar) return None def...
class TreeNodeModel(models.Model): treenode_display_field = None tn_ancestors_pks = models.TextField(blank=True, default='', editable=False, verbose_name=_('Ancestors pks')) tn_ancestors_count = models.PositiveIntegerField(default=0, editable=False, verbose_name=_('Ancestors count')) tn_children_pks = m...
('/m3u8/<cid>/<offset>/<star>/<typefilter>/<searchstr>/<name>') def m3u8(cid, offset, star, typefilter='0', searchstr='0', name='0'): stm = '0' qtyps = [] qtyps.append(('', '800000')) qtyps.append(('', '1200000')) qtyps.append(('', '1800000')) qtyps.append(('1080p', '3000000')) qtyps.append(...
def test_hover_pointer_attr(): string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)}) file_path = ((test_dir / 'hover') / 'pointers.f90') string += hover_req(file_path, 1, 26) (errcode, results) = run_request(string, fortls_args=['--sort_keywords']) assert (errcode == 0) ref_re...
class OptionsChartData(Options): def categories(self): return self._config_get() def categories(self, values): self._config(values) def add_series(self, name, data) -> OptionsChartDataSeries: new_series = self._config_sub_data_enum('series', OptionsChartDataSeries) new_series...
.authentication class TestReadToken(): .asyncio async def test_missing_token(self, redis_strategy: RedisStrategy[(UserModel, IDType)], user_manager): authenticated_user = (await redis_strategy.read_token(None, user_manager)) assert (authenticated_user is None) .asyncio async def test_inv...
class _ZebraBfdDestination(_ZebraMessageBody): _HEADER_FMT = '!I' HEADER_SIZE = struct.calcsize(_HEADER_FMT) _FAMILY_FMT = '!H' FAMILY_SIZE = struct.calcsize(_FAMILY_FMT) _BODY_FMT = '!IIBB' BODY_SIZE = struct.calcsize(_BODY_FMT) _FOOTER_FMT = '!B' FOOTER_SIZE = struct.calcsize(_FOOTER_F...
_eh class GrimoireHandler(THBEventHandler): interested = ['action_after', 'action_shootdown'] def handle(self, evt_type, act): if (evt_type == 'action_shootdown'): if (not isinstance(act, LaunchCard)): return act c = act.card if c.is_card(GrimoireSkill...
def test_wrong_zcornsv_size(): split_enz = np.full(8, fill_value=4, dtype=np.uint8).tobytes() zvals = np.ones(300, dtype=np.float32) zcornsv = np.zeros(5, dtype=np.float32) retval = _cxtgeo.grd3d_roff2xtgeo_splitenz(3, 1.0, 1.0, split_enz, zvals, zcornsv) assert (retval == (- 4))
def test_record_none_exc_info(django_elasticapm_client): record = logging.LogRecord('foo', logging.INFO, pathname=None, lineno=None, msg='test', args=(), exc_info=(None, None, None)) handler = LoggingHandler() handler.emit(record) assert (len(django_elasticapm_client.events[ERROR]) == 1) event = dja...
class IBCCoreConnectionRestClient(IBCCoreConnection): API_URL = '/ibc/core/connection/v1beta1' def __init__(self, rest_api: RestClient) -> None: self._rest_api = rest_api def Connection(self, request: QueryConnectionRequest) -> QueryConnectionResponse: json_response = self._rest_api.get(f'{s...
def test_machine_should_use_and_model_attr_other_than_state(campaign_machine): model = MyModel(status='producing') machine = campaign_machine(model, state_field='status') assert (getattr(model, 'state', None) is None) assert (model.status == 'producing') assert (machine.current_state == machine.prod...
def get_special_exec_cond_and_kernel(func_attrs, input_type, output_type, acc_type, output_accessors, reduction_op, reduction_identity) -> (str, str): exec_conds = [] for (vector_type, vec_bytesize) in vector_types[input_type]: vlen = int((vec_bytesize / bytesize[input_type])) exec_cond = EXEC_C...
def train(trn_data: List[List[Tuple[(str, str)]]], dev_data: List[List[Tuple[(str, str)]]]) -> Tuple: cw_dict = create_cw_dict(trn_data) pp_dict = create_pp_dict(trn_data) pw_dict = create_pw_dict(trn_data) nw_dict = create_nw_dict(trn_data) (best_acc, best_args) = ((- 1), None) grid = [0.1, 0.5...
class SQLAlchemyDefaultImages(DefaultImages): _DEFAULT_IMAGE_PREFIXES = {PythonVersion.PYTHON_3_8: 'cr.flyte.org/flyteorg/flytekit:py3.8-sqlalchemy-', PythonVersion.PYTHON_3_9: 'cr.flyte.org/flyteorg/flytekit:py3.9-sqlalchemy-', PythonVersion.PYTHON_3_10: 'cr.flyte.org/flyteorg/flytekit:py3.10-sqlalchemy-', PythonV...
class TestLoggingCoprPermissionsLogic(CoprsTestCase): ('coprs.app.logger', return_value=MagicMock()) .usefixtures('f_users', 'f_coprs', 'f_copr_permissions', 'f_db') def test_update_permissions(self, log): perm = models.CoprPermission(copr=self.c2, user=self.u3, copr_builder=helpers.PermissionEnum('...
('/') def index(): tmp = u'\n<p><a href="/admin/?lang=en">Click me to get to Admin! (English)</a></p>\n<p><a href="/admin/?lang=cs">Click me to get to Admin! (Czech)</a></p>\n<p><a href="/admin/?lang=de">Click me to get to Admin! (German)</a></p>\n<p><a href="/admin/?lang=es">Click me to get to Admin! (Spanish)</a>...
class TestPluginRoutes(): def setup_method(self): self.app = Flask(__name__) self.app.config.from_object(__name__) self.api = Api(self.app) def test_get_modules_in_path(self): plugin_dir_path = os.path.join(get_src_dir(), 'plugins') plugin_folder_modules = _get_modules_in...
class NumberVersion(ModelSimple): allowed_values = {} validations = {('value',): {'inclusive_minimum': 1}} additional_properties_type = None _nullable = False _property def openapi_types(): return {'value': (int,)} _property def discriminator(): return None attribute_...
def on_call_check_tokens(request: _Request) -> _OnCallTokenVerification: verifications = _OnCallTokenVerification() auth_token = _on_call_check_auth_token(request) if (auth_token is None): verifications.auth = OnCallTokenState.MISSING elif isinstance(auth_token, dict): verifications.auth...
class Server(object): settings_class = ServerSettings request_class = EnrichedActionRequest client_class = Client use_django = False service_name = None action_class_map = {} introspection_action = None def __init__(self, settings, forked_process_id=None): if (not self.service_na...
.compilertest def test_irauth_grpcservice_version_default(): if EDGE_STACK: pytest.xfail('XFailing for now, custom AuthServices not supported in Edge Stack') yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: AuthService\nmetadata:\n name: mycoolauthservice\n namespace: default\nspec:\n aut...
class CatalogItemAppealStatus(AbstractObject): def __init__(self, api=None): super(CatalogItemAppealStatus, self).__init__() self._isCatalogItemAppealStatus = True self._api = api class Field(AbstractObject.Field): handle = 'handle' item_id = 'item_id' status = 's...
def process_data(data, tokens): for house in data: house_data = extract_house_data(house) if (house_data is None): continue if (house_data['token'] in tokens): continue tokens.append(house_data['token']) send_telegram_message(house_data) time.s...
class Ticket(BaseObject): def __init__(self, api=None, assignee_id=None, brand_id=None, collaborator_ids=None, created_at=None, custom_fields=None, description=None, due_at=None, external_id=None, fields=None, forum_topic_id=None, group_id=None, has_incidents=None, id=None, organization_id=None, priority=None, prob...
class SlackNotification(): def __init__(self, app=None, env=None, prop_path=None): timestamp = time.strftime('%B %d, %Y %H:%M:%S %Z', time.gmtime()) self.settings = get_properties(prop_path) short_commit_sha = self.settings['pipeline']['config_commit'][0:11] self.info = {'app': app, ...
def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), ((errorIndex and varBindTable[0][(int(errorIndex) - 1)][0]) or '?')))) else: for varBindRow in varBindTable: for va...
class OptionSeriesHeatmapSonificationDefaultinstrumentoptionsActivewhen(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, nu...
def _sign_in_with_password(email, password, api_key): body = {'email': email, 'password': password, 'returnSecureToken': True} params = {'key': api_key} resp = requests.request('post', _verify_password_url, params=params, json=body) resp.raise_for_status() return resp.json().get('idToken')
def test_map_value_judged_only(): current = pd.DataFrame(data=dict(user_id=['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], prediction=[1, 2, 3, 1, 2, 3, 1, 2, 3], target=[1, 0, 0, 0, 0, 0, 0, 0, 1])) metric = MAPKMetric(k=3, no_feedback_users=True) report = Report(metrics=[metric]) column_mapping = Colum...
(NOTICES_SERVED, status_code=HTTP_200_OK, response_model=List[LastServedConsentSchema]) _limiter.limit(CONFIG.security.public_request_rate_limit) def save_consent_served_to_user(*, db: Session=Depends(get_db), data: RecordConsentServedRequest, request: Request, response: Response) -> List[LastServedNotice]: verify_...
class APILogin(): def __init__(self): self.api_logger = zapscan.logger() self.parse_data = parsers.PostmanParser() def fetch_logintoken(self, url, method, headers, body=None, relogin=None): if (method.upper() == 'GET'): login_request = requests.get(url, headers=headers) ...
class IDispatch(IUnknown): if TYPE_CHECKING: _disp_methods_ = hints.AnnoField() _GetTypeInfo = hints.AnnoField() __com_GetIDsOfNames = hints.AnnoField() __com_Invoke = hints.AnnoField() _iid_ = GUID('{-0000-0000-C000-}') _methods_ = [COMMETHOD([], HRESULT, 'GetTypeInfoCount',...
class TestSuperFencesClassesIdsAttrListNoPygmentsOnPre(util.MdCase): extension = ['pymdownx.highlight', 'pymdownx.superfences', 'markdown.extensions.attr_list'] extension_configs = {'pymdownx.highlight': {'use_pygments': False, 'code_attr_on_pre': True}} def test_classes(self): self.check_markdown('...
class OptionPlotoptionsSolidgaugeOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._confi...
def test_extruded_periodic_1_layer(): mesh = UnitIntervalMesh(1) extm = ExtrudedMesh(mesh, layers=1, extrusion_type='uniform', periodic=True) elem = TensorProductElement(FiniteElement('DG', mesh.ufl_cell(), 0), FiniteElement('CG', 'interval', 1)) V = FunctionSpace(extm, elem) v = TestFunction(V) ...
def test_integration_output_psv(capsys): CISAudit().output(data=data, format='psv') (output, error) = capsys.readouterr() assert (error == '') assert (output.split('\n')[0] == 'ID|Description|Level|Result|Duration') assert (output.split('\n')[1] == '1|"section header"|||') assert (output.split('...
class ServiceIdAndVersionString(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 {'service_id': (str,), ...
def syncpwm(bcmpin, value): for x in range(0, len(Settings.Tasks)): if (Settings.Tasks[x] and (type(Settings.Tasks[x]) is not bool)): if Settings.Tasks[x].enabled: if ((Settings.Tasks[x].pluginid == 213) and (Settings.Tasks[x].taskdevicepin[0] == bcmpin)): try...
class OptionSeriesVectorSonificationDefaultspeechoptionsMappingPlaydelay(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 fine(node): if isinstance(node, IntConst): return 'INT({})({})'.format(node.width, node.value) elif isinstance(node, StringConst): return 'STR' elif isinstance(node, SwitchTable): return 'SWITCH' elif isinstance(node, Flag): return '{}:{}'.format(node.base_flag, node....
class TestDialogueBase(): def setup(cls): cls.incomplete_reference = (str(1), '') cls.complete_reference = (str(1), str(1)) cls.opponent_address = 'agent 2' cls.agent_address = 'agent 1' cls.dialogue_label = DialogueLabel(dialogue_reference=cls.incomplete_reference, dialogue_...
class _XorMatcher(_AlreadyChainedMatcher): def __init__(self, a: Matcher, b: Matcher) -> None: self.a = a self.b = b def __eq__(self, other: AnyType) -> bool: return (((self.a == other) or (self.b != other)) and ((self.a != other) or (self.b == other))) def __repr__(self) -> str: ...
class OptionSeriesXrangeSonificationTracksMappingFrequency(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....
class QRDialog(WindowModalDialog): def __init__(self, data, parent=None, title='', show_text=False): WindowModalDialog.__init__(self, parent, title) vbox = QVBoxLayout() qrw = QRCodeWidget(data) qscreen = QApplication.primaryScreen() vbox.addWidget(qrw, 1) if show_tex...
def pytest_generate_tests(metafunc): if ('language_pack' in metafunc.fixturenames): if ('language_string' in metafunc.fixturenames): language_packs = get_language_packs() metafunc.parametrize(['language_pack', 'language_string'], [(lp, ls) for lp in language_packs for ls in get_langu...
def build_index(force_rebuild=False, execute_after_end=None): config = mw.addonManager.getConfig(__name__) md_files = [] if ((config['md.folder_path'] is not None) and (len(config['md.folder_path']) > 0) and os.path.exists(config['md.folder_path'])): stamp = '' if config['md.last_index_stamp...
class WebUIRequests(_RequestsInterface): def new_project(self, name, chroots, **kwargs): data = {'name': name, 'chroots': chroots} for config in ['bootstrap', 'isolation', 'contact', 'homepage', 'appstream', 'follow_fedora_branching']: if (not (config in kwargs)): continu...
def simulate(shot: System, engine: Optional[PhysicsEngine]=None, inplace: bool=False, continuous: bool=False, dt: Optional[float]=None, t_final: Optional[float]=None, quartic_solver: QuarticSolver=QuarticSolver.HYBRID, include: Set[EventType]=INCLUDED_EVENTS) -> System: if (not inplace): shot = shot.copy() ...
def test_gzip_streaming_response(test_client_factory): def homepage(request): async def generator(bytes, count): for index in range(count): (yield bytes) streaming = generator(bytes=(b'x' * 400), count=10) return StreamingResponse(streaming, status_code=200) a...
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptions(Options): def activeWhen(self) -> 'OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsActivewhen) def inst...
class WheelKeys(): SCHEMA = 1 CONFIG_NAME = 'wheel.json' def __init__(self): self.data = {'signers': [], 'verifiers': []} def load(self): for path in load_config_paths('wheel'): conf = os.path.join(native(path), self.CONFIG_NAME) if os.path.exists(conf): ...
def all_blogs(request): public_blogs = Blog.objects.filter(public=True) if request.user.is_authenticated: user_blogs = Blog.objects.filter(owner=request.user) else: user_blogs = [] context = {'public_blogs': public_blogs, 'user_blogs': user_blogs} return render(request, 'blogs/all_bl...
def create_click_web_app(module, command: click.BaseCommand, root='/'): global _flask_app, logger assert (_flask_app is None), 'Flask App already created.' _register(module, command) _flask_app = Flask(__name__, static_url_path=(root.rstrip('/') + '/static')) _flask_app.config['APPLICATION_ROOT'] = ...
def test_value_mean_error_test_render_json() -> None: test_dataset = pd.DataFrame({'category_feature': ['n', 'd', 'p', 'n'], 'numerical_feature': [0, 1, 2, 5], 'target': [0, 0, 0, 1], 'prediction': [0, 1, 0, 0]}) suite = TestSuite(tests=[TestValueMeanError()]) suite.run(current_data=test_dataset, reference_...
class CliParser(argparse.ArgumentParser): def set_default_subparser(self, name, args=None): subparser_found = False for arg in sys.argv[1:]: if (arg in ['-h', '--help']): break else: for x in self._subparsers._actions: if (not isinstanc...
def format_quote(username, content): profile_url = url_for('user.profile', username=username) content = '\n> '.join(content.strip().split('\n')) quote = u'**[{username}]({profile_url}) wrote:**\n> {content}\n'.format(username=username, profile_url=profile_url, content=content) return quote
def main(argv): import getopt def usage(): error(f'Usage: {argv[0]} [-d] [-l logfile] [-s sshdir] [-L addr] [-p port] [-c cmdexe] [-u username] [-a authkeys] [-h homedir] ssh_host_key ...') return 100 try: (opts, args) = getopt.getopt(argv[1:], 'dl:s:L:p:u:a:h:c:') except getopt....
class LMTPMultiProcessingClient(): def __init__(self, model_identifier, **kwargs): ensure_picklable(kwargs, 'lmtp.inprocess kwargs must be pickleable as it has to be sent to a subprocess') self.model_identifier = model_identifier if (multiprocessing.current_process().name != 'MainProcess'): ...
class Node(): def __init__(self, id_: int, data: Dict, type_: NodeType) -> None: self.parent: Optional[Node] = None self.data: Dict = data self.children: Dict[(int, Node)] = {} self.id = id_ self.type = type_ def __repr__(self) -> str: parent = ('no ' if (self.par...
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.') def test_schema_in_dataclass(): import pandas as pd schema = TestSchema() df = pd.DataFrame(data={'some_str': ['a', 'b', 'c']}) schema.open().write(df) o = Result(result=InnerResult(number=1, schema=schema), schema=schema) ...
def common_config(request, docker_mount_base_dir) -> config.Common: overwrite_config = merge_markers(request, 'common_config_overwrite', dict) if ('docker_mount_base_dir' in overwrite_config): raise ValueError('docker-mount-base-dir may not be changed with `.common_config_overwrite`') config.load() ...
def gridproperties_dataframe(gridproperties: Iterable[GridProperties], grid: (Grid | None)=None, activeonly: bool=True, ijk: bool=False, xyz: bool=False, doubleformat: bool=False) -> pd.DataFrame: proplist = list(gridproperties) dataframe_dict = {} if ijk: if activeonly: if grid: ...
class CmdUnconnectedCreate(MuxCommand): key = 'create' aliases = ['cre', 'cr'] locks = 'cmd:all()' def parse(self): super().parse() self.accountinfo = [] if (len(self.arglist) < 3): return if (len(self.arglist) > 3): password = self.arglist.pop() ...
def test_transformer_pipeline_tagger_internal(): orig_config = Config().from_str(cfg_string) nlp = util.load_model_from_config(orig_config, auto_fill=True, validate=True) assert (nlp.pipe_names == ['tagger']) tagger = nlp.get_pipe('tagger') tagger_trf = tagger.model.get_ref('tok2vec').layers[0] ...
class LightPeerChain(PeerSubscriber, Service, BaseLightPeerChain): reply_timeout = REPLY_TIMEOUT headerdb: BaseAsyncHeaderDB = None _pending_replies: 'weakref.WeakValueDictionary[int, asyncio.Future[CommandAPI[Any]]]' def __init__(self, headerdb: BaseAsyncHeaderDB, peer_pool: LESPeerPool) -> None: ...