code
stringlengths
281
23.7M
class CriticViewPreprocessor(Preprocessor): def __init__(self, critic_stash): super().__init__() self.critic_stash = critic_stash def _ins(self, text): if RE_BLOCK_SEP.match(text): return ('\n\n%s\n\n' % self.critic_stash.store('<ins class="critic break">&nbsp;</ins>')) ...
def make_random_data_and_loader(args, ln_emb, m_den): train_data = RandomDataset(m_den, ln_emb, args.data_size, args.num_batches, args.mini_batch_size, args.num_indices_per_lookup, args.num_indices_per_lookup_fixed, 1, args.round_targets, args.data_generation, args.data_trace_file, args.data_trace_enable_padding, r...
def test_qidian(): try: settings = local_entry_point.loadSettings() lock_dict = local_entry_point.initialize_manager() except local_entry_point.SettingsLoadFailed: print('WARNING! No settings!') print('Cannot test storiesonline!') return instance = dispatcher.RpcCallD...
def extractMathranslationBlogspotCom(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 cmd_request_compile_bench(jobs: Jobs, reqid: Optional[RequestID], revision: str, *, remote: Optional[str]=None, branch: Optional[str]=None, benchmarks: Optional[str]=None, optimize: bool=True, debug: bool=False, worker: str='linux', _fake: Any=None) -> Job: if (not reqid): raise NotImplementedError ...
def test_get_ipv6_os(): endpoint = endpoint_factory('foo') endpoint.endpoint_data = {'tenant': 'foo', 'mac': '00:00:00:00:00:00', 'segment': 'foo', 'port': '1', 'ipv6': '1212::1'} endpoint.metadata = {'ipv6_addresses': {}} ipv6_os = GetData._get_ipv6_os(endpoint) assert (ipv6_os == NO_DATA) endp...
class OptionPlotoptionsAreaSonificationDefaultinstrumentoptionsMappingTremoloDepth(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, t...
def bad_matmul_reporter() -> GraphFixer: typer = LatticeTyper() def get_error(bmg: BMGraphBuilder, node: bn.BMGNode) -> Optional[BMGError]: if (not isinstance(node, bn.MatrixMultiplicationNode)): return None lt = typer[node.left] if (not isinstance(lt, bt.BMGMatrixType)): ...
class DRAM(Memory): def global_(cls): return '#include <stdio.h>\n#include <stdlib.h>\n' def alloc(cls, new_name, prim_type, shape, srcinfo): if (len(shape) == 0): return f'{prim_type} {new_name};' return f"{prim_type} *{new_name} = ({prim_type}*) malloc({' * '.join(shape)} *...
.parametrize('deployments', ({'Escrow': {'contractType': 'Escrow', 'address': '0x8c1968deB27251A3f1F4508df32dA4dfD1b7b57f', 'transaction': '0xc60e32c63abfef65d83cc5eb52225de38c3eeca2e5afa961d71c16d0', 'block': '0x4d1a618802bb87752d95db453dddeeaa2f836bedf8769a67ee276b8', 'runtimeBytecode': {'linkDependencies': [{'offset...
class OptionSeriesStreamgraphSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionSeriesStreamgraphSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesStreamgraphSonificationContexttracksMappingHighpassFrequency) def reson...
class OptionPlotoptionsPackedbubbleSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsPackedbubbleSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsPackedbubbleSonificationTracksActivewhen) def instrument(self): return self._config_get...
def create_models(db): class GeoModel(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20)) point = db.Column(Geometry('POINT')) line = db.Column(Geometry('LINESTRING')) polygon = db.Column(Geometry('POLYGON')) multi = db.Column(Geome...
class Guacamole(object): def __init__(self, request, vm=None, username=None, password=None, save_password=False, load_password=False): self.auth = None self.tree = None self.request = request self.vm = vm if (self.vm and (not hasattr(self.vm, '__iter__'))): self.v...
class TranslateTestCase(unittest.TestCase): def test_dna_protein_nogap(self): sequences = [seqrecord('A', 'TTTTTATAA')] expected = ['FL*'] actual = transform.translate(sequences, 'dna2protein') self.assertEqual(expected, [str(i.seq) for i in actual]) def test_dna_protein_nogap_st...
_tasks('spacy.TextCat.v3') def make_textcat_task_v3(parse_responses: Optional[TaskResponseParser[TextCatTask]]=None, prompt_example_type: Optional[Type[FewshotExample]]=None, labels: Union[(List[str], str)]=[], template: str=DEFAULT_TEXTCAT_TEMPLATE_V3, label_definitions: Optional[Dict[(str, str)]]=None, examples: Exam...
class Solution(): def countArrangement(self, n: int) -> int: _cache(None) def dfs(bm, pl): if (pl == 0): return 1 S = 0 for i in range(n): if ((not (bm & (1 << i))) and ((((i + 1) % pl) == 0) or ((pl % (i + 1)) == 0))): ...
class ArbNumericalEvaluation(object): def __init__(self, cache=None): import flint self.flint = flint self.cache = cache def eval(self, expr, **kwargs): stack = kwargs.get('symbol_stack') if ((self.cache is not None) and (stack is None)): wp = kwargs['wp'] ...
class module_audit_disablefunctionbypass(): error_sh_commands_enabled = 'Error, you can already execute system commands' error_mod_cgi_disabled = 'Error, mod_cgi module is not enabled' error_installing_htaccess = 'Error installing .htaccess' error_uploading_script_to_s = "Error uploading CGI script to '...
def get_task_full_content(title, content, wrap_width=None, smart_wrap=False): if (wrap_width is not None): title = text_wrap.wrap_text(title, wrap_width, smart_wrap) if (content is not None): content = text_wrap.wrap_text(content, wrap_width, smart_wrap) title_width = max((len(line) ...
class ChartCss(MixHtmlState.HtmlOverlayStates, Html.Html): requirements = ('charts.css',) name = 'ChartCss' tag = 'table' _chart__type = 'line' _option_cls = OptChartCss.ChartCssOptions def __init__(self, page: primitives.PageModel, width, height, html_code, options, profile): super(Char...
def extractWujizunCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap:...
def MusicControls(settings, playing_status: PlayingStatus, prev_button_pad=None): (accent_color, bg) = (settings['theme']['accent'], settings['theme']['background']) is_muted = settings['muted'] volume = (0 if is_muted else settings['volume']) v_slider_img = (VOLUME_MUTED_IMG if is_muted else VOLUME_IMG...
def extractAshtranslationsNet(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in...
def udpsender(destip, data, dport=514, retrynum=1): if (destip != ''): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if (type(data) is bytes): dsend = data elif (type(data) is str): dsend = bytes(data, 'utf-8') else: dsend = bytes(data) ...
.parametrize('n_detections', [0, 1, 2]) def test_spancat_scoring(noop_config, n_detections): config = Config().from_str(noop_config) nlp = assemble_from_config(config) examples = [] for text in ['Alice works with Bob.', 'Bob lives with Alice.']: predicted = nlp.make_doc(text) reference =...
def test_pred(): geom = AnaPot.get_geom(((- 0.174), 1.27, 0.0)) calc = geom.calculator trst = 0.05 opt_kwargs = {'trust_min': trst, 'trust_radius': trst, 'trust_max': 0.3, 'hessian_recalc': 1, 'max_micro_cycles': 1} opt = RSPRFOptimizer(geom, **opt_kwargs) opt.run() coords = np.array(opt.coo...
.django_db def test_federal_accounts_endpoint_keyword_filter_account_name(client, fixture_data): resp = client.post('/api/v2/federal_accounts/', content_type='application/json', data=json.dumps({'filters': {'fy': '2017'}, 'keyword': 'someth'})) response_data = resp.json() assert (len(response_data['results'...
def bolster_missing_time_periods(filter_time_periods, queryset, date_range_type, columns): (min_date, max_date) = min_and_max_from_date_ranges(filter_time_periods) results = create_full_time_periods(min_date, max_date, date_range_type, columns) for row in queryset: for item in results: s...
class DataSet(): def __init__(self, ds): self._ds = ds self._bbox = {} self._cache = {} def data_vars(self): return self._ds.data_vars def __getitem__(self, key): if (key not in self._cache): self._cache[key] = self._ds[key] return self._cache[key]...
class AaveTransferClassifier(TransferClassifier): def get_transfer(trace: DecodedCallTrace) -> Transfer: return Transfer(block_number=trace.block_number, transaction_hash=trace.transaction_hash, trace_address=trace.trace_address, amount=trace.inputs['value'], to_address=trace.inputs['to'], from_address=trac...
_stats_type(body_single_struct=True) _set_stats_type(ofproto.OFPMP_AGGREGATE, OFPAggregateStats) _set_msg_type(ofproto.OFPT_MULTIPART_REPLY) class OFPAggregateStatsReply(OFPMultipartReply): def __init__(self, datapath, type_=None, **kwargs): super(OFPAggregateStatsReply, self).__init__(datapath, **kwargs)
class TestUploadManualWebhookAccessInputs(): (scope='function') def url(self, db, privacy_request_requires_input, access_manual_webhook, integration_manual_webhook_config): return (V1_URL_PREFIX + PRIVACY_REQUEST_MANUAL_WEBHOOK_ACCESS_INPUT.format(privacy_request_id=privacy_request_requires_input.id, co...
def main(): data = {} with open(sys.argv[1], 'rb') as f: data.update(parse_cnc1_config(f)) data.update(parse_cnc1_cracklist(f, results=True)) for line in data['wordlist'].decode('ascii').split('\r\n'): if (line.find(' ') != (- 1)): (u, p) = line.split(' ', 1) ...
class Extension(extensions.Extension): ident = 'navigation' navigation_extensions = None _property def _extensions(self): if (self.navigation_extensions is None): return OrderedDict(((f'{ext.__module__}.{ext.__name__}', ext) for ext in NavigationExtension.types if (issubclass(ext, Na...
class ModelRemover(ErsiliaBase): def __init__(self, config_json=None, credentials_json=None): ErsiliaBase.__init__(self, config_json=config_json, credentials_json=credentials_json) self.osf_rm = OsfRemover(username=self.cred.OSF.USER, password=self.cred.OSF.PWD) def remove(self, model_id): ...
def test_debug(computer: Computer): print('\n----testing.py----') if (computer.os != 'windows'): print('----DE/WM----\n') print(('deid: %s' % computer.deid)) print(('wmid: %s' % computer.wmid)) print('\n----TERMINAL/SHELL----\n') print(('termid: %s' % computer.terminalid)...
class OptionPlotoptionsWordcloudSonificationTracksActivewhen(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): ...
def main(): check_user() client = CoprClient.create_from_config_file(args.copr_config) os.chdir(args.repos) if (not os.path.isdir(args.repos)): print('{0} is not a directory.'.format(args.repos), file=sys.stderr) for username in os.listdir(args.repos): repos_user_path = os.path.join(...
class SnippetResponseCommon(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_impor...
class Load(IntervalModule): format = '{avg1} {avg5}' settings = ('format', ('color', 'The text color'), ('critical_limit', 'Limit above which the load is considered critical, defaults to amount of cores.'), ('critical_color', 'The critical color')) file = '/proc/loadavg' color = '#ffffff' critical_l...
class PaymentFundingWidget(FormSectionWidget): def __init__(self, form_context, parent=None) -> None: super().__init__(parent) self._form_context = form_context from_widget = FundsSelectionWidget(form_context) amount_widget = PaymentAmountWidget(form_context) self.add_title(_...
def disable_auto_login_without_login(): from koapy.backend.kiwoom_open_api_plus.core.KiwoomOpenApiPlusQAxWidgetMixin import KiwoomOpenApiPlusQAxWidgetUniversalMixin from koapy.backend.kiwoom_open_api_plus.core.KiwoomOpenApiPlusTypeLibSpec import API_MODULE_PATH class GetAPIModulePathStub(): def GetA...
.xfail(raises=ImageComparisonFailure, reason='Matplotlib plots for reasons a different image size.') .skipif((LOW_MEMORY > memory), reason='Travis has too less memory to run it.') def test_hicPlotMatrix_cool_perChr_log1p_chromosomeOrder(): outfile = NamedTemporaryFile(suffix='.png', prefix='hicexplorer_test', delet...
.parametrize('vm_class, code, expect_gas_used', ((ConstantinopleVM, assemble(opcode_values.PUSH1, 0, opcode_values.SLOAD), (3 + 200)), (ConstantinopleVM, assemble(opcode_values.PUSH20, CANONICAL_ADDRESS_A, opcode_values.EXTCODEHASH), (3 + 400)), (IstanbulVM, assemble(opcode_values.PUSH1, 0, opcode_values.SLOAD), (3 + 8...
def test_ot_span(tracer): with tracer.start_active_span('test') as ot_scope_transaction: with tracer.start_active_span('testspan') as ot_scope_span: ot_scope_span.span.set_tag('span.kind', 'custom') with tracer.start_active_span('testspan2') as ot_scope_span2: with tr...
class OptionSeriesTreegraphSonificationDefaultinstrumentoptionsPointgrouping(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:...
def _initialize_all(controller_addr: str, system_app: SystemApp): from dbgpt.model.cluster import RemoteWorkerManager, ModelRegistryClient from dbgpt.model.cluster.worker.manager import _DefaultWorkerManagerFactory if (not system_app.get_component(ComponentType.MODEL_REGISTRY, ModelRegistry, default_compone...
class TestWrite(): def test_dump_path(self, tmpdir): from srsly.ruamel_yaml import YAML fn = (Path(str(tmpdir)) / 'test.yaml') yaml = YAML() data = yaml.map() data['a'] = 1 data['b'] = 2 yaml.dump(data, fn) assert (fn.read_text() == 'a: 1\nb: 2\n') ...
.parametrize('make_state_root_after_create', [True, False]) def test_delete_after_create_in_same_block(state, make_state_root_after_create): state.set_storage(ADDRESS, 0, 1) state.lock_changes() if make_state_root_after_create: state.make_state_root() state.delete_account(ADDRESS) state.lock...
class table_mod_failed_error_msg(error_msg): version = 5 type = 1 err_type = 8 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...
def sync_invoices(center_id=None, start_date=None, end_date=None): if cint(frappe.db.get_single_value('Zenoti Settings', 'enable_zenoti')): if (center_id or cint(frappe.db.get_single_value('Zenoti Settings', 'enable_auto_syncing'))): check_perpetual_inventory_disabled() interval = fr...
class OptionSeriesVennSonificationContexttracksMappingPitch(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 LevelModel(proteus.Transport.OneLevelTransport): nCalls = 0 def __init__(self, uDict, phiDict, testSpaceDict, matType, dofBoundaryConditionsDict, dofBoundaryConditionsSetterDict, coefficients, elementQuadrature, elementBoundaryQuadrature, fluxBoundaryConditionsDict=None, advectiveFluxBoundaryConditionsSet...
class TFLiteFormat(ModelFormat): def __init__(self, model_source=None): self._data = {} self._model_source = None if (model_source is not None): self.model_source = model_source def from_dict(cls, data): data_copy = dict(data) tflite_format = TFLiteFormat(mode...
.parametrize('credentials,ssl_context,expected', [(None, {}, {'security_protocol': 'SSL', 'ssl_context': {}}), (None, None, {'security_protocol': 'PLAINTEXT'}), (auth.SSLCredentials({}), None, {'security_protocol': 'SSL', 'ssl_context': {}}), (auth.SASLCredentials(username='foo', password='bar'), None, {'security_proto...
def extractStrawberrytranslatesWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None titlemap = [('Back to the Apocalypse', 'Back to the Apocalypse', 'translated'), ('Master of Dung...
class OneListMember(Rule): rule: Rule def __init__(self, rule: Rule, name: str='one_child') -> None: Rule.__init__(self, name) self.rule = rule def apply(self, test: Any) -> RuleResult: if (not isinstance(test, list)): return Fail(test) for (i, child) in enumerate...
(scope='session') def heap_secrets(saas_config) -> Dict[(str, Any)]: return {'domain': (pydash.get(saas_config, 'heap.domain') or secrets['domain']), 'app_id': (pydash.get(saas_config, 'heap.app_id') or secrets['app_id']), 'api_key': (pydash.get(saas_config, 'heap.api_key') or secrets['api_key'])}
class run_args(): thrift_spec = None thrift_field_annotations = None thrift_struct_annotations = None __init__ = None def isUnion(): return False def read(self, iprot): if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtocol.THeade...
class ApiSpecifiedOutputError(ErsiliaError): def __init__(self): self.message = 'Specified output is not correct' self.hints = "If you don't specify an output, an interable will be created. If you specify a file extension (.json, .tsv, .csv or .h5), a file will be created. Other valid strings includ...
def test_update_version_inputs_method_updates_the_inputs_of_the_open_version(create_test_data, create_pymel, create_maya_env): data = create_test_data pm = create_pymel maya_env = create_maya_env def open_(version): new_workspace = version.absolute_path pm.workspace.open(new_workspace) ...
class HydraOverrideVisitor(OverrideParserVisitor): def __init__(self, functions: Functions): self.functions = functions def visitPackage(self, ctx: OverrideParser.PackageContext) -> str: return ctx.getText() def visitPackageOrGroup(self, ctx: OverrideParser.PackageOrGroupContext) -> str: ...
(frozen=True) class Pessoa(): nome: str sobrenome: Dict[(str, str)] ddd: int = field(repr=False) telefone: InitVar[Telefone] def __post_init__(self, telefone): if (self.telefone is None): self.telefone(*telefone) def nome_completo(self): return f'{self.nome} {self.sob...
class NotifierTests(unittest.TestCase): def setUp(self): obj = self.obj = NotifierTraits() obj.value1 = 0 obj.value2 = 0 obj.value1_count = 0 obj.value2_count = 0 def tearDown(self): obj = self.obj obj.on_trait_change(self.on_value1_changed, 'value1', remo...
def extractWwwDeadlynovelsIn(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in ...
def convolve(): N = 400000 data = window.Float32Array(N) support = 3 t0 = time() for i in range(support, (N - support)): for j in range((- support), (support + 1)): data[i] += (data[(i + j)] * ((1 / support) * 2)) t1 = time() print(('convolution took %f s' % (t1 - t0)))
def get_rpc_phy_init_sequence(phy_settings, timing_settings): from litedram.phy.rpc.commands import ModeRegister assert (phy_settings.cl == phy_settings.cwl) cl = (phy_settings.cl - 1) nwr = 8 zout = 60 odt = 30 odt_stb = 1 csr_fx = 0 odt_pd = 0 (mr_a, mr_ba) = ModeRegister.dfi_e...
class OptionSeriesHeatmapSonificationContexttracksMappingFrequency(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 ProfilerTestCase(unittest.TestCase): def test_profiler_runner(self): with patch('aitemplate.backend.profiler_runner.extract_profile_result') as mock_extract_profile_result: mock_extract_profile_result.return_value = ('', False) pr = ProfilerRunner(devices=[str(i) for i in range...
class EasyBikeNew(BaseSystem): sync = True FEED_URL = ' def __init__(self, tag, meta, city_uid): super(EasyBikeNew, self).__init__(tag, meta) self.city_uid = city_uid def update(self, scraper=None): if (scraper is None): scraper = utils.PyBikesScraper() data =...
class Secret(_common.FlyteIdlEntity): class MountType(Enum): ANY = _sec.Secret.MountType.ANY ENV_VAR = _sec.Secret.MountType.ENV_VAR FILE = _sec.Secret.MountType.FILE group: Optional[str] = None key: Optional[str] = None group_version: Optional[str] = None mount_requirement: ...
class OptionPlotoptionsLineMarker(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): self._config(num, j...
class OptionXaxisPlotlines(Options): def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('#999999') def color(self, text: str): self._config(text, js_type=False) ...
def vtest(): herder = VpsHerder(debug=True) clientname = 'test-1' (provider, kwargs) = herder.generate_vultr_conf() herder.log.info('Creating instance...') herder.log.info("\tClient name: '%s'", clientname) herder.log.info("\tusing provider: '%s'", provider) herder.log.info("\tkwargs: '%s'",...
() ('all_latest', '--all', '-a', default=False, is_flag=True, help='Upgrades migrations AND fixtures to the latest version.') ('--fixture/', '-f', default=None, help='The fixture which should be upgraded or installed.') ('--force', default=False, is_flag=True, help='Forcefully upgrades the fixtures.') def upgrade(all_l...
class PlotCanvasToolbar(VPlotContainer): align = Enum('ur', 'ul', 'll', 'lr', 'left', 'right', 'top', 'bottom') button_spacing = Int(5) component = Any spacing = 5 fit_components = 'hv' resizable = 'hv' halign = 'center' valign = 'center' fill_padding = False unified_draw = True ...
('{dst_data} = __riscv_vfmacc_vf_f32m1{dst_data}, {lhs_data}, {rhs_data},{vl});') def rvv_vfmacc_1xf32_4xf32(dst: ([f32][4] RVV), lhs: ([f32][1] DRAM), rhs: ([f32][4] RVV), vl: size): assert (stride(dst, 0) == 1) assert (stride(lhs, 0) == 1) assert (stride(rhs, 0) == 1) assert (vl >= 0) assert (v...
def test_database_api_set(db): db[b'key-1'] = b'value-1' assert (db[b'key-1'] == b'value-1') db[b'key-1'] = b'value-2' assert (db[b'key-1'] == b'value-2') db[b'key-1'] = b'value-1' assert (db[b'key-1'] == b'value-1') db[b'key-1'] = b'value-2' assert (db[b'key-1'] == b'value-2')
class T(): def __init__(self): pass def peephole_binop(self, insn): left = insn.src[0] right = insn.src[1] if isinstance(left, instructions.ConstArg): if isinstance(right, instructions.ConstArg): return insn.const_eval() else: ...
class ParseIssueTuple(NamedTuple): code: int message: str callable: str handle: str filename: str line: int start: int end: int preconditions: Iterable[ParseIssueConditionTuple] postconditions: Iterable[ParseIssueConditionTuple] initial_sources: Iterable[ParseIssueLeaf] f...
def refresh_expiration(f): (f) def wrapper(cls, *args, **kwargs): def on_resolve(payload): payload.refresh_expires_in = (timegm(datetime.utcnow().utctimetuple()) + jwt_settings.JWT_REFRESH_EXPIRATION_DELTA.total_seconds()) return payload result = f(cls, *args, **kwargs) ...
('select') ('--log-dir', default='~/.trailscraper/logs', type=click.Path(), help='Where to put logfiles') ('--filter-assumed-role-arn', multiple=True, help='only consider events from this role (can be used multiple times)') ('--use-cloudtrail-api', is_flag=True, default=False, help='Pull Events from CloudtrailAPI inste...
.django_db def test_uei(client, monkeypatch, transaction_data, elasticsearch_transaction_index): setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index) fields = ['Award ID'] request = {'filters': {'keyword': 'testuei', 'award_type_codes': ['A', 'B', 'C', 'D']}, 'fields': fields, 'page': 1, '...
.AnalysisPluginTestConfig(plugin_class=AnalysisPlugin) class TestCryptoMaterial(): def test_gnupg(self, analysis_plugin): _rule_match(analysis_plugin, '0x6C2DF2C5-pub.asc', 'PgpPublicKeyBlock', len(['PgpPublicKeyBlock', 'PgpPublicKeyBlock_GnuPG'])) def test_ssh_public(self, analysis_plugin): _ru...
def test(): assert (("after='ner'" in __solution__) or ('after="ner"' in __solution__)), 'Fugst du die Komponente explizit nach dem Entity Recognizer hinzu?' assert (nlp.pipe_names[(- 1)] == 'animal_component'), 'Hast du die Komponente nach dem Entity Recognizer hinzugefugt?' assert (len(doc.ents) == 2), 'A...
.usefixtures('migrate_db') class CommitteeTestCase(BaseTestCase): def setUp(self): super().setUp() self.longMessage = True self.maxDiff = None self.request_context = rest.app.test_request_context() self.request_context.push() self.connection = db.engine.connect() ...
def ForceWord(ea): if ((ea != BADADDR) and (ea != 0)): if ((not is_word(get_full_flags(ea))) or (get_item_size(ea) != 2)): del_items(ea, DELIT_SIMPLE, 2) create_data(ea, FF_WORD, 2, BADADDR) if (is_off0(get_full_flags(ea)) and (get_fixup_target_type(ea) == (- 1))): ...
_default class Thread(ThreadABC): session = attr.ib(type=_session.Session) id = attr.ib(converter=str, type=str) def _to_send_data(self): raise NotImplementedError('The method you called is not supported on raw Thread objects. Please use an appropriate User/Group/Page object instead!') def _copy...
def template_function(getter, converter=False, to_save=False) -> None: data = getter() print(f'Got `{data}`') if ((len(data) <= 3) and converter): data = converter(data) else: print('Skip conversion') if to_save: saver() print(f'`{data}` was processed')
def searchDelegates(params, fparser): server = params.get('server') email = params.get('email') password = params.get('password') if isinstance(fparser.get('galList'), str): fname = ''.join(fparser.get('galList')) fname = fname.split(' ') else: fname = fparser.get('galList') ...
def test_app_unimportable_other(caplog: pytest.LogCaptureFixture) -> None: config = Config(app='tests.test_config:app') with pytest.raises(SystemExit): config.load() error_messages = [record.message for record in caplog.records if ((record.name == 'uvicorn.error') and (record.levelname == 'ERROR'))]...
('requests.post') def test_notify_start(post_mock, url, service_match, task_definition): post_mock.return_value = NotifyResponseSuccessfulMock() task_definition.set_images(webserver=u'new-image:my-tag', application=u'app-image:another-tag') task_definition.set_environment((('webserver', 'foo', 'baz'),)) ...
def send_and_check_distances(argv, tdb, clip, distances): if (not distances): if argv.detail: print('No distances, no submission.') return False while distances: rechecks = submit_distances(argv, tdb, distances) if (not rechecks): break distances =...
def build_classifier(cmodel, name, temp_dir, include_dir, func=None, test_function=None): if (not os.path.exists(temp_dir)): os.makedirs(temp_dir) if (test_function is None): test_function = 'eml_test_read_csv' cc = new_compiler(force=1) tree_name = name def_file_name = (name + '.h')...
def getOptionBox(self, title): box = self.widgetManager.get(WIDGET_NAMES.OptionBox, title) if (box.kind == 'ticks'): val = self.widgetManager.get(WIDGET_NAMES.TickOptionBox, title, group=WidgetManager.VARS) retVal = {} for (k, v) in val.items(): retVal[k] = bool(v.get()) ...
class OptionSeriesArearangeSonificationDefaultinstrumentoptionsMappingHighpassResonance(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(se...
def anim(): dist = (dwarf.pos - giant.pos) force = ((((6.7e-11 * giant.mass) * dwarf.mass) * dist) / (sqrt((((dist[0] ** 2) + (dist[1] ** 2)) + (dist[2] ** 2))) ** 3)) giant.p = (giant.p + (force * dt)) dwarf.p = (dwarf.p - (force * dt)) for a in [giant, dwarf]: a.pos = (a.pos + ((a.p / a.ma...
class KiwoomOpenApiPlusQAxWidget(QWidgetLogging, KiwoomOpenApiPlusQAxWidgetUniversalMixin, KiwoomOpenApiPlusQAxWidgetServerSideMixin): CLSID = '{A1574A0D-6BFA-4BD7-9020-DEDD}' PROGID = 'KHOPENAPI.KHOpenApiCtrl.1' METHOD_NAMES = KiwoomOpenApiPlusDispatchSignature.names() EVENT_NAMES = KiwoomOpenApiPlusEv...
class SlotPool(): __slots__ = ('num_free', 'capacity', '_slots', '_loop', '_get_waiters', '_slot_ready_waiter') def __init__(self): self.num_free = 0 self.capacity = 0 self._slots = deque() self._loop = asyncio.get_event_loop_policy().get_event_loop() self._get_waiters = ...