code
stringlengths
281
23.7M
class CodeGenProxy(): def __init__(self, host: str='triton', port: int=8001, verbose: bool=False): self.tokenizer = Tokenizer.from_file('/python-docker/cgtok/tokenizer.json') self.client = client_util.InferenceServerClient(url=f'{host}:{port}', verbose=verbose) self.PAD_CHAR = 50256 ...
def test_correct_number_of_rows_are_generated(): df = gen.generate(props={'region': gen.choice(data=['EMEA', 'LATAM', 'NAM', 'APAC'], weights=[0.1, 0.1, 0.3, 0.5]), 'country': gen.country_codes(region_field='region'), 'contact_name': gen.person(country_field='country')}, count=50, randomstate=np.random.RandomState(...
def verbosity_to_loglevel(verbosity, *, maxlevel=logging.CRITICAL): assert (maxlevel is not None) if isinstance(maxlevel, str): _maxlevel = get_valid_loglevel(maxlevel) if (_maxlevel is None): raise ValueError(f'unsupported maxlevel {maxlevel!r}') maxlevel = maxlevel elif...
_type_check def test_trap_protocol_receiving_log(caplog) -> None: proto = tpt.SNMPTrapReceiverProtocol((lambda _: None)) with caplog.at_level(logging.DEBUG): proto.datagram_received(b'trap-packet', ('192.0.2.1', 42)) assert ('Received packet' in caplog.text) assert ('74 72 61' in caplog.text), '...
class ForCursorA(StmtCursorA): def _cursor_call(self, loop_pattern, all_args): try: (name, count) = NameCountA()(loop_pattern, all_args) count = (f' #{count}' if (count is not None) else '') loop_pattern = f'for {name} in _: _{count}' except: pass ...
_app.callback(Output('opt-result', 'children'), Input('finish-otp', 'n_clicks'), State('psa-pin', 'value'), State('psa-code', 'value')) def finishOtp(n_clicks, code_pin, sms_code): ctx = callback_context if ctx.triggered: try: otp_session = new_otp_session(sms_code, code_pin, app.myp.remote_...
def setup_texas_wind_map(ax, region=((- 107), (- 93), 25.5, 37), coastlines=True, **kwargs): if kwargs: warnings.warn(('All kwargs are being ignored. They are accepted to ' + 'guarantee backward compatibility.'), stacklevel=2) _setup_map(ax, xticks=np.arange((- 106), (- 92), 3), yticks=np.arange(27, 38,...
def extractTalesofDreamwidthOrg(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,...
class OptionSeriesAreaSonificationTracksMapping(Options): def frequency(self) -> 'OptionSeriesAreaSonificationTracksMappingFrequency': return self._config_sub_data('frequency', OptionSeriesAreaSonificationTracksMappingFrequency) def gapBetweenNotes(self) -> 'OptionSeriesAreaSonificationTracksMappingGapb...
class TestSentimentAnalysisDataClass(): ITEMS = [SegmentSentimentAnalysisDataClass(segment='Valid Segement', sentiment='Positive', sentiment_rate=0.5)] .parametrize(('kwargs', 'expected'), [_assign_markers_parametrize(items=ITEMS, general_sentiment=SentimentEnum.POSITIVE.value, general_sentiment_rate=0, expecte...
class MyAgv(DataProcessor): def __init__(self, port='/dev/ttyAMA0', baudrate='115200', timeout=0.1, debug=False): self.debug = debug setup_logging(self.debug) self.log = logging.getLogger(__name__) self._serial_port = serial.Serial() self._serial_port.port = port self...
class Contract(BaseContract): w3: 'Web3' functions: ContractFunctions = None caller: 'ContractCaller' = None events: ContractEvents = None def __init__(self, address: Optional[ChecksumAddress]=None) -> None: _w3 = self.w3 if (_w3 is None): raise AttributeError('The `Contr...
def change(): global mc mode = 1 _mode = input('Please input mode, 1 = high precision, 2 = stabilize (default: 1 ):') try: mode = int(_mode) except Exception: pass print(mode) print('') for _mycbot in mc: print(_mycbot) for i in range(1, 7): if...
def construct_sign_and_send_raw_middleware(private_key_or_account: Union[(_PrivateKey, Collection[_PrivateKey])]) -> Middleware: accounts = gen_normalized_accounts(private_key_or_account) def sign_and_send_raw_middleware(make_request: Callable[([RPCEndpoint, Any], Any)], w3: 'Web3') -> Callable[([RPCEndpoint, A...
def reject_recursive_repeats(to_wrap: Callable[(..., Any)]) -> Callable[(..., Any)]: to_wrap.__already_called = {} (to_wrap) def wrapped(*args: Any) -> Any: arg_instances = tuple(map(id, args)) thread_id = threading.get_ident() thread_local_args = ((thread_id,) + arg_instances) ...
def downgrade(): op.drop_constraint('events_event_topic_id_fkey', 'events', type_='foreignkey') op.execute('ALTER TABLE events ALTER COLUMN event_topic_id TYPE varchar USING event_topic_id::varchar') op.execute('UPDATE events SET event_topic_id = (SELECT name FROM event_topics WHERE event_topics.id=cast(eve...
class GetForObjectModelDbTest(TestModelMixin, TestBase): databases = {'default', 'postgres'} def testGetForObjectModelDb(self): with reversion.create_revision(): obj = TestModel.objects.db_manager('postgres').create() self.assertEqual(Version.objects.get_for_object(obj).count(), 0) ...
class ResizeError(FlowChecksumBase): def runTest(self): self.controller.message_send(ofp.message.bsn_table_set_buckets_size(table_id=TABLE_ID, buckets_size=0)) do_barrier(self.controller) (error, _) = self.controller.poll(ofp.OFPT_ERROR) self.assertIsInstance(error, ofp.message.error...
.parametrize('test_ds,expected_interpolable_spaces', [('test_v5_aktiv.designspace', [({}, {'AktivGroteskVF_Italics_Wght', 'AktivGroteskVF_Italics_WghtWdth', 'AktivGroteskVF_Wght', 'AktivGroteskVF_WghtWdth', 'AktivGroteskVF_WghtWdthItal'})]), ('test_v5_sourceserif.designspace', [({'italic': 0}, {'SourceSerif4Variable-Ro...
def run_in_environment_with_teleport(environment: EnvironmentDefinition, code: str, teleport_info: TeleportInfo, locations: DataLocation, config: RuntimeConfig, adapter_type: str) -> AdapterResponse: compressed_local_packages = None is_remote = (type(environment.host) is FalServerlessHost) deps = get_defaul...
_os(*metadata.platforms) def main(): (server, ip, port) = common.serve_web() url = f' winword = 'C:\\Users\\Public\\winword.exe' wmiprvse = 'C:\\Users\\Public\\wmiprvse.exe' dropped = 'C:\\Users\\Public\\posh.exe' common.copy_file(EXE_FILE, winword) common.copy_file(EXE_FILE, wmiprvse) c...
.parametrize('settype', ['PARAMETER', 'COMPUTATION']) def test_values_infer_simple(tmpdir, merge_files_oneLR, settype): path = os.path.join(str(tmpdir), 'values-infer-simple.dlis') content = [*assemble_set(settype), 'data/chap4-7/eflr/ndattrs/objattr/2.dlis.part', 'data/chap4-7/eflr/ndattrs/objattr/empty-INT.dl...
def test_update_tenant(): tenant = tenant_mgt.create_tenant(display_name='py-update-test', allow_password_sign_up=True, enable_email_link_sign_in=True) try: tenant = tenant_mgt.update_tenant(tenant.tenant_id, display_name='updated-py-tenant', allow_password_sign_up=False, enable_email_link_sign_in=False...
def repeat_with_success_at_least(times, min_success): assert (times >= min_success) def _repeat_with_success_at_least(f): (f) def wrapper(*args, **kwargs): assert (len(args) > 0) instance = args[0] assert isinstance(instance, unittest.TestCase) suc...
class Database(): def lookup_parts(self): raise NotImplementedError('') def lookup_dicts(self, *args, **kwargs): raise NotImplementedError('') def count(self, request): raise NotImplementedError('') def load_iterator(self, iterator): raise NotImplementedError('') def ...
class OptionSeriesHeatmapDataAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag,...
class TestNXActionPopQueue(unittest.TestCase): type_ = {'buf': b'\xff\xff', 'val': ofproto.OFPAT_VENDOR} len_ = {'buf': b'\x00\x10', 'val': ofproto.NX_ACTION_SET_TUNNEL_SIZE} vendor = {'buf': b'\x00\x00# ', 'val': ofproto_common.NX_EXPERIMENTER_ID} subtype = {'buf': b'\x00\x05', 'val': ofproto.NXAST_POP...
('cuda.perm102_bmm_rcr.gen_profiler') def gen_profiler(func_attrs, workdir, profiler_filename, dim_info_dict): args_parser = bmm_common.ARGS_PARSER_TEMPLATE.render(a_dims=['M', 'B', 'K'], b_dims=['B', 'N', 'K'], c_dims=['M', 'B', 'N']) mm_info = _get_default_problem_info(alpha_value=func_attrs.get('alpha', 1)) ...
class ConversionActionQuery(AbstractObject): def __init__(self, api=None): super(ConversionActionQuery, self).__init__() self._isConversionActionQuery = True self._api = api class Field(AbstractObject.Field): field_action_type = 'action.type' application = 'application' ...
class ResultsCacheBase(object): _instance = None def __new__(cls, *args, **kwargs): if (not cls._instance): cls._instance = super(ResultsCacheBase, cls).__new__(cls, *args, **kwargs) return cls._instance def get(self, key): pass def set(self, key, value): pass
class OptionSeriesSolidgaugeOnpointPosition(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_type...
def test_attendee_registered(db, client, jwt, user): user.is_super_admin = True event = EventFactoryBasic() microlocation = MicrolocationSubFactory(event=event) ticket = TicketSubFactory(event=event) station = StationSubFactory(event=event, microlocation=microlocation, station_type='registration') ...
def process_stream_frame(source_face: Face, temp_frame: Frame) -> Frame: for frame_processor_module in get_frame_processors_modules(facefusion.globals.frame_processors): if frame_processor_module.pre_process('stream'): temp_frame = frame_processor_module.process_frame(source_face, None, temp_fra...
def fqdns_from_weblinks(hostname, domains, timeout=5): fqdns = set() addrs = dnsx.resolve(hostname) if (not addrs): return fqdns addr = addrs[0] shodan_result = shodan_get_result(addr) if (not shodan_result): return fqdns for port in shodan_result['data']: if (' not i...
class Client(pyrogram.Client): def __init__(self, *args, **kw): super().__init__(*args, **kw) self.cache = Cache() self.dispatcher = Dispatcher(self) async def authorize(self): if self.bot_token: return (await self.sign_in_bot(self.bot_token)) retry = False ...
_cache() def flowmod(cookie, command, table_id, priority, out_port, out_group, match_fields, inst, hard_timeout, idle_timeout, flags=0): return parser.OFPFlowMod(datapath=None, cookie=cookie, command=command, table_id=table_id, priority=priority, out_port=out_port, out_group=out_group, match=match_fields, instructi...
class _DcBoundMixin(models.Model): dc_bound = models.ForeignKey('vms.Dc', related_name='%(class)s_dc_bound_set', null=True, blank=True, default=None, on_delete=models.SET_NULL) class Meta(): app_label = 'vms' abstract = True def dc_bound_bool(self): return bool(self.dc_bound) _bo...
class DataEnum(): dflt = None js_conversion = False def __init__(self, component, value: Any=None): (self.page, self.__value) = (component.page, (value or self.dflt)) self.component = component def set(self, value: Union[(str, primitives.JsDataModel)]=None): if (value is None): ...
def get_ice_breaker_chain() -> LLMChain: ice_breaker_template = '\n given the information about a person from linkedin {information}, and twitter posts {twitter_posts} I want you to create:\n 2 creative Ice breakers with them that are derived from their activity on Linkedin and twitter, preferably o...
def AutocompleteFilterFactory(title, base_parameter_name, viewname='', use_pk_exact=False, label_by=str): class NewMetaFilter(type(AutocompleteFilter)): def __new__(cls, name, bases, attrs): super_new = super().__new__(cls, name, bases, attrs) super_new.use_pk_exact = use_pk_exact ...
class WallPlaneHolder(_WallMountedBox): def __init__(self) -> None: super().__init__() self.argparser.add_argument('--width', action='store', type=float, default=80, help='width of the plane') self.argparser.add_argument('--length', action='store', type=float, default=250, help='length of th...
class SATATestSoC(SoCMini): def __init__(self, platform, connector='fmc', gen='gen3', with_global_analyzer=False, with_sector2mem_analyzer=False, with_mem2sector_analyzer=False): assert (connector in ['fmc', 'sfp', 'pcie']) assert (gen in ['gen1', 'gen2', 'gen3']) sys_clk_freq = int(.0) ...
class QuantilesTracker(): def __init__(self): self._samples: List = [] def update(self, val: float) -> None: self._samples.append(val) def quantile(self, p) -> float: if (len(self._samples) == 0): return float('Inf') return np.quantile(self._samples, p) def me...
class TestShellHook(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() self.original_dir = os.getcwd() self.hook = ShellHook() self.fs.create_dir(FAKEDIR) def tearDown(self): os.chdir(self.original_dir) def test_cd_pre(self): self.assert...
def test_graph_with_switch_empty_nodes2(task): task.graph.add_nodes_from((vertices := [BasicBlock(0, instructions=[IndirectBranch(variable('a'))]), BasicBlock(1, instructions=[Assignment(variable('a'), Constant(2))]), BasicBlock(2, instructions=[]), BasicBlock(3, instructions=[]), BasicBlock(4, instructions=[]), Ba...
def to_prometheus_format(metrics: typing.Dict[(str, str)], prom_stati: typing.Sequence[typing.Tuple[(str, typing.Mapping[(str, typing.Union[(int, float, None)])])]]) -> typing.List[str]: prom_str_list = [] for (metric_name, metric_desc) in metrics.items(): prom_str_list.append(f'# HELP {metric_name} {me...
def test_fastq_scores_mean(): filename = 'tests/data/test.fastq' expected_scores = [29, 30, 33, 33, 32, 36, 36, 36, 32, 36, 36, 37, 38, 38, 38, 38, 38, 37, 37, 38, 38, 38, 39, 38, 38, 39, 39, 38, 39, 38, 38, 38, 39, 39, 39, 39, 38, 39, 37, 38, 39, 38, 38, 39, 39, 38, 38, 39, 37, 38, 38, 34, 34, 38, 38, 33, 38, ...
class OptionPlotoptionsColumnrangeSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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(...
class OptionSeriesStreamgraphSonificationDefaultinstrumentoptionsMappingLowpass(Options): def frequency(self) -> 'OptionSeriesStreamgraphSonificationDefaultinstrumentoptionsMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesStreamgraphSonificationDefaultinstrumentoptionsMappingL...
class FauxPilotException(Exception): def __init__(self, message: str, error_type: Optional[str]=None, param: Optional[str]=None, code: Optional[int]=None): super().__init__(message) self.message = message self.error_type = error_type self.param = param self.code = code de...
class IApplicationWindow(IWindow): icon = Image() menu_bar_manager = Instance(IMenuBarManager) status_bar_manager = Instance(IStatusBarManager) tool_bar_managers = List(Instance(IToolBarManager)) def _create_contents(self, parent): def _create_menu_bar(self, parent): def _create_status_bar(s...
def detect_and_insert_sdk_include_and_library_dirs(include_dirs, library_dirs) -> None: if (sys.platform == 'win32'): r = detect_win32_sdk_include_and_library_dirs() else: r = None if (r is None): print('Automatic kinect SDK detection did not yield any results.') else: (i...
class GraphML(): def __init__(self, execution_trace: ExecutionTrace): self.nodes: List = [] self.edges: List = [] for (id, n) in execution_trace.nodes.items(): self._create_node(id, f'{n.name} ({n.id})', n.name) for tensor in execution_trace.tensors.values(): ...
class AffiliationAddressTeiTrainingDataGenerator(AbstractTeiTrainingDataGenerator): DEFAULT_TEI_FILENAME_SUFFIX = '.affiliation.tei.xml' def __init__(self): super().__init__(root_training_xml_element_path=ROOT_TRAINING_XML_ELEMENT_PATH, training_xml_element_path_by_label=TRAINING_XML_ELEMENT_PATH_BY_LAB...
def mock_api_response(monkeypatch, status, json_data): class MockResponse(): def __init__(self, status, json_data): self.status = status self.json_data = json_data def status_code(self): return self.status def json(self): return self.json_data ...
class TorchHub(Analyser): in_etype = Etype.Any out_etype = Etype.Any def pre_analyse(self, config): if (config.get('args') is None): config['args'] = [] if (config.get('kwargs') is None): config['kwargs'] = {} self.model = torch.hub.load(config['repo'], *confi...
class TestK8sTaskExecutor(unittest.TestCase): ('ai_flow.task_executor.kubernetes.k8s_task_executor.KubernetesTaskExecutor._list_pods') ('ai_flow.task_executor.kubernetes.k8s_task_executor.KubernetesTaskExecutor._is_task_submitted') ('ai_flow.task_executor.kubernetes.helpers.run_pod') ('ai_flow.task_exec...
def test_interpolate_color() -> None: assert (interpolate_color('#000000', '#ffffff', 0) == '#000000') assert (interpolate_color('#000000', '#ffffff', 1) == '#ffffff') assert (interpolate_color('#000000', '#ffffff', 0.5) == '#7f7f7f') assert (interpolate_color('#000000', '#ffffff', (- 100)) == '#000000'...
class Affine(AffineOp, Elementwise): def __init__(self, params_fn: Optional[flowtorch.Lazy]=None, *, shape: torch.Size, context_shape: Optional[torch.Size]=None, log_scale_min_clip: float=(- 5.0), log_scale_max_clip: float=3.0, sigmoid_bias: float=2.0) -> None: super().__init__(params_fn, shape=shape, conte...
class TestOperationsLog(ApiBaseTest): def setUp(self): super().setUp() (factories.OperationsLogFactory(candidate_committee_id='00', report_year=2000, status_num=1),) (factories.OperationsLogFactory(candidate_committee_id='01', report_year=2012, status_num=0),) (factories.OperationsLo...
class Migration(migrations.Migration): dependencies = [('search', '0029_link_subaward_search_to_transaction_search')] operations = [migrations.AddField(model_name='awardsearch', name='earliest_transaction_search', field=models.ForeignKey(db_constraint=False, help_text='The earliest transaction in transaction_se...
def test_task_node_with_overrides(): task_node = _workflow.TaskNode(reference_id=_generic_id, overrides=_workflow.TaskNodeOverrides(Resources(requests=[Resources.ResourceEntry(Resources.ResourceName.CPU, '1')], limits=[Resources.ResourceEntry(Resources.ResourceName.CPU, '2')]), tasks_pb2.ExtendedResources(gpu_accel...
def test_custom_form_complex_fields_complete(db, client, user, jwt): speaker = get_complex_custom_form_speaker(db, user) data = json.dumps({'data': {'type': 'speaker', 'id': str(speaker.id), 'attributes': {'name': 'Areeb', 'heard-from': 'Gypsie', 'complex-field-values': {'best-friend': 'Tester'}}}}) respons...
def generate_daily_movement_chart(date): df = pd.read_sql(sql=app.session.query(ouraActivitySamples.timestamp_local, ouraActivitySamples.met_1min, ouraActivitySamples.class_5min).filter((ouraActivitySamples.summary_date == date), (ouraActivitySamples.class_5min != None)).statement, con=engine, index_col='timestamp_...
class StringSub(StringTransform): def __init__(self, substring: str, replacement: str, *, reversible: bool=True): super().__init__(reversible) self.substring = substring self.replacement = replacement def _apply(self, string: str) -> str: return string.replace(self.substring, sel...
class ItemTests(unittest.TestCase): def test_unicode(self): item = Item() item.Name = 'test' self.assertEqual(str(item), 'test') def test_to_ref(self): item = Item() item.Name = 'test' item.Id = 100 ref = item.to_ref() self.assertEqual(ref.name, 't...
class Local(DeployBase): def __init__(self, config_json=None, credentials_json=None): DeployBase.__init__(self, config_json=config_json, credentials_json=credentials_json) def deploy(self, model_id): app_type = self._app_type(model_id) if (app_type == 'streamlit'): app = Stre...
def test_build_dirhtml_from_template(temp_with_override, cli): book = (temp_with_override / 'new_book') _ = cli.invoke(commands.create, book.as_posix()) build_result = cli.invoke(commands.build, [book.as_posix(), '-n', '-W', '--builder', 'dirhtml']) assert (build_result.exit_code == 0), build_result.out...
def _bump_protocol_specification_id(package_path: Path, configuration: ProtocolConfig) -> None: spec_id: PublicId = configuration.protocol_specification_id old_version = semver.VersionInfo.parse(spec_id.version) new_version = str(old_version.bump_minor()) new_spec_id = PublicId(spec_id.author, spec_id.n...
def extractMiirakuruWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('rett', 'The Story of Rett Pott', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Lo...
def derivative_upward_kernel(fft_grid, order=1): dims = fft_grid.dims freq_easting = fft_grid.coords[dims[1]] freq_northing = fft_grid.coords[dims[0]] k_easting = ((2 * np.pi) * freq_easting) k_northing = ((2 * np.pi) * freq_northing) da_filter = (np.sqrt(((k_easting ** 2) + (k_northing ** 2))) ...
def find_music_dir(): if ('XDG_MUSIC_DIR' in os.environ): return os.environ['XDG_MUSIC_DIR'] conf = open_first_xdg_config('user-dirs.dirs') if (conf is not None): for line in conf: if (not line.startswith('XDG_MUSIC_DIR=')): continue path = shlex.split...
class TestGetIndices(TestCase): IDX1 = 'index-2016.03.03' IDX2 = 'index-2016.03.04' SETTINGS = {IDX1: {'state': 'open'}, IDX2: {'state': 'open'}} def test_client_exception(self): client = Mock() client.indices.get_settings.return_value = self.SETTINGS client.indices.get_settings....
.parametrize('cls', load_class_with_subfeature()) class TestApiClass(): def test_issubclass(self, cls: ProviderInterface): assert issubclass(cls, ProviderInterface), f'Please inherit {cls} from ProviderInterface' def test_info_file_exists(self, cls: ProviderInterface): provider = cls.provider_na...
class ExcludeFieldsMixin(object): def get_fields(self): fields = super(ExcludeFieldsMixin, self).get_fields() try: exclude = self.context['exclude'] except KeyError: return fields hierarchy = _get_serializer_hierarchy(self) exclude_nested_names = _get_...
class Cutting2DMazeState(): def __init__(self, inventory: [(int, int)], max_pieces_in_inventory: int, current_demand: (int, int), raw_piece_size: (int, int)): self.inventory = inventory.copy() self.max_pieces_in_inventory = max_pieces_in_inventory self.current_demand = current_demand ...
class TestCharacters(BaseEvenniaTest): def setUp(self): super().setUp() self.character = create.create_object(EvAdventureCharacter, key='testchar') def test_abilities(self): self.character.strength += 2 self.assertEqual(self.character.strength, 3) def test_heal(self): ...
class TestMatrixStoreConnection(SimpleTestCase): def setUpClass(cls): cls.factory = DataFactory() cls.factory.create_all(start_date='2018-06-01', num_months=6, num_practices=6, num_presentations=6) cls.matrixstore = matrixstore_from_data_factory(cls.factory) def test_practice_offsets(sel...
class TestRetryingSender(): def test_repr(self): s = RetryingSender() assert repr(s).startswith('RetryingSender(') def test_rate_limited_request_retried_after_set_seconds(self): time = MagicMock() fail = rate_limit_response() success = ok_response() sender = mock_...
.parametrize('input, output', [(0, 0), (float('inf'), float('inf')), (float('-inf'), float('-inf')), (0.1, 0.1), ((- 0.0), (- 0.0)), (0., 0.1), (1, 1), ((- 1), (- 1)), ((- 0.), (- 0.1)), ((- ), (- )), ((- 0.), (- 0.)), (0.5, 0.5), (1.9e-15, 1.9e-15)]) def test_fix_float_single_double_conversion(input, output): asse...
class OptionPlotoptionsPictorialSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsPictorialSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPictorialSonificationTracksMappingHighpassFrequency) def resonance(self) -...
.skipif(bool(missing_avr_buildtools), reason=str(missing_avr_buildtools)) def test_model_size_avr8(): avr_example_program = '\n #include <stdbool.h>\n #include <avr/io.h>\n #include <util/delay.h>\n\n int main()\n {\n // set PINB0 to output in DDRB\n DDRB |= 0b;\n\n // Set input\...
def test_eth_call_offchain_lookup_raises_when_ccip_read_is_disabled(w3, offchain_lookup_contract): with pytest.raises(OffchainLookup): offchain_lookup_contract.functions.testOffchainLookup(OFFCHAIN_LOOKUP_CONTRACT_TEST_DATA).call(ccip_read_enabled=False) with pytest.raises(OffchainLookup): offch...
(tags=['financial'], description=docs.REPORTS, params={'committee_id': {'description': docs.COMMITTEE_ID}}) class CommitteeReportsView(views.ApiResource): _kwargs(args.paging) _kwargs(args.committee_reports) _kwargs(args.make_multi_sort_args(default=['-coverage_end_date'])) _with(schemas.CommitteeReport...
class SMBRelayServer(Thread): def __init__(self, config): Thread.__init__(self) self.daemon = True self.server = 0 self.config = config self.target = None self.targetprocessor = self.config.target self.authUser = None self.proxyTranslator = None ...
def _extract_args(*args, **kwargs): valid_kwargs = ['bcs', 'J', 'Jp', 'M', 'form_compiler_parameters', 'solver_parameters', 'nullspace', 'transpose_nullspace', 'near_nullspace', 'options_prefix', 'appctx'] for kwarg in kwargs.keys(): if (kwarg not in valid_kwargs): raise RuntimeError(("Illeg...
class DomSnackbar(JsHtml.JsHtmlRich): def isOpen(self) -> JsObjects.JsBoolean.JsBoolean: return JsObjects.JsBoolean.JsBoolean.get(("window['%s'].isOpen()" % self.component.htmlCode)) def open(self) -> JsUtils.jsWrap: return JsUtils.jsWrap(("window['%s'].open()" % self.component.htmlCode)) de...
def getOptParser(doc=''): Option = optparse.Option p = optparse.OptionParser(usage=(('%s [OPTIONS] [regexps]\n' % sys.argv[0]) + doc), version=('%prog ' + version)) p.add_options([Option('-l', '--log-level', dest='log_level', default=None, help='Log level for the logger to use during running tests'), Option...
def scan_status(task_id): status_url = (((base_url + '/scan/') + task_id) + '/status') while True: status_url_resp = req.api_request(status_url, 'GET', api_header) if (json.loads(status_url_resp.text)['status'] == 'terminated'): result = show_scan_data(task_id) return res...
_os(*metadata.platforms) def main(): masquerade = '/tmp/defaults' common.create_macos_masquerade(masquerade) common.log('Launching fake defaults command to mimic installing a login hook.') common.execute([masquerade, 'write', 'LoginHook'], timeout=10, kill=True) common.remove_file(masquerade)
class OptionPlotoptionsSankeyTooltipDatetimelabelformats(Options): def day(self): return self._config_get('%A, %e %b %Y') def day(self, text: str): self._config(text, js_type=False) def hour(self): return self._config_get('%A, %e %b, %H:%M') def hour(self, text: str): sel...
class TestVersionLockSchema(unittest.TestCase): def setUpClass(cls): cls.version_lock_contents = {'33f306e8-417c-411b-965c-c2812d6d3f4d': {'rule_name': 'Remote File Download via PowerShell', 'sha256': '8679cd72bf85b67dde3dcfdaba749ed1fa6560bca5efd03ed41c76a500ce31d6', 'type': 'eql', 'version': 4}, '34fde489...
def extractLittleducktlWordpressCom(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_ty...
_page.route('/table/delete_config', methods=['POST']) def table_delete_config(): res = check_uuid(all_data['uuid'], request.json['uuid']) if (res != None): return jsonify(res) if ('config_name' in request.json): if (request.json['config_name'] != all_data['log_config_name']): log...
class BuildTimedelta(PropertyPreprocessor): type = 'to_timedelta' properties_schema_cls = BuildTimedeltaSchema def imports(self): return {'modules': ['datetime']} def process_arg(self, arg, node, raw_args): delta = None if (arg is None): return delta try: ...
class CoprFormFactory(object): def create_form_cls(user=None, group=None, copr=None): class F(CoprForm): id = wtforms.HiddenField() group_id = wtforms.HiddenField() name = wtforms.StringField('Name', validators=[wtforms.validators.DataRequired(), NameCharactersValidator()...
class TestSeq2Pat(unittest.TestCase): TEST_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = (((TEST_DIR + os.sep) + 'data') + os.sep) def test_example(self): seq2pat = Seq2Pat(sequences=[['A', 'C', 'B', 'A', 'D'], ['C', 'B', 'A'], ['C', 'A', 'C', 'D']]) patterns = seq2pat.get_patt...
class ResponseObject(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 {'cache_condition': (str, none_typ...
def push_package(package_id: PackageId, runner: CliRunner) -> None: print('Trying to push {}: {}'.format(package_id.package_type.value, str(package_id.public_id))) cwd = os.getcwd() try: agent_name = 'some_agent' result = runner.invoke(cli, [*CLI_LOG_OPTION, 'create', '--local', '--empty', a...
def _get_meta_from_request(request: Request): meta = {'device_name': escape(request.form['device_name']), 'device_part': escape(request.form['device_part']), 'device_class': escape(request.form['device_class']), 'vendor': escape(request.form['vendor']), 'version': escape(request.form['version']), 'release_date': es...