code
stringlengths
281
23.7M
def gen_x10(targ_house, targ_unit, targ_cmd): res = [0, 0] if _debug: print(targ_house, targ_unit, targ_cmd, file=sys.stderr) res[0] = houseCodes[targ_house] if (targ_unit and (not (cmd_code[targ_cmd] & 128))): res[0] |= ((unit_code[targ_unit] >> 8) & 255) res[1] |= (unit_code[ta...
class TreeNodeAdminTestCase(TestCase): def setUp(self): pass def tearDown(self): pass def assertStaticFile(self, path): result = finders.find(path) self.assertTrue((result is not None)) def test_staticfiles(self): if ('treenode' not in settings.INSTALLED_APPS): ...
def validateExamples(examples, schemas, maxExamples, shuffle): failures = [] numberOfSuccessfulValidations = 0 unchecked = [] numChecked = 0 latestReportTime = time.perf_counter() if shuffle: random.shuffle(examples) for (path, type, version, id, event) in examples: schemaKey...
(config_path='../cfgs/', config_name='default_test') def test_fn(cfg: DictConfig): OmegaConf.set_struct(cfg, False) accelerator = Accelerator(even_batches=False, device_placement=False) accelerator.print('Model Config:', OmegaConf.to_yaml(cfg), accelerator.state) torch.backends.cudnn.benchmark = (cfg.te...
class ModelSerializer(Serializer): _options_class = ModelSerializerOptions field_mapping = {models.AutoField: IntegerField, models.FloatField: FloatField, models.IntegerField: IntegerField, models.PositiveIntegerField: IntegerField, models.SmallIntegerField: IntegerField, models.PositiveSmallIntegerField: Integ...
class InputText(JsHtml.JsHtmlRich): def isEmpty(self, js_funcs: types.JS_FUNCS_TYPES): if (not isinstance(js_funcs, list)): js_funcs = [js_funcs] return JsIf.JsIf(('%s === ""' % self.component.dom.content.toStr()), js_funcs) def hasLength(self, n: int, js_funcs: types.JS_FUNCS_TYPES)...
def upgrade(): op.execute('alter type connectiontype rename to connectiontype_old') op.execute("create type connectiontype as enum('postgres', 'mongodb', 'mysql', ' 'snowflake', 'redshift', 'mssql', 'mariadb', 'bigquery', 'saas', 'manual', 'manual_webhook', 'timescale', 'fides', 'sovrn', 'attentive', 'dynamodb'...
def only_wire(tile1, tile2, tiles, x_wires, y_wires): tile1_info = tiles[tile1] tile2_info = tiles[tile2] tile1_x = tile1_info['grid_x'] tile2_x = tile2_info['grid_x'] tiles_x_adjacent = (abs((tile1_x - tile2_x)) == 1) if (tiles_x_adjacent and (len(x_wires[tile1_x]) == 1) and (len(x_wires[tile2_...
class Waters(): def make_molsetup_OPC(): raise NotImplementedError rdmol = Chem.MolFromSmiles('O') conformer = Chem.Conformer(rdmol.GetNumAtoms()) conformer.SetAtomPosition(0, Point3D(0, 0, 0)) rdmol.AddConformer(conformer) molsetup = RDKitMoleculeSetup(rdmol) ...
class Game(): def __init__(self, platform: Platforms, region: Regions, title: str, nsuid: str=None, product_code: str=None): self.platform: Platforms = platform self.region: Regions = region self.title: str = title self.nsuid: str = nsuid self.product_code: str = product_code...
.asyncio .workspace_host class TestDeleteRole(): async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData): role = test_data['roles']['castles_visitor'] response = (await test_client_api.delete(f'/roles/{role.id}')) unauthor...
class State(): def __init__(self, i3): self.context: Optional[Context] = None self.workspace_sequences: Dict[(str, WorkspaceSequence)] = {} self.rebuild_action = RebuildAction() self.old_workspace_name = '' self.sync_context(i3) for workspace in i3.get_workspaces(): ...
def callback_query(args: str, payload=True): async def func(ftl, __, query: CallbackQuery): if payload: thing = '{}\\_' if re.search(re.compile(thing.format(ftl.data)), query.data): search = re.search(re.compile('\\_{1}(.*)'), query.data) if search: ...
class For_Loop_Statement(Compound_Statement): def __init__(self, t_for): super().__init__() assert isinstance(t_for, MATLAB_Token) assert ((t_for.kind == 'KEYWORD') and (t_for.value in ('for', 'parfor'))) self.t_for = t_for self.t_for.set_ast(self) self.n_ident = None...
class OptionSeriesWordcloudSonificationContexttracksMappingRate(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_when_field_can_be_merged_with_casts(): cfg = ControlFlowGraph() r32 = [Variable('reg', unsigned_int, i) for i in range(10)] r64 = [Variable('reg', unsigned_long, i) for i in range(10)] int_var = Variable('int_var', signed_int, 0) char_var = Variable('char_var', signed_char, 0) instructi...
_invites_misc_routes.route('/role_invites/accept-invite', methods=['POST']) def accept_invite(): token = request.json['data']['token'] try: role_invite = RoleInvite.query.filter_by(hash=token).one() except NoResultFound: raise NotFoundError({'source': ''}, 'Role Invite Not Found') else: ...
def Check_DeleteConfigWrite(proc, stmts): assert (len(stmts) > 0) ctxt = ContextExtraction(proc, stmts) p = ctxt.get_control_predicate() G = ctxt.get_pre_globenv() ap = ctxt.get_posteffs() a = G(stmts_effs(stmts)) stmtsG = globenv(stmts) slv = SMTSolver(verbose=False) slv.push() ...
def recognize_ngram(tokens: List[str], gazetteer: Dict[(str, Set[str])]) -> List[Tuple[(int, int, str, Set[str])]]: entities = [] for i in range(len(tokens)): for j in range((i + 1), (len(tokens) + 1)): key = ' '.join(tokens[i:j]) val = gazetteer.get(key, None) if val...
def extractCreamSavers(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=...
class AttributeHandler(): _attrcreate = 'attrcreate' _attredit = 'attredit' _attrread = 'attrread' _attrtype = None def __init__(self, obj, backend_class): self.obj = obj self.backend = backend_class(self, self._attrtype) def has(self, key=None, category=None): ret = [] ...
def parse_link(link): namespace = link.split('/')[(- 2)] print('Parsing {} link: {}'.format(namespace, link)) response = requests.get((base_url + link)) table_attr = SoupStrainer('table') soup = BeautifulSoup(response.content, 'lxml', parse_only=table_attr) table = soup.find('table') if (not...
class OptionPlotoptionsSeriesSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsSeriesSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsSeriesSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def ...
def exp(dtype): if dtypes.is_integer(dtype): raise NotImplementedError((('exp() of ' + str(dtype)) + ' is not supported')) if dtypes.is_real(dtype): polar_unit_ = None else: polar_unit_ = polar_unit(dtypes.real_for(dtype)) return Module(TEMPLATE.get_def('exp'), render_kwds=dict(d...
def get_sns_subscriptions(app_name, env, region): session = boto3.Session(profile_name=env, region_name=region) sns_client = session.client('sns') lambda_alias_arn = get_lambda_alias_arn(app=app_name, account=env, region=region) lambda_subscriptions = [] subscriptions = sns_client.list_subscriptions...
def huggingface_tokenize(tokenizer, texts: List[str]) -> BatchEncoding: warnings.warn('spacy_transformers.util.huggingface_tokenize has been moved to spacy_transformers.layers.transformer_model.huggingface_tokenize.', DeprecationWarning) token_data = tokenizer(texts, add_special_tokens=True, return_attention_ma...
class TestFigureTeiElementFactory(): def test_should_render_label_description_and_id(self): semantic_figure = SemanticFigure([SemanticLabel(layout_block=LayoutBlock.for_text('Label 1')), SemanticCaption(layout_block=LayoutBlock.for_text('Caption 1'))], content_id='fig_0') result = _get_wrapped_figur...
class Solution(): def read(self, buf, n): cnt = 0 tmp = ([''] * 4) while (cnt < n): curr = read4(tmp) i = 0 while ((i < curr) and (cnt < n)): buf[cnt] = tmp[i] i += 1 cnt += 1 if (curr < 4): ...
class SagemakerBuiltinAlgorithmsTask(PythonTask[SagemakerTrainingJobConfig]): _SAGEMAKER_TRAINING_JOB_TASK = 'sagemaker_training_job_task' OUTPUT_TYPE = Annotated[(str, FileExt('tar.gz'))] def __init__(self, name: str, task_config: SagemakerTrainingJobConfig, **kwargs): if ((task_config is None) or ...
class SlatWallEdge(WallEdge): def lengths(self, length): pitch = self.settings.pitch h = self.settings.hook_height he = self.settings.hook_extra_height lengths = [] if (length < (h + he)): return [length] lengths = [0, (h + he)] length -= (h + he) ...
def __getattr__(name): if (name in {'marker_trait'}): from warnings import warn import enable.api warn(f'Please import {name} from enable.api instead of chaco.api.', DeprecationWarning) return getattr(enable.api, name) raise AttributeError(f'module {__name__!r} has no attribute {...
class OptionSeriesVectorClusterZonesMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get(None) def fillColor(self, text: str): self._config(text, js_...
def test_simple_plot_with_seismics(tmpdir, show_plot, generate_plot): mywell = xtgeo.well_from_file(USEFILE7) mycube = xtgeo.cube_from_file(USEFILE6) mysurfaces = [] mysurf = xtgeo.surface_from_file(USEFILE2) for i in range(10): xsurf = mysurf.copy() xsurf.values = (xsurf.values + (i...
class BasePolicyComposer(ABC): def __init__(self, action_spaces_dict: Dict[(StepKeyType, spaces.Dict)], observation_spaces_dict: Dict[(StepKeyType, spaces.Dict)], agent_counts_dict: Dict[(StepKeyType, int)], distribution_mapper: DistributionMapper): self._action_spaces_dict = action_spaces_dict self...
def test_local_raw_fsspec(source_folder): with tempfile.TemporaryDirectory() as dest_tmpdir: local.put(source_folder, dest_tmpdir, recursive=True) new_temp_dir_2 = tempfile.mkdtemp() new_temp_dir_2 = os.path.join(new_temp_dir_2, 'doesnotexist') local.put(source_folder, new_temp_dir_2, recursive=...
class TestComposerThread_perform_gating(ComposerThreadBaseTestCase): def test_expires_compose_updates(self): config['test_gating.required'] = True task = self._make_task() t = ComposerThread(self.semmock, task['composes'][0], 'bowlofeggs', self.Session, self.tempdir) t.compose = Comp...
.parametrize('pt,on_curve,is_infinity', [(G2, True, False), (multiply(G2, 5), True, False), (Z2, True, True), ((FQ2([5566, 5566]), FQ2([5566, 5566]), FQ2.one()), False, None)]) def test_G2_compress_and_decompress_flags(pt, on_curve, is_infinity): if on_curve: (z1, z2) = compress_G2(pt) x1 = (z1 % PO...
class TestRefAddrOnDWARFv2With64BitTarget(unittest.TestCase): def test_main(self): with open(os.path.join('test', 'testfiles_for_unittests', 'arm64_on_dwarfv2.info.dat'), 'rb') as f: info = f.read() with open(os.path.join('test', 'testfiles_for_unittests', 'arm64_on_dwarfv2.abbrev.dat'),...
def acquire_episodes(buffer, env, agent, env_info, agent_info): flag = True slots = None (observation, env_running) = env.reset(env_info) slots = [[] for k in range(env.n_envs())] t = 0 agent_state = None while True: (env_to_slots, agent_state, observation, agent_info, env_running) =...
def test_unregister_unknown_lookups(registry: ABIRegistry): with pytest.raises(KeyError, match='Matcher .* not found in encoder registry'): registry.unregister((lambda x: x)) with pytest.raises(KeyError, match='Label .* not found in encoder registry'): registry.unregister('foo')
def extractPenumbrale(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=p...
_ordering class SemanticVersion(Version): name = 'Semantic' def prerelease(self): try: version_info = semver.VersionInfo.parse(self.parse()) except ValueError: return False if version_info.prerelease: return True for pre_release_filter in self....
class BuildrootOverride(Base): __tablename__ = 'buildroot_overrides' __include_extras__ = ('nvr',) __get_by__ = ('build_id',) notes = Column(UnicodeText, nullable=False) submission_date = Column(DateTime, default=datetime.utcnow, nullable=False) expiration_date = Column(DateTime, nullable=False)...
def test_global_ptr_addr(): base_args = ['python', 'decompile.py', 'tests/samples/bin/systemtests/64/0/globals'] args1 = (base_args + ['global_addr_ptr_add']) output = str(subprocess.run(args1, check=True, capture_output=True).stdout) assert (output.count('e = 0x17') == 1) assert (output.count('f = ...
('overrides,output', [([], 'MySQL connecting to localhost'), (['db=postgresql'], 'PostgreSQL connecting to localhost')]) def test_instantiate_schema(tmpdir: Path, overrides: List[str], output: str) -> None: cmd = (['examples/instantiate/schema/my_app.py', ('hydra.run.dir=' + str(tmpdir)), 'hydra.job.chdir=True'] + ...
def test_cli_path_or_dash(): cli = Radicli() file_name = 'my_file.txt' ran1 = False ran2 = False ('test1', a=Arg()) def test1(a: ExistingFilePathOrDash): assert (str(a) == str(file_path)) nonlocal ran1 ran1 = True ('test2', a=Arg()) def test2(a: ExistingFilePathOr...
def get_time_steps_str(time_steps) -> str: if (time_steps < 1000): time_steps_str = f'{time_steps}' elif (1000 <= time_steps < (1000 * 1000)): time_steps_str = f'{(time_steps / 1000)}K' else: time_steps_str = f'{((time_steps / 1000) / 1000)}M' return time_steps_str
class TorchSharedStateActionCritic(TorchStateActionCritic): (TorchStateActionCritic) def predict_q_values(self, observations: Dict[(Union[(str, int)], Dict[(str, torch.Tensor)])], actions: Dict[(Union[(str, int)], Dict[(str, torch.Tensor)])], gather_output: bool) -> Dict[(Union[(str, int)], List[Union[(torch.Te...
class Discord(): def __init__(self): self.baseurl = ' self.appdata = os.getenv('localappdata') self.roaming = os.getenv('appdata') self.regex = '[\\w-]{24}\\.[\\w-]{6}\\.[\\w-]{25,110}' self.encrypted_regex = 'dQw4w9WgXcQ:[^\\"]*' self.tokens_sent = [] self.to...
class SilhouetteCameoTool(): def __init__(self, toolholder=1): if (toolholder is None): toolholder = 1 self.toolholder = toolholder def select(self): return ('J%d' % self.toolholder) def pressure(self, pressure): return ('FX%d,%d' % (pressure, self.toolholder)) ...
def fetch_event_invoices(invoice_status): if (invoice_status == 'due'): event_invoices = EventInvoice.query.filter(((EventInvoice.created_at + datetime.timedelta(days=30)) <= datetime.datetime.now()), (EventInvoice.paid_via is None)).all() elif (invoice_status == 'paid'): event_invoices = EventI...
class Changes(object): authors = {} authors_dateinfo = {} authors_by_email = {} emails_by_author = {} def __init__(self, repo, hard): self.commits = [] interval.set_ref('HEAD') git_rev_list_p = subprocess.Popen(filter(None, ['git', 'rev-list', '--reverse', '--no-merges', inte...
def average(create: type[Color], colors: Iterable[ColorInput], space: str, premultiplied: bool=True, powerless: bool=False) -> Color: obj = create(space, []) cs = obj.CS_MAP[space] hue_index = (cs.hue_index() if hasattr(cs, 'hue_index') else (- 1)) channels = cs.channels chan_count = len(channels) ...
class LeDevicesScanResult(ScanResult): def __init__(self) -> None: super().__init__('LE Devices') self.devices_info = [] def add_device_info(self, info: LeDeviceInfo): self.devices_info.append(info) def print(self): for dev_info in self.devices_info: print('Addr: ...
class Taichi(TreatAs, Skill): skill_category = ['character', 'active'] def treat_as(self): cl = self.associated_cards if (not cl): return DummyCard c = cl[0] if c.is_card(GrazeCard): return AttackCard if c.is_card(AttackCard): return Gr...
def write_final_vcf(int_duplication_candidates, inversion_candidates, tandem_duplication_candidates, deletion_candidates, novel_insertion_candidates, breakend_candidates, version, contig_names, contig_lengths, types_to_output, options): vcf_output = open((options.working_dir + '/variants.vcf'), 'w') print('##fi...
class qwEditMask(QtWidgets.QWidget): valueChanged = pyqtSignal(int) def __init__(self, parent=None): super().__init__(parent) self.__changeEnCours = False self.__nbAxes = 6 self.frame = QtWidgets.QFrame() self.frame.setMinimumSize(QtCore.QSize(127, 19)) self.frame...
def test_extract_specified_datetime_features(df_datetime, df_datetime_transformed): X = DatetimeFeatures(features_to_extract=['semester', 'week']).fit_transform(df_datetime) pd.testing.assert_frame_equal(X, df_datetime_transformed[(vars_non_dt + [((var + '_') + feat) for var in vars_dt for feat in ['semester', ...
def gen_sites(desired_site_type): db = Database(util.get_db_root(), util.get_part()) grid = db.grid() for tile_name in sorted(grid.tiles()): loc = grid.loc_of_tilename(tile_name) gridinfo = grid.gridinfo_at_loc(loc) for (site, site_type) in gridinfo.sites.items(): if (sit...
class ABI(): def __init__(self, *args, **kwargs): self.contract = kwargs['contract'] self.proj_path = kwargs['proj_path'] self.constructor = Method(**kwargs['Constructor']) self.payable = kwargs['payable'] self.methods = [Method(**method) for method in kwargs['Methods'].value...
class FlicketPost(PaginatedAPIMixin, Base): __tablename__ = 'flicket_post' id = db.Column(db.Integer, primary_key=True) ticket_id = db.Column(db.Integer, db.ForeignKey(FlicketTicket.id)) ticket = db.relationship(FlicketTicket, back_populates='posts') content = db.Column(db.String(field_size['content...
class Client(UMsgPacker): def __init__(self, host, port, connection_handler_class=None): if DEBUG: sys.stderr.write(('Connecting to server at: %s (%s)\n' % (host, port))) self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect((host, port)) if co...
class Param(): def __init__(self, defs): self._defs = defs self._type = None if ((self.type.values == [False, True]) or (self.type.values == [True, False])): self._type = Bool(self) def name(self): return self._defs.get('name') def documentation(self): ret...
class Migration(migrations.Migration): dependencies = [('frontend', '0075_auto__2012')] operations = [migrations.CreateModel(name='STP', fields=[('code', models.CharField(max_length=3, primary_key=True, serialize=False)), ('name', models.CharField(blank=True, max_length=200, null=True)), ('regional_team', model...
def _migrate_summary_info(data_file: DataFile, ens_config: EnsembleConfig) -> List[ResponseConfig]: seen = set() for block in data_file.blocks(Kind.SUMMARY): if (block.name in seen): continue seen.add(block.name) return ([ens_config['summary']] if seen else [])
def info_aubio(fp): info = {} with aubio.source(fp) as f: info['duration'] = (f.duration / f.samplerate) with aubio.source(fp) as f: info['samples'] = f.duration with aubio.source(fp) as f: info['channels'] = f.channels with aubio.source(fp) as f: info['sampling_rate'...
_renderer(wrap_type=ClassificationProbDistribution) class ClassificationProbDistributionRenderer(MetricRenderer): def _plot(self, distribution: Dict[(str, list)]): graphs = [] for label in distribution: pred_distr = ff.create_distplot(distribution[label], [str(label), 'other'], colors=[s...
def get_basemesh_nodes(W): (pstart, pend) = W.mesh().topology_dm.getChart() section = W.dm.getDefaultSection() basemeshoff = numpy.empty((pend - pstart), dtype=IntType) basemeshdof = numpy.empty((pend - pstart), dtype=IntType) basemeshlayeroffset = numpy.empty((pend - pstart), dtype=IntType) lay...
def test_A_fails_with_incorrect_dict(): correct_d = {'terms': {'field': 'tags'}, 'aggs': {'per_author': {'terms': {'field': 'author.raw'}}}} with raises(Exception): aggs.A(correct_d, field='f') d = correct_d.copy() del d['terms'] with raises(Exception): aggs.A(d) d = correct_d.co...
def arm_infer_functions(functions): if functions.binary.sections.has_sec(INIT): init_sec_addr = functions.binary.sections.get_sec(INIT).addr if functions.is_lowpc_function(init_sec_addr): _init = functions.get_function_by_lowpc(init_sec_addr) _init.name = '_init' ...
class _ScheduleModel(models.Model): PT = PeriodicTask _active = None _schedule = None periodic_task = models.ForeignKey(PT, null=True, blank=True) class Meta(): app_label = 'vms' abstract = True def _new_periodic_task(self): return NotImplemented def _save_crontab(sel...
class UserLeadGenDisclaimerResponse(AbstractObject): def __init__(self, api=None): super(UserLeadGenDisclaimerResponse, self).__init__() self._isUserLeadGenDisclaimerResponse = True self._api = api class Field(AbstractObject.Field): checkbox_key = 'checkbox_key' is_checke...
class PreconditioningProgram(object): swagger_types = {} attribute_map = {} def __init__(self): self.discriminator = None def to_dict(self): result = {} for (attr, _) in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, li...
class OptionSeriesNetworkgraphSonificationContexttracksMappingGapbetweennotes(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 walk(st, lex, rule=None): (tok, children) = st if (tok == pgen.PgenParser.RULE): rule = children[0][0] nodes.add(rule) for child in children[1:]: walk(child, lex, rule) elif (isinstance(tok, str) and tok.strip() and (tok[0] in string.ascii_lowercase)): nodes.a...
class RawType(BaseType): def __init__(self, cstruct, name=None, size=0): self.name = name self.size = size super().__init__(cstruct) def __len__(self): return self.size def __repr__(self): if self.name: return self.name return BaseType.__repr__(sel...
class OptionSeriesColumnpyramidSonification(Options): def contextTracks(self) -> 'OptionSeriesColumnpyramidSonificationContexttracks': return self._config_sub_data('contextTracks', OptionSeriesColumnpyramidSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionSeriesColumnpyramidSonific...
() def graph_no_dependency(variable_x, variable_u, variable_v, aliased_variable_y, variable_x_new, variable_u_new, variable_v_new, aliased_variable_y_new) -> Tuple[(List[BasicBlock], List[Instruction], ControlFlowGraph)]: instructions = [Assignment(ListOperation([]), Call(imp_function_symbol('printf'), [Constant()]...
_required _required _required(ImageAdminPermission) _required(ImageImportAdminPermission) def imagestore_list(request, repo=None): user = request.user context = collect_view_data(request, 'dc_image_list') context['image_vm'] = ImageVm.get_uuid() context['is_staff'] = is_staff = user.is_staff context...
(name=MAX_PATH_EXT_RTFILTER_ALL) def validate_max_path_ext_rtfilter_all(max_path_ext_rtfilter_all): if (not isinstance(max_path_ext_rtfilter_all, bool)): raise ConfigTypeError(desc=('Invalid max_path_ext_rtfilter_all configuration value %s' % max_path_ext_rtfilter_all)) return max_path_ext_rtfilter_all
class OptionPlotoptionsPyramid3dSonificationContexttracksPointgrouping(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)...
def resample_to_native(native_mesh, dest_mesh, settings, subject_id, sphere, expected_labels, reg_sphere_mesh): copy_sphere_mesh_from_template(settings, dest_mesh) resample_surfs_and_add_to_spec(subject_id, native_mesh, dest_mesh, current_sphere=sphere, current_sphere_mesh=reg_sphere_mesh) make_inflated_sur...
class TestEnabledApisScannerTest(): .e2e .scanner .server .skip(reason='Flaky test, sometimes no violation is found.') def test_enabled_apis_scanner(self, cloudsql_connection, forseti_scan_readonly, project_id): (scanner_id, scanner_result) = forseti_scan_readonly violation_type = 'E...
class TestAction(ActionBase): def ban(self, aInfo): self._logSys.info('ban ainfo %s, %s, %s, %s', (aInfo['ipmatches'] != ''), (aInfo['ipjailmatches'] != ''), (aInfo['ipfailures'] > 0), (aInfo['ipjailfailures'] > 0)) self._logSys.info('jail info %d, %d, %d, %d', aInfo['jail.banned'], aInfo['jail.bann...
def calc_clip_factor(clipping_value: float, norm: float) -> float: if ((clipping_value < 0) or (norm < 0)): raise ValueError('Error: max_norm and per_user_norm must be both positive.') clip_factor = (clipping_value / (norm + __EPS__)) clip_factor = min(clip_factor, 1.0) return clip_factor
def get_numeric_gradient(predict, n, target): gradient = numpy.zeros(n) for i in range(n): out1 = predict(i, 0.0001) out2 = predict(i, (- 0.0001)) err1 = _get_loss(out1, target) err2 = _get_loss(out2, target) gradient[i] = ((err1 - err2) / (2 * 0.0001)) print('NGr...
('rocm.bert_embeddings.gen_function') def bert_embeddings_gen_function(func_attrs: Dict[(str, Any)]) -> str: backend_spec = ROCMSpec() elem_input_type = backend_spec.dtype_to_lib_type(func_attrs['inputs'][3]._attrs['dtype']) (input_ids, token_type_ids, position_ids, word_embeddings, token_type_embeddings, p...
def test_airflow_dag_get_tasks(airflow_api_tree): dag_id = 'test_dag' airflow_api_tree.dag_api.get_tasks.return_value = dict(tasks=[dict(class_ref=dict(module_path='test_module', class_name='test_class'), task_id='test_task_1', downstream_task_ids=[], group_name=None), dict(class_ref=dict(module_path='test_modu...
class AccessManualWebhook(Base): connection_config_id = Column(String, ForeignKey(ConnectionConfig.id_field_path), unique=True, nullable=False) connection_config = relationship(ConnectionConfig, back_populates='access_manual_webhook', uselist=False) fields = Column(MutableList.as_mutable(JSONB), nullable=Fa...
def _patch_attribute(member: Any, name: str, marker: '_Marker', providers_map: ProvidersMap) -> None: provider = providers_map.resolve_provider(marker.provider, marker.modifier) if (provider is None): return _patched_registry.register_attribute(PatchedAttribute(member, name, marker)) if isinstan...
class UnaryOp(expr): _fields = ('op', 'operand') _attributes = ('lineno', 'col_offset') def __init__(self, op, operand, lineno=0, col_offset=0, **ARGS): expr.__init__(self, **ARGS) self.op = op self.operand = operand self.lineno = int(lineno) self.col_offset = int(col...
class KNNRecommender(object): def __init__(self, k=3, **kwargs): self.k = k self.pipeline = Pipeline([('norm', TextNormalizer(minimum=10, maximum=100)), ('tfidf', TfidfVectorizer()), ('knn', Pipeline([('svd', TruncatedSVD(n_components=100)), ('model', KNNTransformer(k=self.k, algorithm='ball_tree'))...
class CatchUserErrorTest(TestCase): _user_error() def throwsUserError(self): raise UserError def testCatchesUserError(self) -> None: try: self.throwsUserError() except UserError: self.fail('Unexpected UserError') _user_error() def throwsException(self)...
class KeyboardButton(Dictionaryable, JsonSerializable): def __init__(self, text: str, request_contact: Optional[bool]=None, request_location: Optional[bool]=None, request_poll: Optional[KeyboardButtonPollType]=None, web_app: Optional[WebAppInfo]=None, request_user: Optional[KeyboardButtonRequestUser]=None, request_...
class S2DMA(Module): def __init__(self, data_width, adr_width, address=0): self.sink = sink = stream.Endpoint([('data', 8)]) self.source = source = stream.Endpoint([('address', adr_width), ('data', data_width)]) addr = Signal(adr_width, reset=address) self.comb += [source.data.eq(sin...
class LiteEthEtherboneWishboneMaster(LiteXModule): def __init__(self): self.sink = sink = stream.Endpoint(eth_etherbone_mmap_description(32)) self.source = source = stream.Endpoint(eth_etherbone_mmap_description(32)) self.bus = bus = wishbone.Interface() data_update = Signal() ...
class DclibOpenAiModel(DcModel): def __init__(self, model, tokenizer, endpoint=None, **kwargs): super().__init__(model, tokenizer, truncation_threshold=(- 12000), init_workers=False, **kwargs) self.mock = kwargs.get('mock', False) self.output_writer = None if ('output_writer' in kwar...
class Executor(): def __init__(self, loop): self.loop = loop loop.pyi.executor = self self.queue = loop.queue_request self.i = 0 self.bridge = self.loop.pyi def ipc(self, action, ffid, attr, args=None): self.i += 1 r = self.i l = None if (a...
class LegalFlagMessage(Message): def __init__(self, copr, reporter, reason): self.subject = 'Legal flag raised on {0}'.format(copr.name) self.text = '{0}\nNavigate to {1}\nContact on owner is: {2} <{3}>\nReported by {4} <{5}>'.format(reason, flask.url_for('admin_ns.legal_flag', _external=True), copr...
def test_dc_dyn_directory(folders_and_files_setup): proxy_c = MyProxyConfiguration(splat_data_dir='/tmp/proxy_splat', apriori_file='/opt/config/a_file') proxy_p = MyProxyParameters(id='pp_id', job_i_step=1) my_input_gcs = MyInput(main_product=FlyteFile(folders_and_files_setup[0]), apriori_config=MyAprioriCo...