code
stringlengths
281
23.7M
def test_correct_response_with_date_type(client, monkeypatch, elasticsearch_transaction_index, subagency_award): setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index) resp = client.post('/api/v2/search/spending_by_category/awarding_subagency', content_type='application/json', data=json.dumps({'...
def _list_providers(verbose=False): if isinstance(verbose, str): try: verbose = eval(verbose.capitalize()) except (NameError, SyntaxError) as e: print("Please pass 'True' or 'False'.") raise e with _get_data_folder().joinpath('providers-config.yaml').open() as...
class Magic(): _magics: ClassVar[dict[(str, BaseMagic)]] = {'SingleLineMagic': SingleLineMagic(), 'MultiLineMagic': MultiLineMagic(), 'ParagraphMagic': ParagraphMagic(), 'EmailMagic': EmailMagic(), 'UrlMagic': UrlMagic()} def apply(self, ocr_result: OcrResult) -> OcrResult: ocr_result.magic_scores = sel...
class EGridHead(): file_head: Filehead mapunits: (Units | None) = None mapaxes: (MapAxes | None) = None gridunit: (GridUnit | None) = None gdorient: (GdOrient | None) = None def to_egrid(self) -> list[tuple[(str, Any)]]: result = [('FILEHEAD', self.file_head.to_egrid())] if (self...
class OptionPlotoptionsAreasplinerangeSonificationTracksMappingLowpassResonance(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...
def get_speakers_layout(init_speakers=[], default_speaker=None): with gr.Blocks(): n_speakers = gr.Slider(label='Number of Speakers', minimum=1, maximum=MAX_MIXING_SPEAKERS, value=1, step=1) speakers = [] speaker_weights = [] for i in range(MAX_MIXING_SPEAKERS): with gr.R...
def test_psi4(): geom = geom_from_library('hcn_iso_ts.xyz') psi4_kwargs = {'pal': 4, 'mem': 2000, 'method': 'b3lyp', 'basis': 'def2-svp'} psi4 = Psi4(**psi4_kwargs) geom.set_calculator(psi4) print(psi4.base_cmd) f = geom.forces print(f) e = geom.energy print(e) start = time() ...
class GeoGoogle(): def __init__(self, ui): self.page = ui.page self.chartFamily = 'GoogleMaps' def maps(self, latitude: float, longitude: float, profile: Union[(dict, bool)]=None, options: dict=None, width: Union[(int, tuple)]=(100, '%'), height: Union[(int, tuple)]=(Defaults_html.CHARTS_HEIGHT_...
def main(): logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s') known_args = parse_args() model_save_path = known_args.model_path epoch = known_args.epoch sample_count = known_args.sample_count logger.info(f'Model will be trained with {sample_count} samples for {epoc...
class ShotManagerUI(object): __company_name__ = 'Erkan Ozgur Yilmaz' __app_name__ = 'Shot Tools' __version__ = '0.0.1' def __init__(self, layout): self.main_layout = layout self.parent_widget = self.main_layout.parent() self.form_layout = None self.active_projects_only_ch...
def resample_and_mask_metric(subject_id, dscalar, hemisphere, source_mesh, dest_mesh, current_sphere='sphere', dest_sphere='sphere'): map_name = dscalar['mapname'] metric_in = metric_file(subject_id, map_name, hemisphere, source_mesh) metric_out = metric_file(subject_id, map_name, hemisphere, dest_mesh) ...
class DatePicker(Html.Html): requirements = ('jqueryui',) name = 'Date Picker' _option_cls = OptCalendars.OptionDatePicker def __init__(self, page: primitives.PageModel, value, label: Optional[str], icon: Optional[str], width: tuple, height: tuple, color: Optional[str], html_code: Optional[str], profile...
class Snapshot(Base): __tablename__ = 'snapshots' id = Column(Integer, primary_key=True) name = Column(String, index=True, nullable=False) timestamp = Column(Timestamp(timezone=True), server_default=current_timestamp()) library_id = Column(Integer, ForeignKey('libraries.id'), nullable=False) lib...
def legacy_convert_requirement(parsed_req): reqs = [] conflicts = [] for spec in parsed_req.specs: req = legacy_convert(parsed_req.project_name, spec[0], spec[1]) if (spec[0] == '~='): reqs.append(req[0]) reqs.append(req[1]) elif (spec[0] == '!='): ...
_flyte_cli.command('update-cluster-resource-attributes', cls=_FlyteSubCommand) _host_option _insecure_option _project_option _domain_option _optional_name_option _click.option('--attributes', type=(str, str), multiple=True) def update_cluster_resource_attributes(host, insecure, project, domain, name, attributes): _...
class LazySpeller(): def __init__(self): self.speller = None def __call__(self, sentence): print('autocorrect.spell is deprecated, use autocorrect.Speller instead') if (self.speller is None): self.speller = Speller() return self.speller(sentence)
def _fft(vals, modulus, roots_of_unity): if ((len(vals) <= 4) and (type(vals[0]) != tuple)): return _simple_ft(vals, modulus, roots_of_unity) elif ((len(vals) == 1) and (type(vals[0]) == tuple)): return vals L = _fft(vals[::2], modulus, roots_of_unity[::2]) R = _fft(vals[1::2], modulus, ...
.django_db(transaction=True) def test_download_awards_with_all_award_types(client, _award_download_data): download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string()) filters = {'agency': 'all', 'prime_award_types': [*list(award_type_mapping.keys())], 'sub_award_types': [*all_subaward_t...
class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Invalid input.') default_code = 'invalid' default_params = {} def __init__(self, detail=None, code=None, params=None): if (detail is None): detail = self.default_detail if (...
.filterwarnings('ignore:Default values*') def test_irapasc_bytesio_threading(default_surface): def test_xtgeo(): stream = io.BytesIO() surface = xtgeo.RegularSurface(**default_surface) surface.to_file(stream, fformat='irap_ascii') print('XTGeo succeeded') threading.Timer(1.0, tes...
def parse_arguments(): parser = argparse.ArgumentParser(description='args for main.py') parser.add_argument('--input', type=str, default='Suggest at least five related search terms to "Mang neural nhan tao".') parser.add_argument('--approx_model_name', type=str, default=MODELZOO['llama2-7b']) parser.add...
class ETMMsg(Message): file_id: Optional[str] = None file_unique_id: Optional[str] = None type_telegram: TGMsgType chat: ETMChatType author: ETMChatMember __file = None __path = None __filename = None def __init__(self, attributes: Optional[MessageAttribute]=None, author: ChatMember=...
def extractAfterhourssolaceCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [("today's dinner is the hero", 'Todays Dinner is the Hero.', 'translated'), ("today's dinner is the...
class TestComposerThread_check_all_karma_thresholds(ComposerThreadBaseTestCase): ('bodhi.server.models.Update.check_karma_thresholds', mock.MagicMock(side_effect=exceptions.BodhiException('BOOM'))) ('bodhi.server.tasks.composer.log') def test_BodhiException(self, mocked_log): mocked_log.exception = ...
def test_app_mount(tmpdir, test_client_factory): path = os.path.join(tmpdir, 'example.txt') with open(path, 'w') as file: file.write('<file content>') app = Starlette(routes=[Mount('/static', StaticFiles(directory=tmpdir))]) client = test_client_factory(app) response = client.get('/static/ex...
class Database(): def __init__(self, convert_bits=False): self.all_bits = set() self.properties_bits = dict() self.convert_bits = convert_bits self.populate() def populate(self): for (file1, file2) in get_file_pairs(): for (property_str, bit) in generate_diffe...
def test_template_matching_phase_raises_exception_if_incorrect_trace_size(sf, template_datas): ths_building = scared.traces.formats.read_ths_from_ram(template_datas.building_samples, plaintext=template_datas.building_plaintext, key=np.array([template_datas.building_key for i in range(len(template_datas.building_sam...
def test_enctype_debug_helper(app, client): from flask.debughelpers import DebugFilesKeyError app.debug = True ('/fail', methods=['POST']) def index(): return flask.request.files['foo'].filename with client: with pytest.raises(DebugFilesKeyError) as e: client.post('/fail'...
class TraceContextInterceptor(ClientInterceptor): def intercept(self, method: Callable, request_or_iterator: Any, call_details: ClientCallDetails): current_span = get_current_span_context() if (current_span is not None): new_details = call_details._replace(metadata=(*(call_details.metada...
class Coords(Tidy3dBaseModel): x: Coords1D = pd.Field(..., title='X Coordinates', description='1-dimensional array of x coordinates.') y: Coords1D = pd.Field(..., title='Y Coordinates', description='1-dimensional array of y coordinates.') z: Coords1D = pd.Field(..., title='Z Coordinates', description='1-dim...
def test_get_authenticator_pkce(): cfg = PlatformConfig() authn = get_authenticator(cfg, get_client_config()) assert authn assert isinstance(authn, PKCEAuthenticator) cfg = PlatformConfig(insecure_skip_verify=True) authn = get_authenticator(cfg, get_client_config()) assert authn assert i...
class OptionSeriesSolidgaugeSonificationContexttracksMappingLowpassFrequency(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: s...
def s3_setup_args(s3_cfg: configuration.S3Config, anonymous: bool=False) -> Dict[(str, Any)]: kwargs: Dict[(str, Any)] = {'cache_regions': True} if s3_cfg.access_key_id: kwargs[_FSSPEC_S3_KEY_ID] = s3_cfg.access_key_id if s3_cfg.secret_access_key: kwargs[_FSSPEC_S3_SECRET] = s3_cfg.secret_ac...
('./contracts/v2/bulk_download/status.md > Bulk Download Status > GET') def before_bulk_download_status_test(transaction): body = {'filters': {'agency': 50, 'award_types': ['contracts', 'grants'], 'date_range': {'start_date': '2019-01-01', 'end_date': '2019-12-31'}, 'date_type': 'action_date'}, 'award_levels': ['pr...
class _AEAYamlDumper(yaml.SafeDumper): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) _AEAYamlDumper.add_representer(OrderedDict, self._dict_representer) def _dict_representer(dumper: '_AEAYamlDumper', data: OrderedDict) -> MappingNode: return du...
class TelemetryMessageEmbedded(object): swagger_types = {'extension': 'TelemetryExtension'} attribute_map = {'extension': 'extension'} def __init__(self, extension=None): self._extension = None self.discriminator = None if (extension is not None): self.extension = extensi...
def mod_group_entry(dp, group, cmd): ofp = dp.ofproto parser = dp.ofproto_parser group_type = str(group.get('type', 'ALL')) t = UTIL.ofp_group_type_from_user(group_type) group_type = (t if (t != group_type) else None) if (group_type is None): LOG.error('Unknown group type: %s', group.get...
class Test_SendMail(): .dict('bodhi.server.mail.config', {'smtp_server': 'smtp.fp.o'}) ('bodhi.server.mail.log.warning') ('bodhi.server.mail.smtplib.SMTP') def test_recipients_refused(self, SMTP, warning): smtp = SMTP.return_value smtp.sendmail.side_effect = smtplib.SMTPRecipientsRefused...
class IPv6Dest(Destination, NonVrfPathProcessingMixin): ROUTE_FAMILY = RF_IPv6_UC def _best_path_lost(self): old_best_path = self._best_path NonVrfPathProcessingMixin._best_path_lost(self) self._core_service._signal_bus.best_path_changed(old_best_path, True) def _new_best_path(self, ...
class ResourceNotFoundError(FandoghAPIError): message = 'Resource Not found' def __init__(self, response, message=None): self.response = response if message: self.message = message if hasattr(self.response, 'json'): self.message = self.response.json().get('message...
class Sidebar(): def __init__(self): self.ADDON_NOTES_TAB: int = 1 self.PDF_IMPORT_TAB: int = 2 self.SPECIAL_SEARCHES_TAB: int = 3 self.tab: int = self.ADDON_NOTES_TAB self._editor: Editor = None def set_editor(self, editor: Editor): self._editor = editor def ...
def tuplify_forward(model, X, is_train): Ys = [] backprops = [] for layer in model.layers: (Y, backprop) = layer(X, is_train) Ys.append(Y) backprops.append(backprop) def backprop_tuplify(dYs): dXs = [bp(dY) for (bp, dY) in zip(backprops, dYs)] dX = dXs[0] ...
def verify_deposit_data_json(filefolder: str, credentials: Sequence[Credential]) -> bool: with open(filefolder, 'r') as f: deposit_json = json.load(f) with click.progressbar(deposit_json, label=load_text(['msg_deposit_verification']), show_percent=False, show_pos=True) as deposits: retur...
class PortModFlood(base_tests.SimpleDataPlane): def runTest(self): logging.info('Running PortModFlood Test') of_ports = config['port_map'].keys() of_ports.sort() logging.info('Sends Features Request and retrieve Port Configuration from reply') (hw_addr, port_config, advert) =...
def extractHaraftranslationWordpressCom(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, t...
def extractKobatoChanDaiSukiScan(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('Lookism' in item['tags']): return None if ('webtoon' in item['tags']): return None...
def test_span_finder_model(): nlp = Language() docs = [nlp('This is an example.'), nlp('This is the second example.')] docs[0].spans[TRAINING_KEY] = [docs[0][3:4]] docs[1].spans[TRAINING_KEY] = [docs[1][3:5]] total_tokens = 0 for doc in docs: total_tokens += len(doc) config = Config(...
class OptionPlotoptionsColumnpyramidTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionPlotoptionsColumnpyramidToolt...
def kill_running_rally_instances(): def rally_process(p): return ((p.name() == 'esrally') or (p.name() == 'rally') or (p.name().lower().startswith('python') and any((('esrally' in e) for e in p.cmdline())) and (not any((('esrallyd' in e) for e in p.cmdline()))))) kill_all(rally_process)
class ActivityFailureInfo(betterproto.Message): scheduled_event_id: int = betterproto.int64_field(1) started_event_id: int = betterproto.int64_field(2) identity: str = betterproto.string_field(3) activity_type: v1common.ActivityType = betterproto.message_field(4) activity_id: str = betterproto.strin...
class OptionSeriesScatterSonificationDefaultinstrumentoptionsMapping(Options): def frequency(self) -> 'OptionSeriesScatterSonificationDefaultinstrumentoptionsMappingFrequency': return self._config_sub_data('frequency', OptionSeriesScatterSonificationDefaultinstrumentoptionsMappingFrequency) def gapBetwe...
def test_in_thread4(): res = [] class MyComp1(event.Component): foo = event.IntProp(0, settable=True) ('foo') def on_foo(self, *events): for ev in events: res.append(ev.new_value) def main(): loop = asyncio.new_event_loop() event.loop.integ...
class TaxRateDetails(QuickbooksBaseObject): qbo_object_name = 'TaxRateDetails' def __init__(self): super(TaxRateDetails, self).__init__() self.TaxRateName = None self.TaxRateId = None self.RateValue = None self.TaxAgencyId = None self.TaxApplicableOn = 'Sales' ...
def award_with_toptier_agency(id, toa=0, outlay=0): agency = baker.make('references.Agency', toptier_agency_id=id, toptier_flag=True, _fill_optional=True) a1 = baker.make('search.AwardSearch', award_id=id, type='A', funding_agency_id=agency.id, funding_toptier_agency_code=f'00{agency.id}', total_loan_value=0, l...
def guess_new_para_interactive(wordmap): print('What is:', wordmap) if (not wordmap['lemma']): print('No guessing paras without lemmas yet') return 'X_IGNORE' s = wordmap['lemma'] para = None if s.endswith('kko'): para = choose_from(['NOUN_UKKO', 'NOUN_LEPAKKO', 'PROPN_UKKO',...
class MacToPortTable(object): def __init__(self): super(MacToPortTable, self).__init__() self.mac_to_port = {} def dpid_add(self, dpid): LOG.debug('dpid_add: 0x%016x', dpid) self.mac_to_port.setdefault(dpid, {}) def port_add(self, dpid, port, mac): old_port = self.mac...
def test_records_next_observations(): env = build_dummy_structured_env() rollout_generator = RolloutGenerator(env=env, record_next_observations=True) policy = RandomPolicy(env.action_spaces_dict) trajectory = rollout_generator.rollout(policy, n_steps=10) assert (len(trajectory) == 10) sub_step_k...
(cls=FlaskBBGroup, create_app=make_app, add_version_option=False, invoke_without_command=True) ('--config', expose_value=False, callback=set_config, required=False, is_flag=False, is_eager=True, metavar='CONFIG', help="Specify the config to use either in dotted module notation e.g. 'flaskbb.configs.default.DefaultConfi...
def check_return(result_array, checks, only_docs=False): comm_lines = [] found_docs = False idx = 0 for (i, hover_line) in enumerate(result_array['contents']['value'].splitlines()): if (hover_line == '-----'): found_docs = True if (found_docs and only_docs): comm_...
def _get_benchmark_names(benchmarksdir): manifest = os.path.join(benchmarksdir, 'MANIFEST') if os.path.isfile(manifest): with open(manifest) as infile: for line in infile: if (line.strip() == '[benchmarks]'): for line in infile: if ...
class HTMLCompress(jinja2.ext.Extension): context_class = HTMLCompressContext token_class = jinja2.lexer.Token block_tokens = {'variable_begin': 'variable_end', 'block_begin': 'block_end'} def filter_stream(self, stream): transform = self.context_class() lineno = 0 skip_until_tok...
def deselect(self, context): bm = bmesh.from_edit_mesh(bpy.context.active_object.data) uv_layers = bm.loops.layers.uv.verify() islands = utilities_uv.getSelectionIslands(bm, uv_layers) if islands: for face in islands[0]: for loop in face.loops: loop[uv_layers].select ...
class OptionPlotoptionsTreegraphSonificationTracksActivewhen(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): ...
class OptionSeriesDumbbellMarker(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, js...
def extractThelotusworldCom(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 t...
def bfs(graph, start): dist = {start: 0} parents = {start: None} for i in range(len(graph)): if (i != start): dist[i] = math.inf parents[i] = [] queue = [start] while queue: node = queue.pop() for neighbor in graph[node]: if (dist[neighbor]...
def find_program(name): if (os.path.isabs(name) and PathInfo(name).is_executable): return name for path in os.environ['PATH'].split(os.pathsep): name_path = os.path.abspath(os.path.join(path, name)) if PathInfo(name_path).is_executable: return name_path return None
class TestCompositeContext(): def test_cannot_be_used_outside_of_composite(self): with pytest.raises(exceptions.RallyAssertionError) as exc: runner.CompositeContext.put('test', 1) assert (exc.value.args[0] == 'This operation is only allowed inside a composite operation.') .asyncio ...
('no_yaml_module_installed') def test_option_no_yaml_installed(config, yaml_config_file_1): with raises(errors.Error) as error: config.option.from_yaml(yaml_config_file_1) assert (error.value.args[0] == 'Unable to load yaml configuration - PyYAML is not installed. Install PyYAML or install Dependency In...
def test_tuple(): c = Config('testconfig', foo=('1,2', [int], ''), bar=((1, 2, 3), [str], '')) assert (c.foo == (1, 2)) assert (c.bar == ('1', '2', '3')) c.foo = (1.2, 3.3, 5) assert (c.foo == (1, 3, 5)) c.foo = '(7, 8, 9)' assert (c.foo == (7, 8, 9)) c.foo = '1, 2,-3,4' ...
class OptionPlotoptionsSplineSonificationTracksMappingLowpassResonance(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 Experiment(SAC): def __init__(self, config, create_train_env, create_env, create_agent): super().__init__(config, create_train_env, create_env, create_agent) def _create_model(self): module = SACPolicy(self.obs_dim, self.action_dim, 16) module.apply(weight_init) return modu...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = 'name' fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':...
class PaymentManager(BaseManager): def __init__(self, name, credentials, unit_price_4dps=False, user_agent=None): self.credentials = credentials self.name = name self.base_url = (credentials.base_url + XERO_API_URL) self.extra_params = ({'unitdp': 4} if unit_price_4dps else {}) ...
class OptionSeriesPieSonificationTracksMappingPitch(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._config(...
def lazy_import(): from fastly.model.included_with_waf_exclusion import IncludedWithWafExclusion from fastly.model.pagination import Pagination from fastly.model.pagination_links import PaginationLinks from fastly.model.pagination_meta import PaginationMeta from fastly.model.waf_exclusion_response_d...
class BaseNodeSpec(EntitySpec): def __init__(self, params): super().__init__(params) def _lookup(self, depth, unlocked=False): name = self._params['config']['name'] return SpecView(self, depth=[depth], name=name, unlocked=unlocked) def config(self) -> SpecView: return self._l...
class TestAndIncr(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec subtypeSpec += ConstraintsUnion(ValueRangeConstraint(0, )) if mibBuilder.loadTexts: description = "Represents integer-valued information used for atomic operations. When the\nmanagement protoc...
class SudoGenericTokenError(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 {'msg': (str,)} _proper...
def plot_diagnostics(samples: MonteCarloSamples, ordering: Union[(None, List[str])]=None, plot_posterior: bool=False) -> List[Figure]: COLORS = ['#2a2eec', '#fa7c17', '#328c06', '#c10c90'] samples_xr = samples.to_xarray() data = {str(key): value.values for (key, value) in samples_xr.data_vars.items()} i...
class StalkerSceneAddAllShotLightingOutputsOperator(bpy.types.Operator): bl_label = 'Add All Shot Lighting Outputs' bl_idname = 'stalker.scene_add_all_shot_lighting_outputs_op' stalker_entity_id = bpy.props.IntProperty(name='stalker_entity_id') stalker_entity_name = bpy.props.StringProperty(name='stalke...
class Solution(): def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: choice = (- 1) count = 0 for (i, e) in enumerate(self.nums): if (e != target): continue if (random.randint(0, count) == 0): ...
def setup_qat_get_optimizer_param_groups(model, qat_method): if (not qat_method.startswith('learnable')): return model assert _is_q_state_dict(model.state_dict()) model = mixin_with_subclass(model, ModelGetOptimizerParamGroupLearnableQATMixin) assert hasattr(model, 'get_optimizer_param_groups') ...
def test_records_episode_with_correct_data(): env = build_dummy_maze_env() env = ActionRecordingWrapper.wrap(env, record_maze_actions=True, record_actions=True, output_dir='action_records') actions = [] env.seed(1234) env.reset() cum_reward = 0.0 for _ in range(5): action = env.actio...
class OptionPlotoptionsScatterSonificationContexttracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsScatterSonificationContexttracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsScatterSonificationContexttracksMappingTremoloDepth) def speed(self) -> 'Optio...
def extractMtlparadiseWordpressCom(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_typ...
.signal_handling def test_dispatch_with_multi_kwarg_message_transformer_succeeds(fake_sqs_queue): queue = fake_sqs_queue queue.send_message(MessageBody=1234) dispatcher = SQSWorkDispatcher(queue, worker_process_name='Test Worker Process', long_poll_seconds=1, monitor_sleep_time=1) def do_some_work(task_...
def shfl_scan(arr_in: ti.template(), in_beg: ti.i32, in_end: ti.i32, sum_smem: ti.template(), single_block: ti.template()): ti.loop_config(block_dim=BLOCK_SZ) for i in range(in_beg, in_end): val = arr_in[i] thread_id = (i % BLOCK_SZ) block_id = int(((i - in_beg) // BLOCK_SZ)) lan...
def seed_bigquery_integration_db(bigquery_integration_engine) -> None: statements = ['\n DROP TABLE IF EXISTS fidesopstest.report;\n ', '\n DROP TABLE IF EXISTS fidesopstest.service_request;\n ', '\n DROP TABLE IF EXISTS fidesopstest.login;\n ', '\n DROP TABLE IF EXI...
def fortios_authentication(data, fos, check_mode): fos.do_member_operation('authentication', 'rule') if data['authentication_rule']: resp = authentication_rule(data, fos, check_mode) else: fos._module.fail_json(msg=('missing task body: %s' % 'authentication_rule')) if check_mode: ...
class ResourceRulesEngineTest(ForsetiTestCase): def setUp(self): resource_rules_engine.LOGGER = mock.MagicMock() def test_build_rule_book_from_local_yaml_file(self): rule = '\nrules:\n- name: Resource test rule\n mode: required\n resource_types: [project]\n resource_trees: []\n' rules...
_HOOK_REGISTRY.register() class ActivationCheckpointModelingHook(mh.ModelingHook): def apply(self, model: nn.Module) -> nn.Module: logger.info('Activation Checkpointing is used') wrapper_fn = partial(checkpoint_wrapper, checkpoint_impl=(CheckpointImpl.NO_REENTRANT if (not self.cfg.ACTIVATION_CHECKPO...
class TestPeriodFilterAbsolute(TestCase): def builder(self, key='2'): self.client = Mock() self.client.info.return_value = get_es_ver() self.client.cat.indices.return_value = get_testvals(key, 'state') self.client.indices.get_settings.return_value = get_testvals(key, 'settings') ...
def _check_offsets(offsets_list: List[List[int]]) -> None: offsets_len = len(offsets_list[0]) for offsets in offsets_list: assert (offsets[0] == 0) assert (len(offsets) == offsets_len) for j in range(1, len(offsets)): assert (offsets[j] >= offsets[(j - 1)]) offsets_le...
def main(): parser = argparse.ArgumentParser(description='Verify IOB FASM vs BELs.') parser.add_argument('--fasm') parser.add_argument('--params') args = parser.parse_args() if ((not args.fasm) and (not args.params)): scan_specimens() else: count = process_specimen(fasm_file=args...
def extractPlebianfinetranslationWordpressCom(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, n...
class OptionSeriesAreaSonificationDefaultinstrumentoptionsPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool...
class Node(ABC): parent: Optional['Node'] children: List['Node'] name: str ambassador_id: str namespace: str is_ambassador = False xfail: Optional[str] def __init__(self, *args, name: Optional[str]=None, namespace: Optional[str]=None, _clone: Optional['Node']=None, **kwargs) -> None: ...
def get_images(html, url): if ('This post was deleted' in html): raise SkipEpisodeError(always=True) login_check(html) result = '' if (match := re.search('<a [^>]*highres[^>]*>', html)): result = re.search('href="([^"]+)"', match.group(0)).group(1) elif (match := re.search('embed src...
class CreateTemplateParamSource(ABC, ParamSource): def __init__(self, track, params, templates, **kwargs): super().__init__(track, params, **kwargs) self.request_params = params.get('request-params', {}) self.template_definitions = [] if (('template' in params) and ('body' in params)...