code
stringlengths
281
23.7M
def __get_validated_git_repos__(repos_relative): if (not repos_relative): repos_relative = '.' repos = [] for repo in repos_relative: cloned_repo = clone.create(repo) if (cloned_repo.name == None): cloned_repo.location = basedir.get_basedir_git(cloned_repo.location) ...
class Compose(Base): __exclude_columns__ = 'updates' __include_extras__ = ('content_type', 'security', 'update_summary') __tablename__ = 'composes' release_id = Column(Integer, ForeignKey('releases.id'), primary_key=True, nullable=False) request = Column(UpdateRequest.db_type(), primary_key=True, nu...
class _MagiclinkShorthandPattern(InlineProcessor): def __init__(self, pattern, md, user, repo, provider, labels): self.user = user self.repo = repo self.labels = labels self.provider = (provider if (provider in PROVIDER_INFO) else '') InlineProcessor.__init__(self, pattern, m...
def import_practices(bq_conn, sqlite_conn, dates): date_start = min(dates) date_end = max(dates) logger.info('Querying for active practice codes between %s and %s', date_start, date_end) sql = "\n SELECT DISTINCT practice FROM {hscic}.prescribing_v2\n WHERE month BETWEEN TIMESTAMP('%(sta...
.parametrize('lang', Mnemonic.list_languages()) .parametrize('num_words', [12, 15, 18, 21, 24]) def test_generation(lang, num_words): m = Mnemonic(lang) mnemonic = m.generate(num_words) assert m.is_mnemonic_valid(mnemonic) if (lang == 'chinese_traditional'): assert ('chinese' in Mnemonic.detect_...
def gen_profiler(func_attrs: Dict[(str, Any)], workdir: str, header_files: str, backend_spec) -> None: op_type = func_attrs['op'] file_pairs = [] blockSize = 1024 t_size = int((((func_attrs['preNmsTop'] + blockSize) - 1) / blockSize)) if (backend_spec.backend_name == 'cuda'): cuda_hmaxmin = ...
def extractNiiselin(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=pos...
def test_get_remote_addr_with_socket(): transport = MockTransport({'socket': MockSocket(family=socket.AF_IPX)}) assert (get_remote_addr(transport) is None) transport = MockTransport({'socket': MockSocket(family=socket.AF_INET6, peername=('::1', 123))}) assert (get_remote_addr(transport) == ('::1', 123))...
def callTransaction21(): c = {} c['code'] = 21 c['in'] = [] c['in'].append({'callingPkg': 'readString16'}) c['in'].append({'featureId': 'readString16'}) c['in'].append({'authority': 'readString16'}) c['in'].append({'method': 'readString16'}) c['in'].append({'stringArg': 'readString16'}) ...
def test_safer(): t = PhyloTree('(a,(b,c));', sp_naming_function=(lambda name: name)) tp_unsafe = tm.TreePattern('("node.get_species()=={\'c\'}", node.species=="b")') assert (list(tp_unsafe.search(t)) == [t.common_ancestor(['b', 'c'])]) tp_safer = tm.TreePattern('("node.get_species()=={\'c\'}", node.s...
class TestGetFieldNames(TestData): def test_get_field_names_all(self): ed_flights = self.ed_flights() pd_flights = self.pd_flights() fields1 = ed_flights._query_compiler.get_field_names(include_scripted_fields=False) fields2 = ed_flights._query_compiler.get_field_names(include_script...
class TestDump(unittest.TestCase): def test_csv(self): filename = 'dump.csv' CSVDump(dump).write(filename) os.remove(filename) def test_py(self): filename = 'dump.py' PythonDump(dump).write(filename) os.remove(filename) def test_sigrok(self): filename ...
class OptionPlotoptionsArearangeOnpointConnectoroptions(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._config...
class ReadonlyEditor(BaseReadonlyEditor): def init(self, parent): super().init(parent) if (self.factory.view is not None): control = self.control control.Bind(wx.EVT_ENTER_WINDOW, self._enter_window) control.Bind(wx.EVT_LEAVE_WINDOW, self._leave_window) ...
class OptionPlotoptionsVariwideSonificationTracksMappingRate(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): sel...
def extractFirebirdFictionCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (('Haventon Chronicles' in item['tags']) and ('Lord of the Wolves' in item['title'])): vol = 2 ...
def test_multiprocessing(simple_nlp, texts): ops = get_current_ops() if isinstance(ops, NumpyOps): texts = (texts * 3) expecteds = [simple_nlp(text) for text in texts] docs = simple_nlp.pipe(texts, n_process=2, batch_size=2) for (doc, expected_doc) in zip(docs, expecteds): ...
def main(): api_key = os.environ.get('OPENAI_API_KEY') api_key_input = gr.components.Textbox(lines=1, label='Enter OpenAI API Key', value=api_key, type='password') model_selection = gr.components.Dropdown(choices=['gpt-4', 'gpt-3.5-turbo'], label='Select a GPT Model', value='gpt-3.5-turbo') user_input =...
class Test_Store(): def store(self, *, app): return Store(url='memory://', app=app, table=Mock(name='table')) def test_clear(self, *, store): store.data['foo'] = 1 store._clear() assert (not store.data) def test_apply_changelog_batch(self, *, store): (event, to_key, t...
def lazy_import(): from fastly.model.realtime_entry_aggregated import RealtimeEntryAggregated from fastly.model.realtime_entry_datacenter import RealtimeEntryDatacenter from fastly.model.realtime_entry_recorded import RealtimeEntryRecorded globals()['RealtimeEntryAggregated'] = RealtimeEntryAggregated ...
def test_density_based_discret_with_delta(bottom, top, quadratic_density): (w, e, s, n) = ((- 3), 2, (- 4), 5) tesseroid = (w, e, s, n, bottom, top) deltas = [0.001, 0.01, 0.1, 1.0] splits = [] for delta in deltas: harmonica._forward._tesseroid_variable_density.DELTA_RATIO = delta sp...
class TestGeneratorsAsciiFields(unittest.TestCase): def setUp(self): self.foo_fieldset = self.dummy_fieldset() self.event_dummy_nested_fields = self.dummy_nested_event_fieldset() def dummy_fieldset(self): return {'description': 'foo', 'fields': {'foo.type': {'dashed_name': 'foo-type', 'd...
def extractEnXiao(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None titlemap = [('Who Dares Slander My Senior Brother ', 'Who Dares Slander My Senior Brother', 'translated'), ('Who Dares Sl...
def test_disabled02_check_disabled_effect(dash_duo, testfile10Mb_csv, testfileWrongType, js_drag_and_drop): app = import_app('tests.apps.disabled') dash_duo.start_server(app) driver = dash_duo._driver wait = WebDriverWait(driver, 10) upload = dash_duo.find_element('#dash-uploader') configs = das...
class Test(unittest.TestCase): def setUp(self): hig.timeout = 0 def testCreate(self): d = hig.Alert(transient_for=toplevel, type=Gtk.MessageType.INFO, primary='Hello!') self.assertNotEqual(d, None) self.runAndDismiss(d) d = hig.Alert(transient_for=toplevel, type=Gtk.Messa...
def test_minimal_renaming_function_arguments_same_color(variable_v, variable_u): instructions = [Assignment(variable_v[1], BinaryOperation(OperationType.plus, [variable_v[0], variable_u[0]])), Assignment(ListOperation([]), Call(imp_function_symbol('printf'), [variable_v[1]]))] node = BasicBlock(0, instructions)...
.usefixtures('copy_poly_case') def test_that_the_ui_show_no_errors_and_enables_update_for_poly_example(qapp): args = Mock() args.config = 'poly.ert' with add_gui_log_handler() as log_handler: (gui, *_) = ert.gui.main._start_initial_gui_window(args, log_handler) combo_box = get_child(gui, QCo...
def test_xor(): x = Fxp(None, True, 8, 4) xu = Fxp(None, False, 8, 4) y = Fxp(None, True, 8, 4) yu = Fxp(None, False, 8, 4) val_str = '' mks_str = '' xor_str = '' x(('0b' + val_str)) xu(('0b' + val_str)) y(('0b' + mks_str)) yu(('0b' + mks_str)) assert ((x ^ y).bin() == xo...
class OptionPlotoptionsAreasplineSonificationContexttracksMapping(Options): def frequency(self) -> 'OptionPlotoptionsAreasplineSonificationContexttracksMappingFrequency': return self._config_sub_data('frequency', OptionPlotoptionsAreasplineSonificationContexttracksMappingFrequency) def gapBetweenNotes(s...
class CirnoDropCards(GenericAction): def __init__(self, source, target, cards): self.source = source self.target = target self.cards = cards def apply_action(self): (src, tgt) = (self.source, self.target) cards = self.cards g = self.game g.players.reveal(c...
class OptionSeriesAreasplineSonificationContexttracksMappingVolume(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 main(): parser = argparse.ArgumentParser(usage='%(prog)s [options] [APPID[:VERCODE] [APPID[:VERCODE] ...]]') common.setup_global_opts(parser) parser.add_argument('appid', nargs='*', help=_('applicationId with optional versionCode in the form APPID[:VERCODE]')) metadata.add_metadata_arguments(parser)...
class TestIN(unittest.TestCase): def test_get_start_of_day(self): start_day = get_start_of_day(arrow.get('2020-12-16 18:30:00+00:00').datetime) assert (start_day == arrow.get('2020-12-17 00:00:00+05:30').datetime) start_day = get_start_of_day(arrow.get('2020-12-16 18:29:00+00:00').datetime) ...
def apply_unifier(x, subst): if (subst is None): return None elif (len(subst) == 0): return x elif isinstance(x, Const): return x elif isinstance(x, Var): if (x.name in subst): return apply_unifier(subst[x.name], subst) else: return x e...
class op(bpy.types.Operator): bl_idname = 'uv.textools_unwrap_edge_peel' bl_label = 'Edge Peel' bl_description = 'Unwrap as a pipe along the edges selected in 3D Space' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): if (not bpy.context.active_object): return False ...
def extractWwwDaisytannenbaumCom(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 handle_bad_request(view_function): (view_function) def wrapper(request, *args, **kwargs): try: return view_function(request, *args, **kwargs) except BadRequestError as e: context = {'error_code': 400, 'reason': str(e)} return render(request, '500.html', co...
class OptionSeriesSunburstSonificationContexttracksMappingTremoloSpeed(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 _parse_from_to_timestamps(param_from: (datetime or None), param_to: (datetime or None)) -> Tuple[(int, int)]: from_timestamp = None to_timestamp = None if (param_from is not None): from_timestamp = int((param_from.timestamp() * 1000)) if (param_to is None): param_to = datetim...
def patch_function(func, *additional_modules): if (not additional_modules): additional_modules = ((((_green_os_modules() + _green_select_modules()) + _green_socket_modules()) + _green_thread_modules()) + _green_time_modules()) def patched(*args, **kw): saver = SysModulesSaver() for (name...
class OptionSeriesScatterSonificationTracksMappingFrequency(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 OptionPlotoptionsSeriesSonificationTracksMappingRate(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....
def run_task(task, year, month, **kwargs): if TaskLog.objects.filter(year=year, month=month, task_name=task.name, status=TaskLog.SUCCESSFUL).exists(): return task_log = TaskLog.objects.create(year=year, month=month, task_name=task.name) try: task.run(year, month, **kwargs) task_log.m...
class HeartRateMeasurementChrc(Characteristic): HR_MSRMT_UUID = '00002a37-0000-1000-8000-00805f9b34fb' def __init__(self, bus, index, service): Characteristic.__init__(self, bus, index, self.HR_MSRMT_UUID, ['notify'], service) self.notifying = False self.hr_ee_count = 0 def hr_msrmt_...
class Attachment(): def __init__(self, filename, content_type, content, disposition='attachment'): self.filename = filename self.content_type = content_type self.content = content self.disposition = disposition def payload(self): return {'Filename': self.filename, 'Conten...
class OptionSeriesOrganizationSonificationTracksMappingPan(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 DWARFReader(object): def __init__(self, filename): self._elffile = ELFFile(filename) self._dwarf = self._elffile.get_dwarf_info() self._build_offset_lut() def _build_offset_lut(self): self.offset_lut = {} self.function_lut = {} self.typedef_lut = {} ...
class CustomLogicCondition(ConditionInterface, Generic[LOGICCLASS]): def __init__(self, condition: WorldObject, tmp: bool=False): if isinstance(condition, Variable): self._variable = condition else: self._variable: BaseVariable = condition.world.new_variable(condition.size, t...
class TestDistanceSpecificCases(util.ColorAsserts, unittest.TestCase): def test_delta_e_alternate_calls(self): self.assertCompare(Color('red').delta_e('blue', method='2000'), Color('red').delta_e('blue', method='2000')) def test_delta_e_alternate_calls_with_params(self): self.assertCompare(Color...
def antivirus_quarantine(data, fos): vdom = data['vdom'] antivirus_quarantine_data = data['antivirus_quarantine'] antivirus_quarantine_data = flatten_multilists_attributes(antivirus_quarantine_data) filtered_data = underscore_to_hyphen(filter_antivirus_quarantine_data(antivirus_quarantine_data)) ret...
def rldecode(data): decoded = b'' i = 0 while (i < len(data)): length = data[i] if (length == 128): break if ((length >= 0) and (length < 128)): run = data[(i + 1):((i + 1) + (length + 1))] decoded += run i = ((i + 1) + (length + 1)) ...
def process_youtube(args): print('') print(f'# Process Youtube, dedup: {args.dedup}') print('') op = OperatorYoutube() data = op.readFromJson(args.data_folder, args.run_id, 'youtube.json') data_deduped = data need_dedup = utils.str2bool(args.dedup) if need_dedup: data_deduped = o...
def test_dpa_initialize_raises_exception_f_max_data_value_is_not_in_0_1(): d = scared.DPADistinguisher() data = np.random.randint(0, 255, (500, 16), dtype='uint8') traces = np.random.randint(0, 255, (500, 16), dtype='uint8') with pytest.raises(ValueError): d._initialize(traces, data)
class MockChrootsLogic(object): def get(cls, os_release, os_version, arch, active_only=False, noarch=False): if (noarch and (not arch)): query = models.MockChroot.query.filter((models.MockChroot.os_release == os_release), (models.MockChroot.os_version == os_version)) else: qu...
def USER_MESSAGE(goal, current_dir): return f'''(USER: {USERNAME}) (DIRECTORY: {current_dir}) Write {OPERATING_SYSTEM} python {PYTHON_VERSION} code so I can achieve my goal by running my code. Do not explain anything. Return only the code. My goal: [{goal}]. Don't forget to print the final result. '''
class IsUserTask(DcBasePermission): def has_permission(self, request, view, args, kwargs): task_id = kwargs.get('task_id', None) if ((not task_id) or (not is_valid_task_id(task_id))): return False (user_id, owner_id, dc_id) = user_owner_dc_ids_from_task_id(task_id) reques...
def extractButterflyscurseStream(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('QTF Record', 'Quick Transmigration Cannon Fodders Record of Counterattacks', 'translated'), ('L...
class CargoBuilder(BuilderBase): def __init__(self, build_opts: 'BuildOptions', ctx, manifest, src_dir, build_dir, inst_dir, build_doc, workspace_dir, manifests_to_build, loader, cargo_config_file) -> None: super(CargoBuilder, self).__init__(build_opts, ctx, manifest, src_dir, build_dir, inst_dir) s...
class TestTachoMotorStopActionValue(ptc.ParameterizedTestCase): def test_stop_action_illegal(self): with self.assertRaises(IOError): self._param['motor'].stop_action = 'ThisShouldNotWork' def test_stop_action_coast(self): if ('coast' in self._param['stop_actions']): self....
def test_register_serialization(): msg = TacMessage(performative=TacMessage.Performative.REGISTER, agent_name='some_agent_name') msg.to = 'receiver' envelope = Envelope(to=msg.to, sender='sender', message=msg) envelope_bytes = envelope.encode() actual_envelope = Envelope.decode(envelope_bytes) e...
def _preprocess(x): x['rnd_invcap'] = (x['rnd'] / x['invcap']) x['capex_invcap'] = (x['capex'] / x['invcap']) x['ebit_invcap'] = (x['ebit'] / x['invcap']) x['ev_ebitda'] = (x['ev'] / x['ebitda']) x['ev_ebit'] = (x['ev'] / x['ebit']) x['debt_equity'] = (x['debt'] / x['equity']) x['grossmargin...
class OptCheck(Options): def icon_check(self): return self._config_get('fas fa-check') _check.setter def icon_check(self, icon: str): self._config(icon) def icon_not_check(self): return self._config_get('fas fa-times') _not_check.setter def icon_not_check(self, icon: str)...
class AsyncioBrokenComponent(AsyncioComponentForTest): name = 'component-test-asyncio-broken' endpoint_name = 'component-test-asyncio-broken' async def _loop_monitoring_task(self, event_bus: EndpointAPI) -> None: (await asyncio.Future()) async def do_run(self, event_bus: EndpointAPI) -> None: ...
class OptionPlotoptionsTimelineStatesSelectMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): sel...
_app.on('disconnect') def test_disconnect(): global client_connected client_connected = False push_object.trigger_action(push2_python.constants.ACTION_MIDI_DISCONNECTED) push_object.trigger_action(push2_python.constants.ACTION_DISPLAY_DISCONNECTED) logging.info('Simulator client disconnected')
class OptionPlotoptionsPieSonificationTracksMappingHighpassResonance(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_dependency_resolution_8(): a0 = Thing('a0.js', []) a1 = Thing('a1.js', ['b1.js', 'b2.js']) b1 = Thing('b1.js', ['c1.js']) b2 = Thing('b2.js', ['d1.js']) c1 = Thing('c1.js', ['d1.js']) d1 = Thing('d1.js', []) aa = (a0, a1, b1, b2, c1, d1) aa = solve_dependencies(aa) assert ([...
def _create(data: CollectionIn, user: UserType): with transaction.atomic(): if (data.item.etag is not None): raise ValidationError('bad_etag', 'etag is not null') instance = models.Collection(uid=data.item.uid, owner=user) try: instance.validate_unique() excep...
def test_explicit_stack(logger): logger.info('This is a test of stacks', extra={'stack': iter_stack_frames()}) assert (len(logger.client.events) == 1) event = logger.client.events[ERROR][0] assert ('culprit' in event), event assert (event['culprit'] == 'tests.handlers.logging.logging_tests.test_expl...
def test_raises_warning_if_no_feature_selected(load_diabetes_dataset): (X, y) = load_diabetes_dataset sel = SelectBySingleFeaturePerformance(estimator=DecisionTreeRegressor(random_state=0), scoring='neg_mean_squared_error', cv=2, threshold=10) with pytest.warns(UserWarning): warnings.warn(sel.fit(X,...
def serialize_basemodel_to_literal(basemodel: pydantic.BaseModel, flyteobject_store: BaseModelFlyteObjectStore) -> literals.Literal: def encoder(obj: Any) -> Union[(str, commons.LiteralObjID)]: if isinstance(obj, commons.PYDANTIC_SUPPORTED_FLYTE_TYPES): return flyteobject_store.register_python_o...
class Wrapper(): def __init__(self, estimator, classifier='inline', dtype='float'): self.dtype = dtype precision = estimator.get_precision() self._means = estimator.location_.copy() self._precision = precision self._offset = estimator.offset_ if (classifier == 'inline...
class TestRuleExecutor(UnitTestWithNamespace): def _build_workflow_execution(self): with Workflow(name='workflow', namespace=self.namespace_name) as workflow: op_1 = Operator(name='op_1') op_2 = Operator(name='op_2') op_3 = Operator(name='op_3') op_4 = Operato...
def cifti_info(filename): c_info = get_stdout(['wb_command', '-file-information', filename, '-no-map-info']) cinfo = {} for line in c_info.split(os.linesep): if ('Structure' in line): cinfo['has_LSurf'] = (True if ('CortexLeft' in line) else False) cinfo['has_RSurf'] = (True ...
def prepare_issfile_for_uninstall(filepath, reboot=False): iss_filedir = os.path.join(os.path.dirname(__file__), '../../backend/kiwoom_open_api_plus/data/scripts/') iss_filename = 'uninstall.iss' iss_filepath = os.path.join(iss_filedir, iss_filename) shutil.copy(iss_filepath, filepath) if reboot: ...
class WallTypeTray(_WallMountedBox, _TopEdge): def __init__(self) -> None: super().__init__() self.addSettingsArgs(edges.StackableSettings) self.buildArgParser('sx', 'sy', 'h', 'hi', 'outside', 'bottom_edge') self.argparser.add_argument('--back_height', action='store', type=float, de...
def probe_csv(path, probe_size=4096, compression=None, for_is_csv=False, minimum_columns=2, minimum_rows=2): OPENS = {None: open, 'zip': ZipProbe} try: import gzip OPENS['gzip'] = gzip.open except ImportError: pass try: import bz2 OPENS['bz2'] = bz2.open excep...
class TestApp(unittest.TestCase): module = browsepy app = browsepy.app def test_config(self): try: with tempfile.NamedTemporaryFile(delete=False) as f: f.write(b'DIRECTORY_DOWNLOADABLE = False\n') name = f.name os.environ['BROWSEPY_TEST_SETTING...
def test_config_non_string_types(): class MyValue(object): def __init__(self, content): self.content = content def __str__(self): return str(self.content) def __repr__(self): return repr(self.content) client = TempStoreClient(server_url='localhost', se...
_scope class TestGetWealth(AEATestCaseEmpty): ('click.echo') def test_get_wealth(self, _echo_mock, password_or_none): self.generate_private_key(password=password_or_none) self.add_private_key(password=password_or_none) self.get_wealth(password=password_or_none) expected_wealth = ...
def test_delete_removes_data_from_underlying_db_after_persist(journal_db, memory_db): memory_db.set(b'1', b'test-a') assert (memory_db.exists(b'1') is True) journal_db.delete(b'1') assert (memory_db.exists(b'1') is True) journal_db.persist() assert (memory_db.exists(b'1') is False)
class override_method(): def __init__(self, view, request, method): self.view = view self.request = request self.method = method self.action = getattr(view, 'action', None) def __enter__(self): self.view.request = clone_request(self.request, self.method) action_ma...
class DWARFInfo(object): def __init__(self, config, debug_info_sec, debug_aranges_sec, debug_abbrev_sec, debug_frame_sec, eh_frame_sec, debug_str_sec, debug_loc_sec, debug_ranges_sec, debug_line_sec, debug_pubtypes_sec, debug_pubnames_sec, debug_addr_sec, debug_str_offsets_sec, debug_line_str_sec, debug_loclists_se...
def create_folders(path: Path) -> Tuple[(str, Path)]: tutorial_folder_name = path.stem filename = ''.join([token.title() for token in tutorial_folder_name.split('_')]) tutorial_folder = TUTORIALS_DIR.joinpath(tutorial_folder_name) assets_folder = (tutorial_folder / 'assets') img_folder = (assets_fol...
def _build_log_service(config: Dict[(str, Any)]) -> LogService: config_dependency: Optional[Dict[(str, Any)]] = config.get('dependency') if ((not config_dependency) or ('LogService' not in config_dependency)): raise KeyError('LogService is absent in the config.') log_svc_config: Dict[(str, Any)] = c...
class MyModel(): def __init__(self, random_seed: int): self.random_seed = random_seed log.info('Init my model') def save(self, checkpoint_path: str) -> None: checkpoint_dir = Path(checkpoint_path) checkpoint_dir.mkdir(parents=True, exist_ok=True) log.info(f'Created dir fo...
class MockGE(): def __init__(self, max_jobs=4, qsub_delay=0.0, qacct_delay=15.0, shell='/bin/bash', database_dir=None, debug=False): if debug: logging.getLogger().setLevel(logging.DEBUG) if (database_dir is None): database_dir = os.path.join(self._user_home(), '.mockGE') ...
def adobe_campaign_dataset_config(db: Session, adobe_campaign_connection_config: ConnectionConfig, adobe_campaign_dataset: Dict[(str, Any)]) -> Generator: fides_key = adobe_campaign_dataset['fides_key'] adobe_campaign_connection_config.name = fides_key adobe_campaign_connection_config.key = fides_key ad...
class OptionSeriesFunnelSonificationDefaultinstrumentoptionsMappingLowpassResonance(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, ...
def extractWeleTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None guidmap = [('/zhan-xian/zhan-xian-chapter-', 'Zhanxian', 'translated'), ('/sin-city/sin-city-chapter-', 'Sin Cit...
class SegmentInfo(): def __init__(self, raw_segment, is_dummy=False): self.base_addr = raw_segment[0] self.size = raw_segment[4] self.flags = raw_segment[6] self.type = raw_segment[7] self.is_dummy = is_dummy def __eq__(self, other): if isinstance(other, self.__cl...
def test_slack_message_attachments_limit(): very_short_attachments = (['attachment'] * (SlackMessageBuilder._MAX_AMOUNT_OF_ATTACHMENTS - 1)) short_attachments = (['attachment'] * SlackMessageBuilder._MAX_AMOUNT_OF_ATTACHMENTS) long_attachments = (['attachment'] * (SlackMessageBuilder._MAX_AMOUNT_OF_ATTACHME...
def test_log_base_10_plus_user_passes_var_list(df_vartypes): transformer = LogTransformer(base='10', variables='Age') X = transformer.fit_transform(df_vartypes) transf_df = df_vartypes.copy() transf_df['Age'] = [1.30103, 1.32222, 1.27875, 1.25527] assert (transformer.base == '10') assert (transf...
class KiwoomOpenApiWNegativeReturnCodeError(KiwoomOpenApiWError): OP_ERR_NONE = 0 OP_ERR_NO_LOGIN = (- 1) OP_ERR_LOGIN = (- 100) OP_ERR_CONNECT = (- 101) OP_ERR_VERSION = (- 102) OP_ERR_TRCODE = (- 103) OP_ERR_NO_REGOPENAPI = (- 104) OP_ERR_SISE_OVERFLOW = (- 200) OP_ERR_ORDER_OVERFL...
def get_refractive_index(glass_name): if (_glass_catalogue is None): _build_glass_catalogue() if (glass_name not in _glass_catalogue): for key in _glass_catalogue.keys(): if (key.lower() == glass_name.lower()): raise ValueError(('The requested glass "%s" was not found...
class ToolboxLayout(QtWidgets.QVBoxLayout): def __init__(self, *args, **kwargs): super(ToolboxLayout, self).__init__(*args, **kwargs) self._setup_ui() def _setup_ui(self): main_tab_widget = QtWidgets.QTabWidget(self.widget()) self.addWidget(main_tab_widget) general_tab_wi...
def test_proj_bad(): msg = 'type-shape of calling argument may not equal the required type-shape' def dot(m: size, x: R[(1, 1)], y: R[m]): huga: R pass with pytest.raises(TypeError, match=msg): def proj(n: size, x: R[(100, 10, 1)], y: R[(10, n)]): dot(n, x[1], y[0])
def initial_alerts(): test_alerts = [PendingTestAlertSchema(id='1', alert_class_id='test_id_1', model_unique_id='elementary.model_id_1', test_unique_id='test_id_1', test_name='test_1', test_created_at='2022-10-10 10:10:10', tags='["one", "two"]', model_meta=dict(owner='["jeff", "john"]'), status='fail', elementary_...
class ListOpsTest(unittest.TestCase): def test_append_empty_lists(self): self.assertEqual(append([], []), []) def test_append_list_to_empty_list(self): self.assertEqual(append([], [1, 2, 3, 4]), [1, 2, 3, 4]) def test_append_empty_list_to_list(self): self.assertEqual(append([1, 2, 3,...
def test_unknown_media_type(): class TestResource(): async def on_get(self, req, resp): resp.content_type = 'nope/json' resp.media = {'something': True} try: (await resp.render_body()) except Exception as ex: assert isinstance(e...