code
stringlengths
281
23.7M
def test_adding_a_extra_volume_with_volume_mount(): config = '\nextraVolumes: |\n - name: extras\n emptyDir: {}\nextraVolumeMounts: |\n - name: extras\n mountPath: /usr/share/extras\n readOnly: true\n' r = helm_template(config) extraVolume = r['statefulset'][name]['spec']['template']['spec']['vol...
class Migration(migrations.Migration): dependencies = [('frontend', '0021_chemical_is_current')] operations = [migrations.AddField(model_name='product', name='is_current', field=models.BooleanField(default=True)), migrations.AddField(model_name='section', name='is_current', field=models.BooleanField(default=Tru...
class GetForObjectReferenceDbTest(TestModelMixin, TestBase): databases = {'default', 'postgres'} def testGetForObjectReferenceModelDb(self): with reversion.create_revision(using='postgres'): obj = TestModel.objects.create() self.assertEqual(Version.objects.get_for_object_reference(Te...
def extractLuciferscansWordpressCom(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...
def get_all_pipelines(app=''): uri = '/applications/{app}/pipelineConfigs'.format(app=app) response = gate_request(uri=uri) assert response.ok, 'Could not retrieve Pipelines for {0}.'.format(app) pipelines = response.json() LOG.debug('Pipelines:\n%s', pipelines) return pipelines
.parametrize('api_style', ('v4', 'build_filter')) def test_event_filter_new_events_many_deployed_contracts(w3, emitter, emitter_contract_factory, wait_for_transaction, emitter_contract_event_ids, api_style, create_filter): matching_transact = emitter.functions.logNoArgs(which=1).transact deployed_contract_addre...
class OptionSeriesPictorial(Options): def accessibility(self) -> 'OptionSeriesPictorialAccessibility': return self._config_sub_data('accessibility', OptionSeriesPictorialAccessibility) def allowPointSelect(self): return self._config_get(False) def allowPointSelect(self, flag: bool): ...
def build_hyperparameter_optimizer(hyperparameters={}, cv=10, n_iter=100, n_jobs=(- 1), verbose=1): search = sklearn.model_selection.RandomizedSearchCV(RandomForestClassifier(n_jobs=1), param_distributions=hyperparameters, scoring={'accuracy': sklearn.metrics.make_scorer(sklearn.metrics.accuracy_score), 'size': mod...
def aggregate_output_types(cell_outputs: List[NotebookNode]) -> CELL_OUTPUTS_TO_PROCESS: (prioritized_cell_output_dtypes, plotly_flags) = prioritize_dtypes(cell_outputs) cell_outputs_to_process = {'bokeh': [], 'image': [], 'markdown': [], 'pandas': [], 'plain': [], 'plotly': [], 'tqdm': []} for (i, cell_out...
def test_medium2d(log_capture): sigma = 0.45 thickness = 0.01 cond_med = td.Medium(conductivity=sigma) medium = td.Medium2D.from_medium(cond_med, thickness=thickness) _ = medium.plot_sigma(freqs=[.0, .0], ax=AX) plt.close() assert np.isclose(medium.ss.to_medium().conductivity, (sigma * thick...
def extractJaptem(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('[Chinese] Shadow Rogue' in item['tags']): return buildReleaseMessageWithType(item, 'Shadow Rogue', vol, chp, ...
class OptionSeriesXrangeSonificationTracksMappingTime(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._conf...
def extractMeanderingotakuWordpressCom(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, fra...
def _make_tcp_client_connection(address: str, public_key: str, host: str, port: int): configuration = ConnectionConfig(address=host, port=port, connection_id=TCPClientConnection.connection_id) tcp_connection = TCPClientConnection(configuration=configuration, data_dir=MagicMock(), identity=Identity('name', addre...
def test_intra_function(): cfg = ControlFlowGraph() cfg.add_node((node := BasicBlock(0, instructions=[Assignment(Variable('a'), Call(imp_function_symbol('foo'), [expr1, expr1, expr1])), Branch(Condition(OperationType.equal, [expr1, Constant(1)]))]))) _run_cse(cfg, _generate_options(intra=False)) assert ...
class TestInstanceEditorDemo(unittest.TestCase): def test_instance_editor_demo(self): demo = runpy.run_path(DEMO_PATH)['demo'] tester = UITester() with tester.create_ui(demo) as ui: simple = tester.find_by_id(ui, 'simple') custom = tester.find_by_id(ui, 'custom') ...
def taplog_callback(frame, bp_loc, internal_dict): parameterExpr = objc.functionPreambleExpressionForObjectParameterAtIndex(0) print('Gesture Recognizers:\n{}'.format(fb.describeObject(('[[[%s allTouches] anyObject] gestureRecognizers]' % parameterExpr)))) print('View:\n{}'.format(fb.describeObject(('[[[%s ...
('overrides', ['hydra.launcher.batch_size=1', 'hydra.launcher.max_nbytes=10000', 'hydra.launcher.max_nbytes=1M', 'hydra.launcher.pre_dispatch=all', 'hydra.launcher.pre_dispatch=10', 'hydra.launcher.pre_dispatch=3*n_jobs']) def test_example_app_launcher_overrides(hydra_sweep_runner: TSweepRunner, overrides: str) -> None...
class CirnoAI(object): def __init__(self, trans, ilet): self.trans = trans self.ilet = ilet def entry(self): ilet = self.ilet trans = self.trans p = ilet.actor g = trans.game g.pause(1.2) if (trans.name == 'ActionStageAction'): tl = g.p...
def test_raises(): with pytest.raises(TypeError): alert.new('foo') assert (len(alert.show()) == 0) with pytest.raises(ValueError): alert.new(time.time, repeat=(- 1)) assert (len(alert.show()) == 0) with pytest.raises(TypeError): alert.new(time.time, args=('potato',)) asse...
def read_utf16(io, size=(- 1)): raw = b'' i = 0 while ((size == (- 1)) or (i < size)): wchar = io.read(2) i += 2 if ((wchar == b'') or (wchar == b'\x00\x00')): break raw += wchar if (i < size): io.seek((size - i), 1) return raw.decode('UTF-16le', '...
class CsssDivBoxMarginBorder(CssStyle.Style): _attrs = {'margin': 0, 'padding': '0 2px 0 2px', 'white-space': 'pre-wrap'} def customize(self): self.css({'border': ('1px solid %s' % self.page.theme.greys[0]), 'font-family': self.page.body.style.globals.font.family}) self.hover.css({'border': ('1p...
class Logger(): def __init__(self, name=None, file=sys.stderr): debug = os.getenv('DEBUG', '') if (debug and name.endswith(debug)): func = self.stderr else: func = self.null self.d = func self.i = func self.w = self.stderr self.e = self...
class WeathercomHTMLParser(HTMLParser): user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:80.0) Gecko/ Firefox/80.0' def __init__(self, logger): self.logger = logger super(WeathercomHTMLParser, self).__init__() def get_weather_data(self, url): self.logger.debug(f'Making request to {ur...
class RangeFacet(Facet): agg_type = 'range' def _range_to_dict(self, range): (key, range) = range out = {'key': key} if (range[0] is not None): out['from'] = range[0] if (range[1] is not None): out['to'] = range[1] return out def __init__(self,...
class CollectionStripArtistPreference(widgets.ListPreference): default = _get_default_strip_list() name = 'collection/strip_list' def __init__(self, preferences, widget): widgets.ListPreference.__init__(self, preferences, widget) self.widget.connect('populate-popup', self._populate_popup_cb)...
def test_scalar_expression(f): xs = SpatialCoordinate(f.function_space().mesh()) f.interpolate(xs[1]) assert (abs((assemble((f * ds_t)) - 1.0)) < 1e-07) assert (abs((assemble((f * ds_b)) - 0.0)) < 1e-07) assert (abs((assemble((f * ds_tb)) - 1.0)) < 1e-07) assert (abs((assemble((f * ds_v)) - 1.0)...
class QueryRewriteParser(BaseOutputParser): def __init__(self, is_stream_out: bool, **kwargs): super().__init__(is_stream_out=is_stream_out, **kwargs) def parse_prompt_response(self, response, max_length: int=128): lowercase = True try: results = [] response = res...
('/javbus') def javbus(): if (not ('base' in javbusurl.raw_dict())): javbusurl['base'] = ' getjavbusurl() if (not url_is_alive(javbusurl['base'])): notify(', ') getjavbusurl() item = [{'label': '', 'path': plugin.url_for('javlist', qbbb='qb', filtertype='0', filterkey='0', pa...
def zone_bounding_boxes(zones_config: dict[(ZoneKey, Any)]) -> dict[(ZoneKey, BoundingBox)]: bounding_boxes = {} for (zone_id, zone_config) in zones_config.items(): if ('bounding_box' in zone_config): bounding_boxes[zone_id] = zone_config['bounding_box'] return bounding_boxes
def get_builder(uifile: str) -> Gtk.Builder: builder = Gtk.Builder() if (sys.platform == 'win32'): with open(uifile, 'rb') as fp: template = fp.read() template_string = get_template_translated(template) builder.add_from_string(template_string) else: builde...
class MeeJeeFetch(PreemptProcessorBase.PreemptProcessorBase): log_name = 'Main.Processor.MeeJee' def preemptive_wants_url(lowerspliturl: tuple): return lowerspliturl.netloc.endswith('meejee.net') def premptive_handle_content(self, url): wrapper_step_through_timeout = 60 loading_str =...
class ScopedRateThrottle(SimpleRateThrottle): scope_attr = 'throttle_scope' def __init__(self): pass def allow_request(self, request, view): self.scope = getattr(view, self.scope_attr, None) if (not self.scope): return True self.rate = self.get_rate() (sel...
.parametrize('pt,on_curve,is_infinity', [(G1, True, False), (multiply(G1, 5), True, False), (Z1, True, True), ((FQ(5566), FQ(5566), FQ.one()), False, None)]) def test_G1_compress_and_decompress_flags(pt, on_curve, is_infinity): assert (on_curve == is_on_curve(pt, b)) z = compress_G1(pt) if on_curve: ...
def delete_single_doctype_from_es(index_name=None, doc_type=None, num_doc_id=None): body = {'query': {'bool': {'must': [{'match': {'type': doc_type}}, {'match': {'doc_id': num_doc_id}}]}}} es_client = create_es_client() es_client.delete_by_query(index=index_name, body=body) logger.info(' Successfully de...
class PredictionCountEvaluator(DatasetEvaluator): def __init__(self, distributed: bool=True): self._distributed = distributed self.prediction_counts = [] self.confidence_scores = [] def reset(self): self.prediction_counts = [] self.confidence_scores = [] def process(s...
def get_main(main_module: tp.Optional[str]=None, package: tp.Optional[str]=None): if (main_module is None): main_module = (os.environ.get('DORA_MAIN_MODULE') or 'train') if (package is None): package = os.environ.get('DORA_PACKAGE') if (package is None): package = _find_packa...
class AnEditor(HasPrivateTraits): code1 = Code() code2 = Code() name = Str('Mike Noggins') address = Str('1313 Drury Lane') shell = PythonValue traits_view = View(VSplit(VGroup('', '|<>'), VGroup('', '|<>'), VGroup('name', 'address'), VGroup('shell', '|{Python Shell}<>'), export='editor', show_l...
class PickBallMode(BaseMode): name = Mode.pick_ball keymap = {Action.quit: False, Action.pick_ball: True, Action.done: False} def enter(self): mouse.mode(MouseMode.RELATIVE) self.closest_ball = None self.register_keymap_event('escape', Action.quit, True) self.register_keymap_...
class AsyncShieldCancellation(): def __init__(self) -> None: self._backend = current_async_library() if (self._backend == 'trio'): self._trio_shield = trio.CancelScope(shield=True) elif (self._backend == 'asyncio'): self._anyio_shield = anyio.CancelScope(shield=True) ...
('cuda.conv2d_bias_few_channels.gen_function') def conv2d_bias_few_channels_gen_function(func_attrs, exec_cond_template, shape_eval_template, shape_save_template): return cba.gen_function(func_attrs=func_attrs, exec_cond_template=exec_cond_template, shape_eval_template=shape_eval_template, shape_save_template=shape...
def get_form_for(command_path: str): try: ctx_and_commands = _get_commands_by_path(command_path) except CommandNotFound as err: return abort(404, str(err)) levels = _generate_form_data(ctx_and_commands) return render_template('command_form.html.j2', levels=levels, command=levels[(- 1)]['...
def loader(dataset, *args, shuffle=False, klass=DataLoader, **kwargs): if (not is_distributed()): return klass(dataset, *args, shuffle=shuffle, **kwargs) if shuffle: sampler = DistributedSampler(dataset) return klass(dataset, *args, **kwargs, sampler=sampler) else: dataset = ...
.parametrize('response,case_sensitive,single_match,gold_spans', [('PER: Jean', False, False, [('jean', 'PER'), ('Jean', 'PER'), ('Jean', 'PER')]), ('PER: Jean', False, True, [('jean', 'PER')]), ('PER: Jean', True, False, [('Jean', 'PER'), ('Jean', 'PER')]), ('PER: Jean', True, True, [('Jean', 'PER')])]) def test_spanca...
class TestBlend(util.ColorAsserts, unittest.TestCase): def test_blend_no_mode(self): c1 = Color('blue').set('alpha', 0.5) c2 = Color('yellow') self.assertEqual(c1.compose(c2, blend='normal'), c1.compose(c2)) def test_blend_different_space(self): c1 = Color('blue').set('alpha', 0....
def read_status(id): connection = False run_records = [] try: connection = psycopg2.connect(**conf.DB_HANDLER_CONFIG, database='test_event_log_storage') cursor = connection.cursor() postgreSQL_select_Query = "\n select event, dagster_event_type, timestamp from event_logs \n ...
def is_arn_filter_match(arn: str, filter_arn: str) -> bool: arn_split = arn.split(':') filter_arn_split = filter_arn.split(':') if (len(arn_split) != len(filter_arn_split)): return False for i in range(0, len(arn_split), 1): if (filter_arn_split[i] and (filter_arn_split[i] != arn_split[i...
class AgentModel(nn.Module): def __init__(self, n_observations, n_actions, n_hidden): super().__init__() self.linear = nn.Linear(n_observations, n_hidden) self.linear2 = nn.Linear(n_hidden, n_actions) def forward(self, frame): z = torch.tanh(self.linear(frame)) score_acti...
def test_A_from_dict(): d = {'terms': {'field': 'tags'}, 'aggs': {'per_author': {'terms': {'field': 'author.raw'}}}} a = aggs.A(d) assert isinstance(a, aggs.Terms) assert (a._params == {'field': 'tags', 'aggs': {'per_author': aggs.A('terms', field='author.raw')}}) assert (a['per_author'] == aggs.A('...
def sstore(evm: Evm) -> None: key = pop(evm.stack).to_be_bytes32() new_value = pop(evm.stack) ensure((evm.gas_left > GAS_CALL_STIPEND), OutOfGasError) original_value = get_storage_original(evm.env.state, evm.message.current_target, key) current_value = get_storage(evm.env.state, evm.message.current_...
def scan_binary(apkfile): logging.info(_('Scanning APK with dexdump for known non-free classes.')) result = get_embedded_classes(apkfile) (problems, warnings) = (0, 0) for classname in result: for (suspect, regexp) in _get_tool().regexs['warn_code_signatures'].items(): if regexp.matc...
class TestMain(BasePyTestCase): def setup_method(self, method): super().setup_method(method) self.compose_dir = tempfile.mkdtemp() def teardown_method(self, method): shutil.rmtree(self.compose_dir) super().teardown_method(method) ('bodhi.server.tasks.clean_old_composes.log') ...
class JsIterable(): def __init__(self, iterable: Union[(primitives.JsDataModel, str)], options: Optional[dict]=None, profile: Optional[Union[(dict, bool)]]=None): self.__js_it = iterable self.options = {'var': 'x', 'type': 'in'} if (options is not None): self.options.update(optio...
def generateActF3(iterationsMap, iteration, t): msg = generateGenericMessage('EiffelActivityFinishedEvent', t, '1.0.0', 'ActF3', iteration) link(msg, iterationsMap[iteration]['ActT3'], 'ACTIVITY_EXECUTION') msg['data']['outcome'] = {'conclusion': getOutcomeValuesFromVerdicts([iterationsMap[iteration]['TSF1'...
class TrackTitleFormatPreference(widgets.ComboEntryPreference): name = 'plugin/minimode/track_title_format' completion_items = {'$tracknumber': _('Track number'), '$title': _('Title'), '$artist': _('Artist'), '$composer': _('Composer'), '$album': _('Album'), '$__length': _('Length'), '$discnumber': _('Disc numb...
class InteractiveItem(QGraphicsRectItem): def __init__(self, *arg, **karg): super().__init__(*arg, **karg) self.node = None self.label = None self.setCursor(QtCore.Qt.PointingHandCursor) self.setAcceptsHoverEvents(True) def hoverEnterEvent(self, e): if (not self.l...
class Selection(OrderOrSelection): def __init__(self, kwargs, remapping=None): self.remapping = build_remapping(remapping) class InList(): def __init__(self, lst): self.first = True self.lst = lst def __call__(self, x): if (self...
def extractCnobsessionsWordpressCom(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...
class FalseNode(ConditionalNode): def __str__(self) -> str: return 'FalseNode' def __repr__(self) -> str: return f'''FalseNode({self.reaching_condition}) {(type(self.child) if self.child else '')}''' def copy(self) -> FalseNode: return FalseNode(self.reaching_condition) def branc...
def test_place_electrodes_equal_spacing(): mesh_obj = load_mesh((parent_dir + '/data/Rectangle.STL')) plotting_obj = {} electrode_nodes = place_electrodes_equal_spacing(mesh_obj, n_electrodes=8, starting_angle=np.pi, starting_offset=0, output_obj=plotting_obj) ccw_electrode_nodes = place_electrodes_equa...
class AsnDB(): __instance = None asndb = None def instance(): if (AsnDB.__instance == None): AsnDB.__instance = AsnDB() return AsnDB.__instance def __init__(self): self.ASN_AVAILABLE = True self.load() def is_available(self): return self.ASN_AVAILA...
class GptAgent(BaseAgent): _system_prompt: str _full_message_history: List[dict] = [] _message_tokens: List[int] = [] def __init__(self, caller_context: CallerContext): super().__init__(caller_context) self._system_prompt = _generate_first_prompt() logger.debug(f'Using GptAgent, ...
.parametrize('filename, expected_format', (list(files_formats.items()) + [(pathlib.Path('README.md'), 'unknown')])) def test_detect_fformat_suffix_only(testpath, filename, expected_format): xtgeo_file = xtgeo._XTGeoFile((testpath / filename)) assert (xtgeo_file.detect_fformat(suffixonly=True) == expected_format...
def filter_firewall_region_data(json): option_list = ['city', 'id', 'name'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictionary[attribute] = json[attribute] return dictionary
class OptionPlotoptionsArcdiagramSonificationDefaultspeechoptionsActivewhen(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...
class PublishedAwardFinancial(): def __init__(self, submission_attributes, db_cursor, chunk_size): self.submission_attributes = submission_attributes self.db_cursor = db_cursor self.chunk_size = chunk_size _property def count(self): sql = f'select count(*) {self.get_from_wher...
def test_should_guess_all_matching_statements(): input_policy = PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('autoscaling', 'DescribeLaunchConfigurations')], Resource=['*']), Statement(Effect='Allow', Action=[Action('sts', 'AssumeRole')], Resource=['arn:aws:iam:::role/som...
def StockCutter1D(child_rolls, parent_rolls, output_json=True, large_model=True): parent_width = parent_rolls[0][1] if (not checkWidths(demands=child_rolls, parent_width=parent_width)): return [] print('child_rolls', child_rolls) print('parent_rolls', parent_rolls) if (not large_model): ...
def test_form_and_submission_deletion(client, msend): r = client.post('/register', data={'email': '', 'password': 'friend'}) assert (r.status_code == 302) assert (1 == User.query.count()) user = User.query.filter_by(email='').first() user.plan = Plan.gold DB.session.add(user) DB.session.comm...
class OptionPlotoptionsStreamgraphZones(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(None) def color(self, text: str): self._config(text, js_type=Fal...
def push_wire_types_data(uclass): if (uclass.virtual or (not uclass.has_type_members)): return None type_members_by_version = {} for (version, ofclass) in sorted(uclass.version_classes.items()): pwtms = [] for m in ofclass.members: if isinstance(m, ir.OFTypeMember): ...
class Session(): session_id: int _active: bool _stream_id_to_stream_desc: Dict _stream_id_to_batch_num: DefaultDict def __init__(self, session_id: int, enums: object): self.session_id = session_id self.enums = enums self._active = True self._stream_id_to_batch_num = d...
class VisualizationEvaluator(DatasetEvaluator): _counter = 0 def __init__(self, cfg, tbx_writer, dataset_mapper, dataset_name, train_iter=None, tag_postfix=None, visualizer: Optional[Type[VisualizerWrapper]]=None): self.tbx_writer = tbx_writer self.dataset_mapper = dataset_mapper self.da...
class OptionSeriesLineSonificationTracksMappingVolume(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._conf...
def cmd_error(obj, fun_name, exc): if ((exc is None) or (not isinstance(exc, CmdError))): exc = CmdError(Cmd.ERR_UNKNOWN, CmdError.exception_to_string(exc, debug=obj.verbose)) response = exc.cmd_output() try: obj.cleanup(fun_name, response) except Exception as e: obj.log(('Cleanu...
.parametrize('rng_seed', np.arange(0, 15)) def test_graphene(rng_seed, log_capture): rng = default_rng(rng_seed) gamma_min = GRAPHENE_GAMMA_MIN gamma_max = GRAPHENE_GAMMA_MAX mu_min = GRAPHENE_MU_C_MIN mu_max = GRAPHENE_MU_C_MAX temp_min = GRAPHENE_TEMP_MIN temp_max = GRAPHENE_TEMP_MAX f...
def test_basic_forwarding3(golden): def filter1D(ow: size, kw: size, x: f32[((ow + kw) - 1)], y: f32[ow], w: f32[kw]): for o in seq(0, ow): sum: f32 sum = 0.0 for k in seq(0, kw): sum += (x[(o + k)] * w[k]) y[o] = sum filter1D = divide_loop...
class OptionZaxisTitle(Options): def align(self): return self._config_get('middle') def align(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, js_type=False) def marg...
def export_registry(plugin, args, opts_parser, registry): cmds = registry.get_all_commands() commands = [] for cmd in cmds: if cmd.built_in: continue inspection = cmd.metadata if isinstance(inspection, FunctionInspection): commands.append(_fn_to_dict(inspectio...
def get_data_after_challenge() -> list[dict[(str, int)]]: data: list[dict[(str, int)]] = [] val_22 = next_int_len(4) data.append(val_22) gv_69 = next_int_len(4) data.append(gv_69) val_54 = next_int_len(4) data.append(val_54) val_118 = next_int_len(4) data.append(val_118) for _ in...
def test_custom_form_base(): (app, db, admin) = setup() class TestForm(form.BaseForm): pass (Model1, _) = create_models(db) view = CustomModelView(Model1, form_base_class=TestForm) admin.add_view(view) assert hasattr(view._create_form_class, 'test1') create_form = view.create_form() ...
def map_vae(pt_module, device='cuda', dtype='float16'): if (not isinstance(pt_module, dict)): pt_params = dict(pt_module.named_parameters()) else: pt_params = pt_module params_ait = {} for (key, arr) in pt_params.items(): if key.startswith('encoder'): continue ...
def test_GlyphSet_writeGlyph_formatVersion(tmp_path): src = GlyphSet(GLYPHSETDIR) dst = GlyphSet(tmp_path, ufoFormatVersion=(2, 0)) glyph = src['A'] dst.writeGlyph('A', glyph) glif = dst.getGLIF('A') assert (b'format="1"' in glif) assert (b'formatMinor' not in glif) with pytest.raises(Un...
class LoggingAddressAndPort(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 {'address': (str,), 'port':...
class PlayerWidget(QFrame): time_mode_remain_changed_signal = pyqtSignal(bool) def __init__(self, player_number, parent): super().__init__(parent) self.setObjectName('PlayerFrame') self.setProperty('on_air', False) self.setStyleSheet('#PlayerFrame { border: 3px solid white; } #Pl...
class TestSystem(): def test_system_valid(self) -> None: assert System(description='Test Policy', egress=[DataFlow(fides_key='test_system_2', type='system', data_categories=[])], fides_key='test_system', ingress=[DataFlow(fides_key='test_system_3', type='system', data_categories=[])], meta={'some': 'meta st...
class OptionSeriesScatter3dSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionSeriesScatter3dSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionSeriesScatter3dSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) -> 'OptionSeri...
def test_point_in_tetrahedron(): vert = [0, 0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 2] assert (xcalc.point_in_tetrahedron(0, 0, 0, vert) is True) assert (xcalc.point_in_tetrahedron((- 1), 0, 0, vert) is False) assert (xcalc.point_in_tetrahedron(2, 1, 0, vert) is True) assert (xcalc.point_in_tetrahedron(0, 2, ...
.skipif(sys.platform.startswith('darwin'), reason='Flaky bash mock on mac') def test_ecl100_retries_once_on_license_failure(tmp_path, monkeypatch): mock_eclipse_path = (tmp_path / 'mock_eclipse100') with open((tmp_path / 'mock_config.yaml'), 'w', encoding='utf-8') as fp: yaml.dump({'versions': {'2015.2'...
def get_venv_status(rootdir): fskind = _fs.check_file(rootdir) if (not fskind): return ('missing', None) elif (fskind not in ('dir', 'dir symlink')): return ('not-dir', fskind) elif (not resolve_venv_file(rootdir, 'bin', 'python', checkexists='exe')): return ('invalid', fskind) ...
class OptionSeriesWindbarbDatalabels(Options): def align(self): return self._config_get('undefined') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config(flag,...
class OFConfigClient(app_manager.RyuApp): def __init__(self, *args, **kwargs): super(OFConfigClient, self).__init__(*args, **kwargs) self.switch = capable_switch.OFCapableSwitch(host=HOST, port=PORT, username=USERNAME, password=PASSWORD, unknown_host_cb=(lambda host, fingeprint: True)) hub.s...
class OptionPlotoptionsPackedbubbleSonificationDefaultinstrumentoptionsMappingVolume(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,...
class SignatureTestingMeta(): META_FIELDS = ['software_name', 'open_source', 'website', 'description'] missing_meta_fields = [] def check_meta_fields(self, sig_path: Path): for file in sig_path.iterdir(): self.check_for_file(file) return self.missing_meta_fields def check_for...
def get_solar_capacity_at(date: datetime) -> float: historical_capacities = pd.DataFrame.from_records([('2015-01-01', 1393), ('2016-01-01', 1646), ('2017-01-01', 1859), ('2018-01-01', 2090), ('2019-01-01', 2375), ('2020-01-01', 2795), ('2021-01-01', 3314), ('2022-01-01', 3904)], columns=['datetime', 'capacity.solar...
def calculate_score(cluster, std_span, std_pos, span, type): if ((std_span == None) or (std_pos == None)): span_deviation_score = 0 pos_deviation_score = 0 else: span_deviation_score = (1 - min(1, (std_span / span))) pos_deviation_score = (1 - min(1, (std_pos / span))) if (ty...
class KiwoomOpenApiPlusService(): def Call(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/koapy.backend.kiwoom_open_api_plus.grpc.Kiwoom...
class FileInterface(Interface): def __init__(self, config): Interface.__init__(self, config) def _adapt_dir_path(self, directory): return directory def _adapt_ext_path(self, directory): return directory def _extended_directory_check(self, directory): return def _setup...
class Identity(): __slots__ = ('_name', '_address', '_public_key', '_public_keys', '_addresses', '_default_address_key') def __init__(self, name: SimpleIdOrStr, address: Optional[str]=None, public_key: Optional[str]=None, addresses: Optional[Dict[(str, Address)]]=None, public_keys: Optional[Dict[(str, str)]]=No...
class SACRunner(TrainingRunner): eval_concurrency: int initial_demonstration_trajectories: DictConfig def __post_init__(self): if (self.eval_concurrency <= 0): self.eval_concurrency = query_cpu() (TrainingRunner) def setup(self, cfg: DictConfig) -> None: super().setup(cfg...